2 * Perform PPPoE discovery
4 * Copyright (C) 2000-2001 by Roaring Penguin Software Inc.
5 * Copyright (C) 2004 Marco d'Itri <md@linux.it>
7 * This program may be distributed according to the terms of the GNU
8 * General Public License, version 2 or (at your option) any later version.
26 #ifdef HAVE_NETPACKET_PACKET_H
27 #include <netpacket/packet.h>
28 #elif defined(HAVE_LINUX_IF_PACKET_H)
29 #include <linux/if_packet.h>
32 #ifdef HAVE_NET_ETHERNET_H
33 #include <net/ethernet.h>
36 #ifdef HAVE_ASM_TYPES_H
37 #include <asm/types.h>
40 #ifdef HAVE_SYS_IOCTL_H
41 #include <sys/ioctl.h>
48 #ifdef HAVE_NET_IF_ARP_H
49 #include <net/if_arp.h>
52 char *xstrdup(const char *s);
60 void error(char *fmt, ...)
64 vfprintf(stderr, fmt, pvar);
68 /* Initialize frame types to RFC 2516 values. Some broken peers apparently
69 use different frame types... sigh... */
71 UINT16_t Eth_PPPOE_Discovery = ETH_PPPOE_DISCOVERY;
72 UINT16_t Eth_PPPOE_Session = ETH_PPPOE_SESSION;
74 /**********************************************************************
77 * packet -- a received PPPoE packet
79 * ethernet packet type (see /usr/include/net/ethertypes.h)
81 * Checks the ethernet packet header to determine its type.
82 * We should only be receveing DISCOVERY and SESSION types if the BPF
83 * is set up correctly. Logs an error if an unexpected type is received.
84 * Note that the ethernet type names come from "pppoe.h" and the packet
85 * packet structure names use the LINUX dialect to maintain consistency
86 * with the rest of this file. See the BSD section of "pppoe.h" for
87 * translations of the data structure names.
88 ***********************************************************************/
90 etherType(PPPoEPacket *packet)
92 UINT16_t type = (UINT16_t) ntohs(packet->ethHdr.h_proto);
93 if (type != Eth_PPPOE_Discovery && type != Eth_PPPOE_Session) {
94 fprintf(stderr, "Invalid ether type 0x%x\n", type);
99 /**********************************************************************
100 *%FUNCTION: openInterface
102 * ifname -- name of interface
103 * type -- Ethernet frame type
104 * hwaddr -- if non-NULL, set to the hardware address
106 * A raw socket for talking to the Ethernet card. Exits on error.
108 * Opens a raw Ethernet socket
109 ***********************************************************************/
111 openInterface(char const *ifname, UINT16_t type, unsigned char *hwaddr)
118 #ifdef HAVE_STRUCT_SOCKADDR_LL
119 struct sockaddr_ll sa;
124 memset(&sa, 0, sizeof(sa));
126 #ifdef HAVE_STRUCT_SOCKADDR_LL
134 if ((fd = socket(domain, stype, htons(type))) < 0) {
135 /* Give a more helpful message for the common error case */
136 if (errno == EPERM) {
137 rp_fatal("Cannot create raw socket -- pppoe must be run as root.");
142 if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &optval, sizeof(optval)) < 0) {
143 fatalSys("setsockopt");
146 /* Fill in hardware address */
148 strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
149 if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
150 fatalSys("ioctl(SIOCGIFHWADDR)");
152 memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
154 if (ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) {
156 sprintf(buffer, "Interface %.16s is not Ethernet", ifname);
160 if (NOT_UNICAST(hwaddr)) {
163 "Interface %.16s has broadcast/multicast MAC address??",
169 /* Sanity check on MTU */
170 strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
171 if (ioctl(fd, SIOCGIFMTU, &ifr) < 0) {
172 fatalSys("ioctl(SIOCGIFMTU)");
174 if (ifr.ifr_mtu < ETH_DATA_LEN) {
175 fprintf(stderr, "Interface %.16s has MTU of %d -- should be %d.\n",
176 ifname, ifr.ifr_mtu, ETH_DATA_LEN);
177 fprintf(stderr, "You may have serious connection problems.\n");
180 #ifdef HAVE_STRUCT_SOCKADDR_LL
181 /* Get interface index */
182 sa.sll_family = AF_PACKET;
183 sa.sll_protocol = htons(type);
185 strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
186 ifr.ifr_name[IFNAMSIZ - 1] = 0;
187 if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
188 fatalSys("ioctl(SIOCFIGINDEX): Could not get interface index");
190 sa.sll_ifindex = ifr.ifr_ifindex;
193 strcpy(sa.sa_data, ifname);
196 /* We're only interested in packets on specified interface */
197 if (bind(fd, (struct sockaddr *) &sa, sizeof(sa)) < 0) {
205 /***********************************************************************
206 *%FUNCTION: sendPacket
208 * sock -- socket to send to
209 * pkt -- the packet to transmit
210 * size -- size of packet (in bytes)
212 * 0 on success; -1 on failure
215 ***********************************************************************/
217 sendPacket(PPPoEConnection *conn, int sock, PPPoEPacket *pkt, int size)
219 #if defined(HAVE_STRUCT_SOCKADDR_LL)
220 if (send(sock, pkt, size, 0) < 0) {
221 sysErr("send (sendPacket)");
228 rp_fatal("relay and server not supported on Linux 2.0 kernels");
230 strcpy(sa.sa_data, conn->ifName);
231 if (sendto(sock, pkt, size, 0, &sa, sizeof(sa)) < 0) {
232 sysErr("sendto (sendPacket)");
239 /***********************************************************************
240 *%FUNCTION: receivePacket
242 * sock -- socket to read from
243 * pkt -- place to store the received packet
244 * size -- set to size of packet in bytes
246 * >= 0 if all OK; < 0 if error
249 ***********************************************************************/
251 receivePacket(int sock, PPPoEPacket *pkt, int *size)
253 if ((*size = recv(sock, pkt, sizeof(PPPoEPacket), 0)) < 0) {
254 sysErr("recv (receivePacket)");
260 /**********************************************************************
261 *%FUNCTION: parsePacket
263 * packet -- the PPPoE discovery packet to parse
264 * func -- function called for each tag in the packet
265 * extra -- an opaque data pointer supplied to parsing function
267 * 0 if everything went well; -1 if there was an error
269 * Parses a PPPoE discovery packet, calling "func" for each tag in the packet.
270 * "func" is passed the additional argument "extra".
271 ***********************************************************************/
273 parsePacket(PPPoEPacket *packet, ParseFunc *func, void *extra)
275 UINT16_t len = ntohs(packet->length);
276 unsigned char *curTag;
277 UINT16_t tagType, tagLen;
279 if (PPPOE_VER(packet->vertype) != 1) {
280 fprintf(stderr, "Invalid PPPoE version (%d)\n",
281 PPPOE_VER(packet->vertype));
284 if (PPPOE_TYPE(packet->vertype) != 1) {
285 fprintf(stderr, "Invalid PPPoE type (%d)\n",
286 PPPOE_TYPE(packet->vertype));
290 /* Do some sanity checks on packet */
291 if (len > ETH_JUMBO_LEN - PPPOE_OVERHEAD) { /* 6-byte overhead for PPPoE header */
292 fprintf(stderr, "Invalid PPPoE packet length (%u)\n", len);
296 /* Step through the tags */
297 curTag = packet->payload;
298 while(curTag - packet->payload < len) {
299 /* Alignment is not guaranteed, so do this by hand... */
300 tagType = (curTag[0] << 8) + curTag[1];
301 tagLen = (curTag[2] << 8) + curTag[3];
302 if (tagType == TAG_END_OF_LIST) {
305 if ((curTag - packet->payload) + tagLen + TAG_HDR_SIZE > len) {
306 fprintf(stderr, "Invalid PPPoE tag length (%u)\n", tagLen);
309 func(tagType, tagLen, curTag+TAG_HDR_SIZE, extra);
310 curTag = curTag + TAG_HDR_SIZE + tagLen;
315 /**********************************************************************
316 *%FUNCTION: parseForHostUniq
321 * extra -- user-supplied pointer. This is assumed to be a pointer to int.
325 * If a HostUnique tag is found which matches our PID, sets *extra to 1.
326 ***********************************************************************/
328 parseForHostUniq(UINT16_t type, UINT16_t len, unsigned char *data,
331 PPPoETag *tag = extra;
333 if (type == TAG_HOST_UNIQ && len == ntohs(tag->length))
334 tag->length = memcmp(data, tag->payload, len);
337 /**********************************************************************
338 *%FUNCTION: packetIsForMe
340 * conn -- PPPoE connection info
341 * packet -- a received PPPoE packet
343 * 1 if packet is for this PPPoE daemon; 0 otherwise.
345 * If we are using the Host-Unique tag, verifies that packet contains
346 * our unique identifier.
347 ***********************************************************************/
349 packetIsForMe(PPPoEConnection *conn, PPPoEPacket *packet)
351 PPPoETag hostUniq = conn->hostUniq;
353 /* If packet is not directed to our MAC address, forget it */
354 if (memcmp(packet->ethHdr.h_dest, conn->myEth, ETH_ALEN)) return 0;
356 /* If we're not using the Host-Unique tag, then accept the packet */
357 if (!conn->hostUniq.length) return 1;
359 parsePacket(packet, parseForHostUniq, &hostUniq);
360 return !hostUniq.length;
363 /**********************************************************************
364 *%FUNCTION: parsePADOTags
369 * extra -- extra user data. Should point to a PacketCriteria structure
370 * which gets filled in according to selected AC name and service
375 * Picks interesting tags out of a PADO packet
376 ***********************************************************************/
378 parsePADOTags(UINT16_t type, UINT16_t len, unsigned char *data,
381 struct PacketCriteria *pc = (struct PacketCriteria *) extra;
382 PPPoEConnection *conn = pc->conn;
388 if (conn->printACNames) {
389 printf("Access-Concentrator: %.*s\n", (int) len, data);
391 if (conn->acName && len == strlen(conn->acName) &&
392 !strncmp((char *) data, conn->acName, len)) {
396 case TAG_SERVICE_NAME:
397 pc->seenServiceName = 1;
398 if (conn->printACNames && len > 0) {
399 printf(" Service-Name: %.*s\n", (int) len, data);
401 if (conn->serviceName && len == strlen(conn->serviceName) &&
402 !strncmp((char *) data, conn->serviceName, len)) {
403 pc->serviceNameOK = 1;
407 if (conn->printACNames) {
408 printf("Got a cookie:");
409 /* Print first 20 bytes of cookie */
410 for (i=0; i<len && i < 20; i++) {
411 printf(" %02x", (unsigned) data[i]);
413 if (i < len) printf("...");
416 conn->cookie.type = htons(type);
417 conn->cookie.length = htons(len);
418 memcpy(conn->cookie.payload, data, len);
420 case TAG_RELAY_SESSION_ID:
421 if (conn->printACNames) {
422 printf("Got a Relay-ID:");
423 /* Print first 20 bytes of relay ID */
424 for (i=0; i<len && i < 20; i++) {
425 printf(" %02x", (unsigned) data[i]);
427 if (i < len) printf("...");
430 conn->relayId.type = htons(type);
431 conn->relayId.length = htons(len);
432 memcpy(conn->relayId.payload, data, len);
434 case TAG_SERVICE_NAME_ERROR:
435 if (conn->printACNames) {
436 printf("Got a Service-Name-Error tag: %.*s\n", (int) len, data);
439 case TAG_AC_SYSTEM_ERROR:
440 if (conn->printACNames) {
441 printf("Got a System-Error tag: %.*s\n", (int) len, data);
444 case TAG_GENERIC_ERROR:
445 if (conn->printACNames) {
446 printf("Got a Generic-Error tag: %.*s\n", (int) len, data);
452 /***********************************************************************
455 * conn -- PPPoEConnection structure
459 * Sends a PADI packet
460 ***********************************************************************/
462 sendPADI(PPPoEConnection *conn)
465 unsigned char *cursor = packet.payload;
466 PPPoETag *svc = (PPPoETag *) (&packet.payload);
467 UINT16_t namelen = 0;
470 if (conn->serviceName) {
471 namelen = (UINT16_t) strlen(conn->serviceName);
473 plen = TAG_HDR_SIZE + namelen;
474 CHECK_ROOM(cursor, packet.payload, plen);
476 /* Set destination to Ethernet broadcast address */
477 memset(packet.ethHdr.h_dest, 0xFF, ETH_ALEN);
478 memcpy(packet.ethHdr.h_source, conn->myEth, ETH_ALEN);
480 packet.ethHdr.h_proto = htons(Eth_PPPOE_Discovery);
481 packet.vertype = PPPOE_VER_TYPE(1, 1);
482 packet.code = CODE_PADI;
485 svc->type = TAG_SERVICE_NAME;
486 svc->length = htons(namelen);
487 CHECK_ROOM(cursor, packet.payload, namelen+TAG_HDR_SIZE);
489 if (conn->serviceName) {
490 memcpy(svc->payload, conn->serviceName, strlen(conn->serviceName));
492 cursor += namelen + TAG_HDR_SIZE;
494 /* If we're using Host-Uniq, copy it over */
495 if (conn->hostUniq.length) {
496 int len = ntohs(conn->hostUniq.length);
497 CHECK_ROOM(cursor, packet.payload, len + TAG_HDR_SIZE);
498 memcpy(cursor, &conn->hostUniq, len + TAG_HDR_SIZE);
499 cursor += len + TAG_HDR_SIZE;
500 plen += len + TAG_HDR_SIZE;
503 packet.length = htons(plen);
505 sendPacket(conn, conn->discoverySocket, &packet, (int) (plen + HDR_SIZE));
506 if (conn->debugFile) {
507 dumpPacket(conn->debugFile, &packet, "SENT");
508 fprintf(conn->debugFile, "\n");
509 fflush(conn->debugFile);
513 /**********************************************************************
514 *%FUNCTION: waitForPADO
516 * conn -- PPPoEConnection structure
517 * timeout -- how long to wait (in seconds)
521 * Waits for a PADO packet and copies useful information
522 ***********************************************************************/
524 waitForPADO(PPPoEConnection *conn, int timeout)
532 struct PacketCriteria pc;
534 pc.acNameOK = (conn->acName) ? 0 : 1;
535 pc.serviceNameOK = (conn->serviceName) ? 0 : 1;
537 pc.seenServiceName = 0;
541 if (BPF_BUFFER_IS_EMPTY) {
546 FD_SET(conn->discoverySocket, &readable);
549 r = select(conn->discoverySocket+1, &readable, NULL, NULL, &tv);
550 if (r >= 0 || errno != EINTR) break;
553 perror("select (waitForPADO)");
556 if (r == 0) return; /* Timed out */
560 receivePacket(conn->discoverySocket, &packet, &len);
563 if (ntohs(packet.length) + HDR_SIZE > len) {
564 fprintf(stderr, "Bogus PPPoE length field (%u)\n",
565 (unsigned int) ntohs(packet.length));
570 /* If it's not a Discovery packet, loop again */
571 if (etherType(&packet) != Eth_PPPOE_Discovery) continue;
574 if (conn->debugFile) {
575 dumpPacket(conn->debugFile, &packet, "RCVD");
576 fprintf(conn->debugFile, "\n");
577 fflush(conn->debugFile);
579 /* If it's not for us, loop again */
580 if (!packetIsForMe(conn, &packet)) continue;
582 if (packet.code == CODE_PADO) {
583 if (BROADCAST(packet.ethHdr.h_source)) {
584 fprintf(stderr, "Ignoring PADO packet from broadcast MAC address\n");
587 parsePacket(&packet, parsePADOTags, &pc);
590 if (!pc.seenACName) {
591 fprintf(stderr, "Ignoring PADO packet with no AC-Name tag\n");
594 if (!pc.seenServiceName) {
595 fprintf(stderr, "Ignoring PADO packet with no Service-Name tag\n");
599 if (pc.acNameOK && pc.serviceNameOK) {
600 memcpy(conn->peerEth, packet.ethHdr.h_source, ETH_ALEN);
601 if (conn->printACNames) {
602 printf("AC-Ethernet-Address: %02x:%02x:%02x:%02x:%02x:%02x\n",
603 (unsigned) conn->peerEth[0],
604 (unsigned) conn->peerEth[1],
605 (unsigned) conn->peerEth[2],
606 (unsigned) conn->peerEth[3],
607 (unsigned) conn->peerEth[4],
608 (unsigned) conn->peerEth[5]);
609 printf("--------------------------------------------------\n");
612 conn->discoveryState = STATE_RECEIVED_PADO;
616 } while (conn->discoveryState != STATE_RECEIVED_PADO);
619 /**********************************************************************
620 *%FUNCTION: discovery
622 * conn -- PPPoE connection info structure
626 * Performs the PPPoE discovery phase
627 ***********************************************************************/
629 discovery(PPPoEConnection *conn)
631 int padiAttempts = 0;
632 int timeout = conn->discoveryTimeout;
634 conn->discoverySocket =
635 openInterface(conn->ifName, Eth_PPPOE_Discovery, conn->myEth);
639 if (padiAttempts > conn->discoveryAttempts) {
640 fprintf(stderr, "Timeout waiting for PADO packets\n");
641 close(conn->discoverySocket);
642 conn->discoverySocket = -1;
646 conn->discoveryState = STATE_SENT_PADI;
647 waitForPADO(conn, timeout);
648 } while (!conn->numPADOs);
651 int main(int argc, char *argv[])
654 PPPoEConnection *conn;
656 conn = malloc(sizeof(PPPoEConnection));
660 memset(conn, 0, sizeof(PPPoEConnection));
662 conn->printACNames = 1;
663 conn->discoveryTimeout = PADI_TIMEOUT;
664 conn->discoveryAttempts = MAX_PADI_ATTEMPTS;
666 while ((opt = getopt(argc, argv, "I:D:VUQS:C:W:t:a:h")) > 0) {
669 conn->serviceName = xstrdup(optarg);
672 conn->acName = xstrdup(optarg);
675 if (sscanf(optarg, "%d", &conn->discoveryTimeout) != 1) {
676 fprintf(stderr, "Illegal argument to -t: Should be -t timeout\n");
679 if (conn->discoveryTimeout < 1) {
680 conn->discoveryTimeout = 1;
684 if (sscanf(optarg, "%d", &conn->discoveryAttempts) != 1) {
685 fprintf(stderr, "Illegal argument to -a: Should be -a attempts\n");
688 if (conn->discoveryAttempts < 1) {
689 conn->discoveryAttempts = 1;
693 if(conn->hostUniq.length) {
694 fprintf(stderr, "-U and -W are mutually exclusive\n");
697 pid_t pid = getpid();
698 conn->hostUniq.type = htons(TAG_HOST_UNIQ);
699 conn->hostUniq.length = htons(sizeof(pid));
700 memcpy(conn->hostUniq.payload, &pid, sizeof(pid));
704 if(conn->hostUniq.length) {
705 fprintf(stderr, "-U and -W are mutually exclusive\n");
708 if (!parseHostUniq(optarg, &conn->hostUniq)) {
709 fprintf(stderr, "Invalid host-uniq argument: %s\n", optarg);
714 conn->debugFile = fopen(optarg, "w");
715 if (!conn->debugFile) {
716 fprintf(stderr, "Could not open %s: %s\n",
717 optarg, strerror(errno));
720 fprintf(conn->debugFile, "pppoe-discovery %s\n", RP_VERSION);
723 conn->ifName = xstrdup(optarg);
726 conn->printACNames = 0;
738 /* default interface name */
740 conn->ifName = strdup("eth0");
742 conn->discoverySocket = -1;
743 conn->sessionSocket = -1;
753 void rp_fatal(char const *str)
755 fprintf(stderr, "%s\n", str);
759 void fatalSys(char const *str)
765 void sysErr(char const *str)
770 char *xstrdup(const char *s)
772 register char *ret = strdup(s);
780 fprintf(stderr, "Usage: pppoe-discovery [options]\n");
781 fprintf(stderr, "Options:\n");
782 fprintf(stderr, " -I if_name -- Specify interface (default eth0)\n");
783 fprintf(stderr, " -D filename -- Log debugging information in filename.\n");
785 " -t timeout -- Initial timeout for discovery packets in seconds\n"
786 " -a attempts -- Number of discovery attempts\n"
787 " -V -- Print version and exit.\n"
788 " -Q -- Quit Mode: Do not print access concentrator names\n"
789 " -S name -- Set desired service name.\n"
790 " -C name -- Set desired access concentrator name.\n"
791 " -U -- Use Host-Unique to allow multiple PPPoE sessions.\n"
792 " -W hexvalue -- Set the Host-Unique to the supplied hex string.\n"
793 " -h -- Print usage information.\n");
794 fprintf(stderr, "\nVersion " RP_VERSION "\n");