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>
48 char *xstrdup(const char *s);
56 void error(char *fmt, ...)
60 vfprintf(stderr, fmt, pvar);
64 /* Initialize frame types to RFC 2516 values. Some broken peers apparently
65 use different frame types... sigh... */
67 UINT16_t Eth_PPPOE_Discovery = ETH_PPPOE_DISCOVERY;
68 UINT16_t Eth_PPPOE_Session = ETH_PPPOE_SESSION;
70 /**********************************************************************
73 * packet -- a received PPPoE packet
75 * ethernet packet type (see /usr/include/net/ethertypes.h)
77 * Checks the ethernet packet header to determine its type.
78 * We should only be receveing DISCOVERY and SESSION types if the BPF
79 * is set up correctly. Logs an error if an unexpected type is received.
80 * Note that the ethernet type names come from "pppoe.h" and the packet
81 * packet structure names use the LINUX dialect to maintain consistency
82 * with the rest of this file. See the BSD section of "pppoe.h" for
83 * translations of the data structure names.
84 ***********************************************************************/
86 etherType(PPPoEPacket *packet)
88 UINT16_t type = (UINT16_t) ntohs(packet->ethHdr.h_proto);
89 if (type != Eth_PPPOE_Discovery && type != Eth_PPPOE_Session) {
90 fprintf(stderr, "Invalid ether type 0x%x\n", type);
95 /**********************************************************************
96 *%FUNCTION: openInterface
98 * ifname -- name of interface
99 * type -- Ethernet frame type
100 * hwaddr -- if non-NULL, set to the hardware address
102 * A raw socket for talking to the Ethernet card. Exits on error.
104 * Opens a raw Ethernet socket
105 ***********************************************************************/
107 openInterface(char const *ifname, UINT16_t type, unsigned char *hwaddr)
114 #ifdef HAVE_STRUCT_SOCKADDR_LL
115 struct sockaddr_ll sa;
120 memset(&sa, 0, sizeof(sa));
122 #ifdef HAVE_STRUCT_SOCKADDR_LL
130 if ((fd = socket(domain, stype, htons(type))) < 0) {
131 /* Give a more helpful message for the common error case */
132 if (errno == EPERM) {
133 fatal("Cannot create raw socket -- pppoe must be run as root.");
138 if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &optval, sizeof(optval)) < 0) {
139 fatalSys("setsockopt");
142 /* Fill in hardware address */
144 strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
145 if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
146 fatalSys("ioctl(SIOCGIFHWADDR)");
148 memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
150 if (ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) {
151 fatal("Interface %.16s is not Ethernet", ifname);
154 if (NOT_UNICAST(hwaddr)) {
155 fatal("Interface %.16s has broadcast/multicast MAC address??", ifname);
159 /* Sanity check on MTU */
160 strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
161 if (ioctl(fd, SIOCGIFMTU, &ifr) < 0) {
162 fatalSys("ioctl(SIOCGIFMTU)");
164 if (ifr.ifr_mtu < ETH_DATA_LEN) {
165 fprintf(stderr, "Interface %.16s has MTU of %d -- should be %d.\n",
166 ifname, ifr.ifr_mtu, ETH_DATA_LEN);
167 fprintf(stderr, "You may have serious connection problems.\n");
170 #ifdef HAVE_STRUCT_SOCKADDR_LL
171 /* Get interface index */
172 sa.sll_family = AF_PACKET;
173 sa.sll_protocol = htons(type);
175 strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
176 ifr.ifr_name[IFNAMSIZ - 1] = 0;
177 if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
178 fatalSys("ioctl(SIOCFIGINDEX): Could not get interface index");
180 sa.sll_ifindex = ifr.ifr_ifindex;
183 strcpy(sa.sa_data, ifname);
186 /* We're only interested in packets on specified interface */
187 if (bind(fd, (struct sockaddr *) &sa, sizeof(sa)) < 0) {
195 /***********************************************************************
196 *%FUNCTION: sendPacket
198 * sock -- socket to send to
199 * pkt -- the packet to transmit
200 * size -- size of packet (in bytes)
202 * 0 on success; -1 on failure
205 ***********************************************************************/
207 sendPacket(PPPoEConnection *conn, int sock, PPPoEPacket *pkt, int size)
209 #if defined(HAVE_STRUCT_SOCKADDR_LL)
210 if (send(sock, pkt, size, 0) < 0) {
211 fatalSys("send (sendPacket)");
218 fatal("relay and server not supported on Linux 2.0 kernels");
220 strcpy(sa.sa_data, conn->ifName);
221 if (sendto(sock, pkt, size, 0, &sa, sizeof(sa)) < 0) {
222 fatalSys("sendto (sendPacket)");
229 /***********************************************************************
230 *%FUNCTION: receivePacket
232 * sock -- socket to read from
233 * pkt -- place to store the received packet
234 * size -- set to size of packet in bytes
236 * >= 0 if all OK; < 0 if error
239 ***********************************************************************/
241 receivePacket(int sock, PPPoEPacket *pkt, int *size)
243 if ((*size = recv(sock, pkt, sizeof(PPPoEPacket), 0)) < 0) {
244 fatalSys("recv (receivePacket)");
250 /**********************************************************************
251 *%FUNCTION: parsePacket
253 * packet -- the PPPoE discovery packet to parse
254 * func -- function called for each tag in the packet
255 * extra -- an opaque data pointer supplied to parsing function
257 * 0 if everything went well; -1 if there was an error
259 * Parses a PPPoE discovery packet, calling "func" for each tag in the packet.
260 * "func" is passed the additional argument "extra".
261 ***********************************************************************/
263 parsePacket(PPPoEPacket *packet, ParseFunc *func, void *extra)
265 UINT16_t len = ntohs(packet->length);
266 unsigned char *curTag;
267 UINT16_t tagType, tagLen;
269 if (PPPOE_VER(packet->vertype) != 1) {
270 fprintf(stderr, "Invalid PPPoE version (%d)\n",
271 PPPOE_VER(packet->vertype));
274 if (PPPOE_TYPE(packet->vertype) != 1) {
275 fprintf(stderr, "Invalid PPPoE type (%d)\n",
276 PPPOE_TYPE(packet->vertype));
280 /* Do some sanity checks on packet */
281 if (len > ETH_JUMBO_LEN - PPPOE_OVERHEAD) { /* 6-byte overhead for PPPoE header */
282 fprintf(stderr, "Invalid PPPoE packet length (%u)\n", len);
286 /* Step through the tags */
287 curTag = packet->payload;
288 while(curTag - packet->payload < len) {
289 /* Alignment is not guaranteed, so do this by hand... */
290 tagType = (curTag[0] << 8) + curTag[1];
291 tagLen = (curTag[2] << 8) + curTag[3];
292 if (tagType == TAG_END_OF_LIST) {
295 if ((curTag - packet->payload) + tagLen + TAG_HDR_SIZE > len) {
296 fprintf(stderr, "Invalid PPPoE tag length (%u)\n", tagLen);
299 func(tagType, tagLen, curTag+TAG_HDR_SIZE, extra);
300 curTag = curTag + TAG_HDR_SIZE + tagLen;
305 /**********************************************************************
306 *%FUNCTION: parseForHostUniq
311 * extra -- user-supplied pointer. This is assumed to be a pointer to int.
315 * If a HostUnique tag is found which matches our PID, sets *extra to 1.
316 ***********************************************************************/
318 parseForHostUniq(UINT16_t type, UINT16_t len, unsigned char *data,
321 PPPoETag *tag = extra;
323 if (type == TAG_HOST_UNIQ && len == ntohs(tag->length))
324 tag->length = memcmp(data, tag->payload, len);
327 /**********************************************************************
328 *%FUNCTION: packetIsForMe
330 * conn -- PPPoE connection info
331 * packet -- a received PPPoE packet
333 * 1 if packet is for this PPPoE daemon; 0 otherwise.
335 * If we are using the Host-Unique tag, verifies that packet contains
336 * our unique identifier.
337 ***********************************************************************/
339 packetIsForMe(PPPoEConnection *conn, PPPoEPacket *packet)
341 PPPoETag hostUniq = conn->hostUniq;
343 /* If packet is not directed to our MAC address, forget it */
344 if (memcmp(packet->ethHdr.h_dest, conn->myEth, ETH_ALEN)) return 0;
346 /* If we're not using the Host-Unique tag, then accept the packet */
347 if (!conn->hostUniq.length) return 1;
349 parsePacket(packet, parseForHostUniq, &hostUniq);
350 return !hostUniq.length;
353 /**********************************************************************
354 *%FUNCTION: parsePADOTags
359 * extra -- extra user data. Should point to a PacketCriteria structure
360 * which gets filled in according to selected AC name and service
365 * Picks interesting tags out of a PADO packet
366 ***********************************************************************/
368 parsePADOTags(UINT16_t type, UINT16_t len, unsigned char *data,
371 struct PacketCriteria *pc = (struct PacketCriteria *) extra;
372 PPPoEConnection *conn = pc->conn;
378 if (conn->printACNames) {
379 printf("Access-Concentrator: %.*s\n", (int) len, data);
381 if (conn->acName && len == strlen(conn->acName) &&
382 !strncmp((char *) data, conn->acName, len)) {
386 case TAG_SERVICE_NAME:
387 pc->seenServiceName = 1;
388 if (conn->printACNames && len > 0) {
389 printf(" Service-Name: %.*s\n", (int) len, data);
391 if (conn->serviceName && len == strlen(conn->serviceName) &&
392 !strncmp((char *) data, conn->serviceName, len)) {
393 pc->serviceNameOK = 1;
397 if (conn->printACNames) {
398 printf("Got a cookie:");
399 /* Print first 20 bytes of cookie */
400 for (i=0; i<len && i < 20; i++) {
401 printf(" %02x", (unsigned) data[i]);
403 if (i < len) printf("...");
406 conn->cookie.type = htons(type);
407 conn->cookie.length = htons(len);
408 memcpy(conn->cookie.payload, data, len);
410 case TAG_RELAY_SESSION_ID:
411 if (conn->printACNames) {
412 printf("Got a Relay-ID:");
413 /* Print first 20 bytes of relay ID */
414 for (i=0; i<len && i < 20; i++) {
415 printf(" %02x", (unsigned) data[i]);
417 if (i < len) printf("...");
420 conn->relayId.type = htons(type);
421 conn->relayId.length = htons(len);
422 memcpy(conn->relayId.payload, data, len);
424 case TAG_SERVICE_NAME_ERROR:
425 if (conn->printACNames) {
426 printf("Got a Service-Name-Error tag: %.*s\n", (int) len, data);
429 case TAG_AC_SYSTEM_ERROR:
430 if (conn->printACNames) {
431 printf("Got a System-Error tag: %.*s\n", (int) len, data);
434 case TAG_GENERIC_ERROR:
435 if (conn->printACNames) {
436 printf("Got a Generic-Error tag: %.*s\n", (int) len, data);
442 /***********************************************************************
445 * conn -- PPPoEConnection structure
449 * Sends a PADI packet
450 ***********************************************************************/
452 sendPADI(PPPoEConnection *conn)
455 unsigned char *cursor = packet.payload;
456 PPPoETag *svc = (PPPoETag *) (&packet.payload);
457 UINT16_t namelen = 0;
460 if (conn->serviceName) {
461 namelen = (UINT16_t) strlen(conn->serviceName);
463 plen = TAG_HDR_SIZE + namelen;
464 CHECK_ROOM(cursor, packet.payload, plen);
466 /* Set destination to Ethernet broadcast address */
467 memset(packet.ethHdr.h_dest, 0xFF, ETH_ALEN);
468 memcpy(packet.ethHdr.h_source, conn->myEth, ETH_ALEN);
470 packet.ethHdr.h_proto = htons(Eth_PPPOE_Discovery);
471 packet.vertype = PPPOE_VER_TYPE(1, 1);
472 packet.code = CODE_PADI;
475 svc->type = TAG_SERVICE_NAME;
476 svc->length = htons(namelen);
477 CHECK_ROOM(cursor, packet.payload, namelen+TAG_HDR_SIZE);
479 if (conn->serviceName) {
480 memcpy(svc->payload, conn->serviceName, strlen(conn->serviceName));
482 cursor += namelen + TAG_HDR_SIZE;
484 /* If we're using Host-Uniq, copy it over */
485 if (conn->hostUniq.length) {
486 int len = ntohs(conn->hostUniq.length);
487 CHECK_ROOM(cursor, packet.payload, len + TAG_HDR_SIZE);
488 memcpy(cursor, &conn->hostUniq, len + TAG_HDR_SIZE);
489 cursor += len + TAG_HDR_SIZE;
490 plen += len + TAG_HDR_SIZE;
493 packet.length = htons(plen);
495 sendPacket(conn, conn->discoverySocket, &packet, (int) (plen + HDR_SIZE));
496 if (conn->debugFile) {
497 dumpPacket(conn->debugFile, &packet, "SENT");
498 fprintf(conn->debugFile, "\n");
499 fflush(conn->debugFile);
503 /**********************************************************************
504 *%FUNCTION: waitForPADO
506 * conn -- PPPoEConnection structure
507 * timeout -- how long to wait (in seconds)
511 * Waits for a PADO packet and copies useful information
512 ***********************************************************************/
514 waitForPADO(PPPoEConnection *conn, int timeout)
522 struct PacketCriteria pc;
524 pc.acNameOK = (conn->acName) ? 0 : 1;
525 pc.serviceNameOK = (conn->serviceName) ? 0 : 1;
527 pc.seenServiceName = 0;
531 if (BPF_BUFFER_IS_EMPTY) {
536 FD_SET(conn->discoverySocket, &readable);
539 r = select(conn->discoverySocket+1, &readable, NULL, NULL, &tv);
540 if (r >= 0 || errno != EINTR) break;
543 perror("select (waitForPADO)");
546 if (r == 0) return; /* Timed out */
550 receivePacket(conn->discoverySocket, &packet, &len);
553 if (ntohs(packet.length) + HDR_SIZE > len) {
554 fprintf(stderr, "Bogus PPPoE length field (%u)\n",
555 (unsigned int) ntohs(packet.length));
560 /* If it's not a Discovery packet, loop again */
561 if (etherType(&packet) != Eth_PPPOE_Discovery) continue;
564 if (conn->debugFile) {
565 dumpPacket(conn->debugFile, &packet, "RCVD");
566 fprintf(conn->debugFile, "\n");
567 fflush(conn->debugFile);
569 /* If it's not for us, loop again */
570 if (!packetIsForMe(conn, &packet)) continue;
572 if (packet.code == CODE_PADO) {
573 if (BROADCAST(packet.ethHdr.h_source)) {
574 fprintf(stderr, "Ignoring PADO packet from broadcast MAC address\n");
577 parsePacket(&packet, parsePADOTags, &pc);
580 if (!pc.seenACName) {
581 fprintf(stderr, "Ignoring PADO packet with no AC-Name tag\n");
584 if (!pc.seenServiceName) {
585 fprintf(stderr, "Ignoring PADO packet with no Service-Name tag\n");
589 if (pc.acNameOK && pc.serviceNameOK) {
590 memcpy(conn->peerEth, packet.ethHdr.h_source, ETH_ALEN);
591 if (conn->printACNames) {
592 printf("AC-Ethernet-Address: %02x:%02x:%02x:%02x:%02x:%02x\n",
593 (unsigned) conn->peerEth[0],
594 (unsigned) conn->peerEth[1],
595 (unsigned) conn->peerEth[2],
596 (unsigned) conn->peerEth[3],
597 (unsigned) conn->peerEth[4],
598 (unsigned) conn->peerEth[5]);
599 printf("--------------------------------------------------\n");
602 conn->discoveryState = STATE_RECEIVED_PADO;
606 } while (conn->discoveryState != STATE_RECEIVED_PADO);
609 /**********************************************************************
610 *%FUNCTION: discovery
612 * conn -- PPPoE connection info structure
616 * Performs the PPPoE discovery phase
617 ***********************************************************************/
619 discovery(PPPoEConnection *conn)
621 int padiAttempts = 0;
622 int timeout = conn->discoveryTimeout;
624 conn->discoverySocket =
625 openInterface(conn->ifName, Eth_PPPOE_Discovery, conn->myEth);
629 if (padiAttempts > conn->discoveryAttempts) {
630 fprintf(stderr, "Timeout waiting for PADO packets\n");
631 close(conn->discoverySocket);
632 conn->discoverySocket = -1;
636 conn->discoveryState = STATE_SENT_PADI;
637 waitForPADO(conn, timeout);
638 } while (!conn->numPADOs);
641 int main(int argc, char *argv[])
644 PPPoEConnection *conn;
646 conn = malloc(sizeof(PPPoEConnection));
650 memset(conn, 0, sizeof(PPPoEConnection));
652 conn->printACNames = 1;
653 conn->discoveryTimeout = PADI_TIMEOUT;
654 conn->discoveryAttempts = MAX_PADI_ATTEMPTS;
656 while ((opt = getopt(argc, argv, "I:D:VUQS:C:W:t:a:h")) > 0) {
659 conn->serviceName = xstrdup(optarg);
662 conn->acName = xstrdup(optarg);
665 if (sscanf(optarg, "%d", &conn->discoveryTimeout) != 1) {
666 fprintf(stderr, "Illegal argument to -t: Should be -t timeout\n");
669 if (conn->discoveryTimeout < 1) {
670 conn->discoveryTimeout = 1;
674 if (sscanf(optarg, "%d", &conn->discoveryAttempts) != 1) {
675 fprintf(stderr, "Illegal argument to -a: Should be -a attempts\n");
678 if (conn->discoveryAttempts < 1) {
679 conn->discoveryAttempts = 1;
683 if(conn->hostUniq.length) {
684 fprintf(stderr, "-U and -W are mutually exclusive\n");
687 pid_t pid = getpid();
688 conn->hostUniq.type = htons(TAG_HOST_UNIQ);
689 conn->hostUniq.length = htons(sizeof(pid));
690 memcpy(conn->hostUniq.payload, &pid, sizeof(pid));
694 if(conn->hostUniq.length) {
695 fprintf(stderr, "-U and -W are mutually exclusive\n");
698 if (!parseHostUniq(optarg, &conn->hostUniq)) {
699 fprintf(stderr, "Invalid host-uniq argument: %s\n", optarg);
704 conn->debugFile = fopen(optarg, "w");
705 if (!conn->debugFile) {
706 fprintf(stderr, "Could not open %s: %s\n",
707 optarg, strerror(errno));
710 fprintf(conn->debugFile, "pppoe-discovery from pppd %s\n", VERSION);
713 conn->ifName = xstrdup(optarg);
716 conn->printACNames = 0;
728 /* default interface name */
730 conn->ifName = strdup("eth0");
732 conn->discoverySocket = -1;
733 conn->sessionSocket = -1;
743 void fatal(char * fmt, ...)
747 vfprintf(stderr, fmt, ap);
753 void fatalSys(char const *str)
759 char *xstrdup(const char *s)
761 register char *ret = strdup(s);
769 fprintf(stderr, "Usage: pppoe-discovery [options]\n");
770 fprintf(stderr, "Options:\n");
771 fprintf(stderr, " -I if_name -- Specify interface (default eth0)\n");
772 fprintf(stderr, " -D filename -- Log debugging information in filename.\n");
774 " -t timeout -- Initial timeout for discovery packets in seconds\n"
775 " -a attempts -- Number of discovery attempts\n"
776 " -V -- Print version and exit.\n"
777 " -Q -- Quit Mode: Do not print access concentrator names\n"
778 " -S name -- Set desired service name.\n"
779 " -C name -- Set desired access concentrator name.\n"
780 " -U -- Use Host-Unique to allow multiple PPPoE sessions.\n"
781 " -W hexvalue -- Set the Host-Unique to the supplied hex string.\n"
782 " -h -- Print usage information.\n");
783 fprintf(stderr, "\npppoe-discovery from pppd " VERSION "\n");