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 int *val = (int *) extra;
332 if (type == TAG_HOST_UNIQ && len == sizeof(pid_t)) {
334 memcpy(&tmp, data, len);
335 if (tmp == getpid()) {
341 /**********************************************************************
342 *%FUNCTION: packetIsForMe
344 * conn -- PPPoE connection info
345 * packet -- a received PPPoE packet
347 * 1 if packet is for this PPPoE daemon; 0 otherwise.
349 * If we are using the Host-Unique tag, verifies that packet contains
350 * our unique identifier.
351 ***********************************************************************/
353 packetIsForMe(PPPoEConnection *conn, PPPoEPacket *packet)
357 /* If packet is not directed to our MAC address, forget it */
358 if (memcmp(packet->ethHdr.h_dest, conn->myEth, ETH_ALEN)) return 0;
360 /* If we're not using the Host-Unique tag, then accept the packet */
361 if (!conn->hostUniq.length) return 1;
363 parsePacket(packet, parseForHostUniq, &forMe);
367 /**********************************************************************
368 *%FUNCTION: parsePADOTags
373 * extra -- extra user data. Should point to a PacketCriteria structure
374 * which gets filled in according to selected AC name and service
379 * Picks interesting tags out of a PADO packet
380 ***********************************************************************/
382 parsePADOTags(UINT16_t type, UINT16_t len, unsigned char *data,
385 struct PacketCriteria *pc = (struct PacketCriteria *) extra;
386 PPPoEConnection *conn = pc->conn;
392 if (conn->printACNames) {
393 printf("Access-Concentrator: %.*s\n", (int) len, data);
395 if (conn->acName && len == strlen(conn->acName) &&
396 !strncmp((char *) data, conn->acName, len)) {
400 case TAG_SERVICE_NAME:
401 pc->seenServiceName = 1;
402 if (conn->printACNames && len > 0) {
403 printf(" Service-Name: %.*s\n", (int) len, data);
405 if (conn->serviceName && len == strlen(conn->serviceName) &&
406 !strncmp((char *) data, conn->serviceName, len)) {
407 pc->serviceNameOK = 1;
411 if (conn->printACNames) {
412 printf("Got a cookie:");
413 /* Print first 20 bytes of cookie */
414 for (i=0; i<len && i < 20; i++) {
415 printf(" %02x", (unsigned) data[i]);
417 if (i < len) printf("...");
420 conn->cookie.type = htons(type);
421 conn->cookie.length = htons(len);
422 memcpy(conn->cookie.payload, data, len);
424 case TAG_RELAY_SESSION_ID:
425 if (conn->printACNames) {
426 printf("Got a Relay-ID:");
427 /* Print first 20 bytes of relay ID */
428 for (i=0; i<len && i < 20; i++) {
429 printf(" %02x", (unsigned) data[i]);
431 if (i < len) printf("...");
434 conn->relayId.type = htons(type);
435 conn->relayId.length = htons(len);
436 memcpy(conn->relayId.payload, data, len);
438 case TAG_SERVICE_NAME_ERROR:
439 if (conn->printACNames) {
440 printf("Got a Service-Name-Error tag: %.*s\n", (int) len, data);
443 case TAG_AC_SYSTEM_ERROR:
444 if (conn->printACNames) {
445 printf("Got a System-Error tag: %.*s\n", (int) len, data);
448 case TAG_GENERIC_ERROR:
449 if (conn->printACNames) {
450 printf("Got a Generic-Error tag: %.*s\n", (int) len, data);
456 /***********************************************************************
459 * conn -- PPPoEConnection structure
463 * Sends a PADI packet
464 ***********************************************************************/
466 sendPADI(PPPoEConnection *conn)
469 unsigned char *cursor = packet.payload;
470 PPPoETag *svc = (PPPoETag *) (&packet.payload);
471 UINT16_t namelen = 0;
474 if (conn->serviceName) {
475 namelen = (UINT16_t) strlen(conn->serviceName);
477 plen = TAG_HDR_SIZE + namelen;
478 CHECK_ROOM(cursor, packet.payload, plen);
480 /* Set destination to Ethernet broadcast address */
481 memset(packet.ethHdr.h_dest, 0xFF, ETH_ALEN);
482 memcpy(packet.ethHdr.h_source, conn->myEth, ETH_ALEN);
484 packet.ethHdr.h_proto = htons(Eth_PPPOE_Discovery);
485 packet.vertype = PPPOE_VER_TYPE(1, 1);
486 packet.code = CODE_PADI;
489 svc->type = TAG_SERVICE_NAME;
490 svc->length = htons(namelen);
491 CHECK_ROOM(cursor, packet.payload, namelen+TAG_HDR_SIZE);
493 if (conn->serviceName) {
494 memcpy(svc->payload, conn->serviceName, strlen(conn->serviceName));
496 cursor += namelen + TAG_HDR_SIZE;
498 /* If we're using Host-Uniq, copy it over */
499 if (conn->hostUniq.length) {
500 int len = ntohs(conn->hostUniq.length);
501 CHECK_ROOM(cursor, packet.payload, len + TAG_HDR_SIZE);
502 memcpy(cursor, &conn->hostUniq, len + TAG_HDR_SIZE);
503 cursor += len + TAG_HDR_SIZE;
504 plen += len + TAG_HDR_SIZE;
507 packet.length = htons(plen);
509 sendPacket(conn, conn->discoverySocket, &packet, (int) (plen + HDR_SIZE));
510 if (conn->debugFile) {
511 dumpPacket(conn->debugFile, &packet, "SENT");
512 fprintf(conn->debugFile, "\n");
513 fflush(conn->debugFile);
517 /**********************************************************************
518 *%FUNCTION: waitForPADO
520 * conn -- PPPoEConnection structure
521 * timeout -- how long to wait (in seconds)
525 * Waits for a PADO packet and copies useful information
526 ***********************************************************************/
528 waitForPADO(PPPoEConnection *conn, int timeout)
536 struct PacketCriteria pc;
538 pc.acNameOK = (conn->acName) ? 0 : 1;
539 pc.serviceNameOK = (conn->serviceName) ? 0 : 1;
541 pc.seenServiceName = 0;
545 if (BPF_BUFFER_IS_EMPTY) {
550 FD_SET(conn->discoverySocket, &readable);
553 r = select(conn->discoverySocket+1, &readable, NULL, NULL, &tv);
554 if (r >= 0 || errno != EINTR) break;
557 perror("select (waitForPADO)");
560 if (r == 0) return; /* Timed out */
564 receivePacket(conn->discoverySocket, &packet, &len);
567 if (ntohs(packet.length) + HDR_SIZE > len) {
568 fprintf(stderr, "Bogus PPPoE length field (%u)\n",
569 (unsigned int) ntohs(packet.length));
574 /* If it's not a Discovery packet, loop again */
575 if (etherType(&packet) != Eth_PPPOE_Discovery) continue;
578 if (conn->debugFile) {
579 dumpPacket(conn->debugFile, &packet, "RCVD");
580 fprintf(conn->debugFile, "\n");
581 fflush(conn->debugFile);
583 /* If it's not for us, loop again */
584 if (!packetIsForMe(conn, &packet)) continue;
586 if (packet.code == CODE_PADO) {
587 if (BROADCAST(packet.ethHdr.h_source)) {
588 fprintf(stderr, "Ignoring PADO packet from broadcast MAC address\n");
591 parsePacket(&packet, parsePADOTags, &pc);
594 if (!pc.seenACName) {
595 fprintf(stderr, "Ignoring PADO packet with no AC-Name tag\n");
598 if (!pc.seenServiceName) {
599 fprintf(stderr, "Ignoring PADO packet with no Service-Name tag\n");
603 if (pc.acNameOK && pc.serviceNameOK) {
604 memcpy(conn->peerEth, packet.ethHdr.h_source, ETH_ALEN);
605 if (conn->printACNames) {
606 printf("AC-Ethernet-Address: %02x:%02x:%02x:%02x:%02x:%02x\n",
607 (unsigned) conn->peerEth[0],
608 (unsigned) conn->peerEth[1],
609 (unsigned) conn->peerEth[2],
610 (unsigned) conn->peerEth[3],
611 (unsigned) conn->peerEth[4],
612 (unsigned) conn->peerEth[5]);
613 printf("--------------------------------------------------\n");
616 conn->discoveryState = STATE_RECEIVED_PADO;
620 } while (conn->discoveryState != STATE_RECEIVED_PADO);
623 /**********************************************************************
624 *%FUNCTION: discovery
626 * conn -- PPPoE connection info structure
630 * Performs the PPPoE discovery phase
631 ***********************************************************************/
633 discovery(PPPoEConnection *conn)
635 int padiAttempts = 0;
636 int timeout = conn->discoveryTimeout;
638 conn->discoverySocket =
639 openInterface(conn->ifName, Eth_PPPOE_Discovery, conn->myEth);
643 if (padiAttempts > conn->discoveryAttempts) {
644 fprintf(stderr, "Timeout waiting for PADO packets\n");
645 close(conn->discoverySocket);
646 conn->discoverySocket = -1;
650 conn->discoveryState = STATE_SENT_PADI;
651 waitForPADO(conn, timeout);
652 } while (!conn->numPADOs);
655 int main(int argc, char *argv[])
658 PPPoEConnection *conn;
660 conn = malloc(sizeof(PPPoEConnection));
664 memset(conn, 0, sizeof(PPPoEConnection));
666 conn->printACNames = 1;
667 conn->discoveryTimeout = PADI_TIMEOUT;
668 conn->discoveryAttempts = MAX_PADI_ATTEMPTS;
670 while ((opt = getopt(argc, argv, "I:D:VUQS:C:W:t:a:h")) > 0) {
673 conn->serviceName = xstrdup(optarg);
676 conn->acName = xstrdup(optarg);
679 if (sscanf(optarg, "%d", &conn->discoveryTimeout) != 1) {
680 fprintf(stderr, "Illegal argument to -t: Should be -t timeout\n");
683 if (conn->discoveryTimeout < 1) {
684 conn->discoveryTimeout = 1;
688 if (sscanf(optarg, "%d", &conn->discoveryAttempts) != 1) {
689 fprintf(stderr, "Illegal argument to -a: Should be -a attempts\n");
692 if (conn->discoveryAttempts < 1) {
693 conn->discoveryAttempts = 1;
697 if(conn->hostUniq.length) {
698 fprintf(stderr, "-U and -W are mutually exclusive\n");
701 pid_t pid = getpid();
702 conn->hostUniq.type = htons(TAG_HOST_UNIQ);
703 conn->hostUniq.length = htons(sizeof(pid));
704 memcpy(conn->hostUniq.payload, &pid, sizeof(pid));
708 if(conn->hostUniq.length) {
709 fprintf(stderr, "-U and -W are mutually exclusive\n");
712 if (!parseHostUniq(optarg, &conn->hostUniq)) {
713 fprintf(stderr, "Invalid host-uniq argument: %s\n", optarg);
718 conn->debugFile = fopen(optarg, "w");
719 if (!conn->debugFile) {
720 fprintf(stderr, "Could not open %s: %s\n",
721 optarg, strerror(errno));
724 fprintf(conn->debugFile, "pppoe-discovery %s\n", RP_VERSION);
727 conn->ifName = xstrdup(optarg);
730 conn->printACNames = 0;
742 /* default interface name */
744 conn->ifName = strdup("eth0");
746 conn->discoverySocket = -1;
747 conn->sessionSocket = -1;
757 void rp_fatal(char const *str)
759 fprintf(stderr, "%s\n", str);
763 void fatalSys(char const *str)
769 void sysErr(char const *str)
774 char *xstrdup(const char *s)
776 register char *ret = strdup(s);
784 fprintf(stderr, "Usage: pppoe-discovery [options]\n");
785 fprintf(stderr, "Options:\n");
786 fprintf(stderr, " -I if_name -- Specify interface (default eth0)\n");
787 fprintf(stderr, " -D filename -- Log debugging information in filename.\n");
789 " -t timeout -- Initial timeout for discovery packets in seconds\n"
790 " -a attempts -- Number of discovery attempts\n"
791 " -V -- Print version and exit.\n"
792 " -Q -- Quit Mode: Do not print access concentrator names\n"
793 " -S name -- Set desired service name.\n"
794 " -C name -- Set desired access concentrator name.\n"
795 " -U -- Use Host-Unique to allow multiple PPPoE sessions.\n"
796 " -W hexvalue -- Set the Host-Unique to the supplied hex string.\n"
797 " -h -- Print usage information.\n");
798 fprintf(stderr, "\nVersion " RP_VERSION "\n");