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_ASM_TYPES_H
33 #include <asm/types.h>
36 #ifdef HAVE_SYS_IOCTL_H
37 #include <sys/ioctl.h>
44 #ifdef HAVE_NET_IF_ARP_H
45 #include <net/if_arp.h>
57 vfprintf(stderr, fmt, pvar);
63 void fatalSys(char const *str)
74 vfprintf(stderr, fmt, pvar);
84 vfprintf(stderr, fmt, pvar);
100 init_pr_log(const char *prefix, int level)
110 pr_log(void *arg, char *fmt, ...)
115 strlcpy(char *dest, const char *src, size_t len)
117 size_t ret = strlen(src);
123 strncpy(dest, src, len - 1);
131 xstrdup(const char *s)
133 char *ret = strdup(s);
142 get_time(struct timeval *tv)
144 return gettimeofday(tv, NULL);
147 /* Initialize frame types to RFC 2516 values. Some broken peers apparently
148 use different frame types... sigh... */
150 UINT16_t Eth_PPPOE_Discovery = ETH_PPPOE_DISCOVERY;
151 UINT16_t Eth_PPPOE_Session = ETH_PPPOE_SESSION;
153 /**********************************************************************
154 *%FUNCTION: etherType
156 * packet -- a received PPPoE packet
158 * ethernet packet type (see /usr/include/net/ethertypes.h)
160 * Checks the ethernet packet header to determine its type.
161 * We should only be receveing DISCOVERY and SESSION types if the BPF
162 * is set up correctly. Logs an error if an unexpected type is received.
163 * Note that the ethernet type names come from "pppoe.h" and the packet
164 * packet structure names use the LINUX dialect to maintain consistency
165 * with the rest of this file. See the BSD section of "pppoe.h" for
166 * translations of the data structure names.
167 ***********************************************************************/
169 etherType(PPPoEPacket *packet)
171 UINT16_t type = (UINT16_t) ntohs(packet->ethHdr.h_proto);
172 if (type != Eth_PPPOE_Discovery && type != Eth_PPPOE_Session) {
173 fprintf(stderr, "Invalid ether type 0x%x\n", type);
178 /**********************************************************************
179 *%FUNCTION: openInterface
181 * ifname -- name of interface
182 * type -- Ethernet frame type
183 * hwaddr -- if non-NULL, set to the hardware address
185 * A raw socket for talking to the Ethernet card. Exits on error.
187 * Opens a raw Ethernet socket
188 ***********************************************************************/
190 openInterface(char const *ifname, UINT16_t type, unsigned char *hwaddr)
197 #ifdef HAVE_STRUCT_SOCKADDR_LL
198 struct sockaddr_ll sa;
203 memset(&sa, 0, sizeof(sa));
205 #ifdef HAVE_STRUCT_SOCKADDR_LL
213 if ((fd = socket(domain, stype, htons(type))) < 0) {
214 /* Give a more helpful message for the common error case */
215 if (errno == EPERM) {
216 fatal("Cannot create raw socket -- pppoe must be run as root.");
221 if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &optval, sizeof(optval)) < 0) {
222 fatalSys("setsockopt");
225 /* Fill in hardware address */
227 strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
228 if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
229 fatalSys("ioctl(SIOCGIFHWADDR)");
231 memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
233 if (ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) {
234 fatal("Interface %.16s is not Ethernet", ifname);
237 if (NOT_UNICAST(hwaddr)) {
238 fatal("Interface %.16s has broadcast/multicast MAC address??", ifname);
242 /* Sanity check on MTU */
243 strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
244 if (ioctl(fd, SIOCGIFMTU, &ifr) < 0) {
245 fatalSys("ioctl(SIOCGIFMTU)");
247 if (ifr.ifr_mtu < ETH_DATA_LEN) {
248 fprintf(stderr, "Interface %.16s has MTU of %d -- should be %d.\n",
249 ifname, ifr.ifr_mtu, ETH_DATA_LEN);
250 fprintf(stderr, "You may have serious connection problems.\n");
253 #ifdef HAVE_STRUCT_SOCKADDR_LL
254 /* Get interface index */
255 sa.sll_family = AF_PACKET;
256 sa.sll_protocol = htons(type);
258 strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
259 ifr.ifr_name[IFNAMSIZ - 1] = 0;
260 if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
261 fatalSys("ioctl(SIOCFIGINDEX): Could not get interface index");
263 sa.sll_ifindex = ifr.ifr_ifindex;
266 strcpy(sa.sa_data, ifname);
269 /* We're only interested in packets on specified interface */
270 if (bind(fd, (struct sockaddr *) &sa, sizeof(sa)) < 0) {
278 /***********************************************************************
279 *%FUNCTION: sendPacket
281 * sock -- socket to send to
282 * pkt -- the packet to transmit
283 * size -- size of packet (in bytes)
285 * 0 on success; -1 on failure
288 ***********************************************************************/
290 sendPacket(PPPoEConnection *conn, int sock, PPPoEPacket *pkt, int size)
292 #if defined(HAVE_STRUCT_SOCKADDR_LL)
293 if (send(sock, pkt, size, 0) < 0) {
294 fatalSys("send (sendPacket)");
301 fatal("relay and server not supported on Linux 2.0 kernels");
303 strcpy(sa.sa_data, conn->ifName);
304 if (sendto(sock, pkt, size, 0, &sa, sizeof(sa)) < 0) {
305 fatalSys("sendto (sendPacket)");
312 /***********************************************************************
313 *%FUNCTION: receivePacket
315 * sock -- socket to read from
316 * pkt -- place to store the received packet
317 * size -- set to size of packet in bytes
319 * >= 0 if all OK; < 0 if error
322 ***********************************************************************/
324 receivePacket(int sock, PPPoEPacket *pkt, int *size)
326 if ((*size = recv(sock, pkt, sizeof(PPPoEPacket), 0)) < 0) {
327 fatalSys("recv (receivePacket)");
333 /**********************************************************************
334 *%FUNCTION: parsePacket
336 * packet -- the PPPoE discovery packet to parse
337 * func -- function called for each tag in the packet
338 * extra -- an opaque data pointer supplied to parsing function
340 * 0 if everything went well; -1 if there was an error
342 * Parses a PPPoE discovery packet, calling "func" for each tag in the packet.
343 * "func" is passed the additional argument "extra".
344 ***********************************************************************/
346 parsePacket(PPPoEPacket *packet, ParseFunc *func, void *extra)
348 UINT16_t len = ntohs(packet->length);
349 unsigned char *curTag;
350 UINT16_t tagType, tagLen;
352 if (PPPOE_VER(packet->vertype) != 1) {
353 fprintf(stderr, "Invalid PPPoE version (%d)\n",
354 PPPOE_VER(packet->vertype));
357 if (PPPOE_TYPE(packet->vertype) != 1) {
358 fprintf(stderr, "Invalid PPPoE type (%d)\n",
359 PPPOE_TYPE(packet->vertype));
363 /* Do some sanity checks on packet */
364 if (len > ETH_JUMBO_LEN - PPPOE_OVERHEAD) { /* 6-byte overhead for PPPoE header */
365 fprintf(stderr, "Invalid PPPoE packet length (%u)\n", len);
369 /* Step through the tags */
370 curTag = packet->payload;
371 while(curTag - packet->payload < len) {
372 /* Alignment is not guaranteed, so do this by hand... */
373 tagType = (curTag[0] << 8) + curTag[1];
374 tagLen = (curTag[2] << 8) + curTag[3];
375 if (tagType == TAG_END_OF_LIST) {
378 if ((curTag - packet->payload) + tagLen + TAG_HDR_SIZE > len) {
379 fprintf(stderr, "Invalid PPPoE tag length (%u)\n", tagLen);
382 func(tagType, tagLen, curTag+TAG_HDR_SIZE, extra);
383 curTag = curTag + TAG_HDR_SIZE + tagLen;
388 /**********************************************************************
389 *%FUNCTION: parseForHostUniq
394 * extra -- user-supplied pointer. This is assumed to be a pointer to int.
398 * If a HostUnique tag is found which matches our PID, sets *extra to 1.
399 ***********************************************************************/
401 parseForHostUniq(UINT16_t type, UINT16_t len, unsigned char *data,
404 PPPoETag *tag = extra;
406 if (type == TAG_HOST_UNIQ && len == ntohs(tag->length))
407 tag->length = memcmp(data, tag->payload, len);
410 /**********************************************************************
411 *%FUNCTION: packetIsForMe
413 * conn -- PPPoE connection info
414 * packet -- a received PPPoE packet
416 * 1 if packet is for this PPPoE daemon; 0 otherwise.
418 * If we are using the Host-Unique tag, verifies that packet contains
419 * our unique identifier.
420 ***********************************************************************/
422 packetIsForMe(PPPoEConnection *conn, PPPoEPacket *packet)
424 PPPoETag hostUniq = conn->hostUniq;
426 /* If packet is not directed to our MAC address, forget it */
427 if (memcmp(packet->ethHdr.h_dest, conn->myEth, ETH_ALEN)) return 0;
429 /* If we're not using the Host-Unique tag, then accept the packet */
430 if (!conn->hostUniq.length) return 1;
432 parsePacket(packet, parseForHostUniq, &hostUniq);
433 return !hostUniq.length;
436 /**********************************************************************
437 *%FUNCTION: parsePADOTags
442 * extra -- extra user data. Should point to a PacketCriteria structure
443 * which gets filled in according to selected AC name and service
448 * Picks interesting tags out of a PADO packet
449 ***********************************************************************/
451 parsePADOTags(UINT16_t type, UINT16_t len, unsigned char *data,
454 struct PacketCriteria *pc = (struct PacketCriteria *) extra;
455 PPPoEConnection *conn = pc->conn;
461 if (pppoe_verbose >= 1) {
462 printf("Access-Concentrator: %.*s\n", (int) len, data);
464 if (conn->acName && len == strlen(conn->acName) &&
465 !strncmp((char *) data, conn->acName, len)) {
469 case TAG_SERVICE_NAME:
470 pc->seenServiceName = 1;
471 if (pppoe_verbose >= 1 && len > 0) {
472 printf(" Service-Name: %.*s\n", (int) len, data);
474 if (conn->serviceName && len == strlen(conn->serviceName) &&
475 !strncmp((char *) data, conn->serviceName, len)) {
476 pc->serviceNameOK = 1;
480 if (pppoe_verbose >= 1) {
481 printf("Got a cookie:");
482 /* Print first 20 bytes of cookie */
483 for (i=0; i<len && i < 20; i++) {
484 printf(" %02x", (unsigned) data[i]);
486 if (i < len) printf("...");
489 conn->cookie.type = htons(type);
490 conn->cookie.length = htons(len);
491 memcpy(conn->cookie.payload, data, len);
493 case TAG_RELAY_SESSION_ID:
494 if (pppoe_verbose >= 1) {
495 printf("Got a Relay-ID:");
496 /* Print first 20 bytes of relay ID */
497 for (i=0; i<len && i < 20; i++) {
498 printf(" %02x", (unsigned) data[i]);
500 if (i < len) printf("...");
503 conn->relayId.type = htons(type);
504 conn->relayId.length = htons(len);
505 memcpy(conn->relayId.payload, data, len);
507 case TAG_SERVICE_NAME_ERROR:
508 if (pppoe_verbose >= 1) {
509 printf("Got a Service-Name-Error tag: %.*s\n", (int) len, data);
512 case TAG_AC_SYSTEM_ERROR:
513 if (pppoe_verbose >= 1) {
514 printf("Got a System-Error tag: %.*s\n", (int) len, data);
517 case TAG_GENERIC_ERROR:
518 if (pppoe_verbose >= 1) {
519 printf("Got a Generic-Error tag: %.*s\n", (int) len, data);
525 /***********************************************************************
528 * conn -- PPPoEConnection structure
532 * Sends a PADI packet
533 ***********************************************************************/
535 sendPADI(PPPoEConnection *conn)
538 unsigned char *cursor = packet.payload;
539 PPPoETag *svc = (PPPoETag *) (&packet.payload);
540 UINT16_t namelen = 0;
543 if (conn->serviceName) {
544 namelen = (UINT16_t) strlen(conn->serviceName);
546 plen = TAG_HDR_SIZE + namelen;
547 CHECK_ROOM(cursor, packet.payload, plen);
549 /* Set destination to Ethernet broadcast address */
550 memset(packet.ethHdr.h_dest, 0xFF, ETH_ALEN);
551 memcpy(packet.ethHdr.h_source, conn->myEth, ETH_ALEN);
553 packet.ethHdr.h_proto = htons(Eth_PPPOE_Discovery);
554 packet.vertype = PPPOE_VER_TYPE(1, 1);
555 packet.code = CODE_PADI;
558 svc->type = TAG_SERVICE_NAME;
559 svc->length = htons(namelen);
560 CHECK_ROOM(cursor, packet.payload, namelen+TAG_HDR_SIZE);
562 if (conn->serviceName) {
563 memcpy(svc->payload, conn->serviceName, strlen(conn->serviceName));
565 cursor += namelen + TAG_HDR_SIZE;
567 /* If we're using Host-Uniq, copy it over */
568 if (conn->hostUniq.length) {
569 int len = ntohs(conn->hostUniq.length);
570 CHECK_ROOM(cursor, packet.payload, len + TAG_HDR_SIZE);
571 memcpy(cursor, &conn->hostUniq, len + TAG_HDR_SIZE);
572 cursor += len + TAG_HDR_SIZE;
573 plen += len + TAG_HDR_SIZE;
576 packet.length = htons(plen);
578 sendPacket(conn, conn->discoverySocket, &packet, (int) (plen + HDR_SIZE));
579 if (conn->debugFile) {
580 dumpPacket(conn->debugFile, &packet, "SENT");
581 fprintf(conn->debugFile, "\n");
582 fflush(conn->debugFile);
586 /**********************************************************************
587 *%FUNCTION: waitForPADO
589 * conn -- PPPoEConnection structure
590 * timeout -- how long to wait (in seconds)
594 * Waits for a PADO packet and copies useful information
595 ***********************************************************************/
597 waitForPADO(PPPoEConnection *conn, int timeout)
605 struct PacketCriteria pc;
607 pc.acNameOK = (conn->acName) ? 0 : 1;
608 pc.serviceNameOK = (conn->serviceName) ? 0 : 1;
610 pc.seenServiceName = 0;
614 if (BPF_BUFFER_IS_EMPTY) {
619 FD_SET(conn->discoverySocket, &readable);
622 r = select(conn->discoverySocket+1, &readable, NULL, NULL, &tv);
623 if (r >= 0 || errno != EINTR) break;
626 perror("select (waitForPADO)");
629 if (r == 0) return; /* Timed out */
633 receivePacket(conn->discoverySocket, &packet, &len);
636 if (ntohs(packet.length) + HDR_SIZE > len) {
637 fprintf(stderr, "Bogus PPPoE length field (%u)\n",
638 (unsigned int) ntohs(packet.length));
643 /* If it's not a Discovery packet, loop again */
644 if (etherType(&packet) != Eth_PPPOE_Discovery) continue;
647 if (conn->debugFile) {
648 dumpPacket(conn->debugFile, &packet, "RCVD");
649 fprintf(conn->debugFile, "\n");
650 fflush(conn->debugFile);
652 /* If it's not for us, loop again */
653 if (!packetIsForMe(conn, &packet)) continue;
655 if (packet.code == CODE_PADO) {
656 if (BROADCAST(packet.ethHdr.h_source)) {
657 fprintf(stderr, "Ignoring PADO packet from broadcast MAC address\n");
660 parsePacket(&packet, parsePADOTags, &pc);
663 if (!pc.seenACName) {
664 fprintf(stderr, "Ignoring PADO packet with no AC-Name tag\n");
667 if (!pc.seenServiceName) {
668 fprintf(stderr, "Ignoring PADO packet with no Service-Name tag\n");
672 if (pc.acNameOK && pc.serviceNameOK) {
673 memcpy(conn->peerEth, packet.ethHdr.h_source, ETH_ALEN);
674 if (pppoe_verbose >= 1) {
675 printf("AC-Ethernet-Address: %02x:%02x:%02x:%02x:%02x:%02x\n",
676 (unsigned) conn->peerEth[0],
677 (unsigned) conn->peerEth[1],
678 (unsigned) conn->peerEth[2],
679 (unsigned) conn->peerEth[3],
680 (unsigned) conn->peerEth[4],
681 (unsigned) conn->peerEth[5]);
682 printf("--------------------------------------------------\n");
685 conn->discoveryState = STATE_RECEIVED_PADO;
689 } while (conn->discoveryState != STATE_RECEIVED_PADO);
692 /**********************************************************************
693 *%FUNCTION: discovery
695 * conn -- PPPoE connection info structure
699 * Performs the PPPoE discovery phase
700 ***********************************************************************/
702 discovery(PPPoEConnection *conn)
704 int padiAttempts = 0;
705 int timeout = conn->discoveryTimeout;
707 conn->discoverySocket =
708 openInterface(conn->ifName, Eth_PPPOE_Discovery, conn->myEth);
712 if (padiAttempts > conn->discoveryAttempts) {
713 fprintf(stderr, "Timeout waiting for PADO packets\n");
714 close(conn->discoverySocket);
715 conn->discoverySocket = -1;
719 conn->discoveryState = STATE_SENT_PADI;
720 waitForPADO(conn, timeout);
721 } while (!conn->numPADOs);
725 term_handler(int signum)
730 static void usage(void);
732 int main(int argc, char *argv[])
735 PPPoEConnection *conn;
737 conn = malloc(sizeof(PPPoEConnection));
741 memset(conn, 0, sizeof(PPPoEConnection));
744 conn->discoveryTimeout = PADI_TIMEOUT;
745 conn->discoveryAttempts = MAX_PADI_ATTEMPTS;
747 while ((opt = getopt(argc, argv, "I:D:VUQS:C:W:t:a:h")) > 0) {
750 conn->serviceName = xstrdup(optarg);
753 conn->acName = xstrdup(optarg);
756 if (sscanf(optarg, "%d", &conn->discoveryTimeout) != 1) {
757 fprintf(stderr, "Illegal argument to -t: Should be -t timeout\n");
760 if (conn->discoveryTimeout < 1) {
761 conn->discoveryTimeout = 1;
765 if (sscanf(optarg, "%d", &conn->discoveryAttempts) != 1) {
766 fprintf(stderr, "Illegal argument to -a: Should be -a attempts\n");
769 if (conn->discoveryAttempts < 1) {
770 conn->discoveryAttempts = 1;
774 if(conn->hostUniq.length) {
775 fprintf(stderr, "-U and -W are mutually exclusive\n");
778 pid_t pid = getpid();
779 conn->hostUniq.type = htons(TAG_HOST_UNIQ);
780 conn->hostUniq.length = htons(sizeof(pid));
781 memcpy(conn->hostUniq.payload, &pid, sizeof(pid));
785 if(conn->hostUniq.length) {
786 fprintf(stderr, "-U and -W are mutually exclusive\n");
789 if (!parseHostUniq(optarg, &conn->hostUniq)) {
790 fprintf(stderr, "Invalid host-uniq argument: %s\n", optarg);
795 conn->debugFile = fopen(optarg, "w");
796 if (!conn->debugFile) {
797 fprintf(stderr, "Could not open %s: %s\n",
798 optarg, strerror(errno));
801 fprintf(conn->debugFile, "pppoe-discovery from pppd %s\n", VERSION);
804 conn->ifName = xstrdup(optarg);
819 /* default interface name */
821 conn->ifName = strdup("eth0");
823 conn->discoverySocket = -1;
824 conn->sessionSocket = -1;
837 fprintf(stderr, "Usage: pppoe-discovery [options]\n");
838 fprintf(stderr, "Options:\n");
839 fprintf(stderr, " -I if_name -- Specify interface (default eth0)\n");
840 fprintf(stderr, " -D filename -- Log debugging information in filename.\n");
842 " -t timeout -- Initial timeout for discovery packets in seconds\n"
843 " -a attempts -- Number of discovery attempts\n"
844 " -V -- Print version and exit.\n"
845 " -Q -- Quit Mode: Do not print access concentrator names\n"
846 " -S name -- Set desired service name.\n"
847 " -C name -- Set desired access concentrator name.\n"
848 " -U -- Use Host-Unique to allow multiple PPPoE sessions.\n"
849 " -W hexvalue -- Set the Host-Unique to the supplied hex string.\n"
850 " -h -- Print usage information.\n");
851 fprintf(stderr, "\npppoe-discovery from pppd " VERSION "\n");