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.
30 #ifdef HAVE_NETPACKET_PACKET_H
31 #include <netpacket/packet.h>
32 #elif defined(HAVE_LINUX_IF_PACKET_H)
33 #include <linux/if_packet.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 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) {
155 fatal("Interface %.16s is not Ethernet", ifname);
158 if (NOT_UNICAST(hwaddr)) {
159 fatal("Interface %.16s has broadcast/multicast MAC address??", ifname);
163 /* Sanity check on MTU */
164 strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
165 if (ioctl(fd, SIOCGIFMTU, &ifr) < 0) {
166 fatalSys("ioctl(SIOCGIFMTU)");
168 if (ifr.ifr_mtu < ETH_DATA_LEN) {
169 fprintf(stderr, "Interface %.16s has MTU of %d -- should be %d.\n",
170 ifname, ifr.ifr_mtu, ETH_DATA_LEN);
171 fprintf(stderr, "You may have serious connection problems.\n");
174 #ifdef HAVE_STRUCT_SOCKADDR_LL
175 /* Get interface index */
176 sa.sll_family = AF_PACKET;
177 sa.sll_protocol = htons(type);
179 strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
180 ifr.ifr_name[IFNAMSIZ - 1] = 0;
181 if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
182 fatalSys("ioctl(SIOCFIGINDEX): Could not get interface index");
184 sa.sll_ifindex = ifr.ifr_ifindex;
187 strcpy(sa.sa_data, ifname);
190 /* We're only interested in packets on specified interface */
191 if (bind(fd, (struct sockaddr *) &sa, sizeof(sa)) < 0) {
199 /***********************************************************************
200 *%FUNCTION: sendPacket
202 * sock -- socket to send to
203 * pkt -- the packet to transmit
204 * size -- size of packet (in bytes)
206 * 0 on success; -1 on failure
209 ***********************************************************************/
211 sendPacket(PPPoEConnection *conn, int sock, PPPoEPacket *pkt, int size)
213 #if defined(HAVE_STRUCT_SOCKADDR_LL)
214 if (send(sock, pkt, size, 0) < 0) {
215 fatalSys("send (sendPacket)");
222 fatal("relay and server not supported on Linux 2.0 kernels");
224 strcpy(sa.sa_data, conn->ifName);
225 if (sendto(sock, pkt, size, 0, &sa, sizeof(sa)) < 0) {
226 fatalSys("sendto (sendPacket)");
233 /***********************************************************************
234 *%FUNCTION: receivePacket
236 * sock -- socket to read from
237 * pkt -- place to store the received packet
238 * size -- set to size of packet in bytes
240 * >= 0 if all OK; < 0 if error
243 ***********************************************************************/
245 receivePacket(int sock, PPPoEPacket *pkt, int *size)
247 if ((*size = recv(sock, pkt, sizeof(PPPoEPacket), 0)) < 0) {
248 fatalSys("recv (receivePacket)");
254 /**********************************************************************
255 *%FUNCTION: parsePacket
257 * packet -- the PPPoE discovery packet to parse
258 * func -- function called for each tag in the packet
259 * extra -- an opaque data pointer supplied to parsing function
261 * 0 if everything went well; -1 if there was an error
263 * Parses a PPPoE discovery packet, calling "func" for each tag in the packet.
264 * "func" is passed the additional argument "extra".
265 ***********************************************************************/
267 parsePacket(PPPoEPacket *packet, ParseFunc *func, void *extra)
269 UINT16_t len = ntohs(packet->length);
270 unsigned char *curTag;
271 UINT16_t tagType, tagLen;
273 if (PPPOE_VER(packet->vertype) != 1) {
274 fprintf(stderr, "Invalid PPPoE version (%d)\n",
275 PPPOE_VER(packet->vertype));
278 if (PPPOE_TYPE(packet->vertype) != 1) {
279 fprintf(stderr, "Invalid PPPoE type (%d)\n",
280 PPPOE_TYPE(packet->vertype));
284 /* Do some sanity checks on packet */
285 if (len > ETH_JUMBO_LEN - PPPOE_OVERHEAD) { /* 6-byte overhead for PPPoE header */
286 fprintf(stderr, "Invalid PPPoE packet length (%u)\n", len);
290 /* Step through the tags */
291 curTag = packet->payload;
292 while(curTag - packet->payload < len) {
293 /* Alignment is not guaranteed, so do this by hand... */
294 tagType = (curTag[0] << 8) + curTag[1];
295 tagLen = (curTag[2] << 8) + curTag[3];
296 if (tagType == TAG_END_OF_LIST) {
299 if ((curTag - packet->payload) + tagLen + TAG_HDR_SIZE > len) {
300 fprintf(stderr, "Invalid PPPoE tag length (%u)\n", tagLen);
303 func(tagType, tagLen, curTag+TAG_HDR_SIZE, extra);
304 curTag = curTag + TAG_HDR_SIZE + tagLen;
309 /**********************************************************************
310 *%FUNCTION: parseForHostUniq
315 * extra -- user-supplied pointer. This is assumed to be a pointer to int.
319 * If a HostUnique tag is found which matches our PID, sets *extra to 1.
320 ***********************************************************************/
322 parseForHostUniq(UINT16_t type, UINT16_t len, unsigned char *data,
325 PPPoETag *tag = extra;
327 if (type == TAG_HOST_UNIQ && len == ntohs(tag->length))
328 tag->length = memcmp(data, tag->payload, len);
331 /**********************************************************************
332 *%FUNCTION: packetIsForMe
334 * conn -- PPPoE connection info
335 * packet -- a received PPPoE packet
337 * 1 if packet is for this PPPoE daemon; 0 otherwise.
339 * If we are using the Host-Unique tag, verifies that packet contains
340 * our unique identifier.
341 ***********************************************************************/
343 packetIsForMe(PPPoEConnection *conn, PPPoEPacket *packet)
345 PPPoETag hostUniq = conn->hostUniq;
347 /* If packet is not directed to our MAC address, forget it */
348 if (memcmp(packet->ethHdr.h_dest, conn->myEth, ETH_ALEN)) return 0;
350 /* If we're not using the Host-Unique tag, then accept the packet */
351 if (!conn->hostUniq.length) return 1;
353 parsePacket(packet, parseForHostUniq, &hostUniq);
354 return !hostUniq.length;
357 /**********************************************************************
358 *%FUNCTION: parsePADOTags
363 * extra -- extra user data. Should point to a PacketCriteria structure
364 * which gets filled in according to selected AC name and service
369 * Picks interesting tags out of a PADO packet
370 ***********************************************************************/
372 parsePADOTags(UINT16_t type, UINT16_t len, unsigned char *data,
375 struct PacketCriteria *pc = (struct PacketCriteria *) extra;
376 PPPoEConnection *conn = pc->conn;
382 if (conn->printACNames) {
383 printf("Access-Concentrator: %.*s\n", (int) len, data);
385 if (conn->acName && len == strlen(conn->acName) &&
386 !strncmp((char *) data, conn->acName, len)) {
390 case TAG_SERVICE_NAME:
391 pc->seenServiceName = 1;
392 if (conn->printACNames && len > 0) {
393 printf(" Service-Name: %.*s\n", (int) len, data);
395 if (conn->serviceName && len == strlen(conn->serviceName) &&
396 !strncmp((char *) data, conn->serviceName, len)) {
397 pc->serviceNameOK = 1;
401 if (conn->printACNames) {
402 printf("Got a cookie:");
403 /* Print first 20 bytes of cookie */
404 for (i=0; i<len && i < 20; i++) {
405 printf(" %02x", (unsigned) data[i]);
407 if (i < len) printf("...");
410 conn->cookie.type = htons(type);
411 conn->cookie.length = htons(len);
412 memcpy(conn->cookie.payload, data, len);
414 case TAG_RELAY_SESSION_ID:
415 if (conn->printACNames) {
416 printf("Got a Relay-ID:");
417 /* Print first 20 bytes of relay ID */
418 for (i=0; i<len && i < 20; i++) {
419 printf(" %02x", (unsigned) data[i]);
421 if (i < len) printf("...");
424 conn->relayId.type = htons(type);
425 conn->relayId.length = htons(len);
426 memcpy(conn->relayId.payload, data, len);
428 case TAG_SERVICE_NAME_ERROR:
429 if (conn->printACNames) {
430 printf("Got a Service-Name-Error tag: %.*s\n", (int) len, data);
433 case TAG_AC_SYSTEM_ERROR:
434 if (conn->printACNames) {
435 printf("Got a System-Error tag: %.*s\n", (int) len, data);
438 case TAG_GENERIC_ERROR:
439 if (conn->printACNames) {
440 printf("Got a Generic-Error tag: %.*s\n", (int) len, data);
446 /***********************************************************************
449 * conn -- PPPoEConnection structure
453 * Sends a PADI packet
454 ***********************************************************************/
456 sendPADI(PPPoEConnection *conn)
459 unsigned char *cursor = packet.payload;
460 PPPoETag *svc = (PPPoETag *) (&packet.payload);
461 UINT16_t namelen = 0;
464 if (conn->serviceName) {
465 namelen = (UINT16_t) strlen(conn->serviceName);
467 plen = TAG_HDR_SIZE + namelen;
468 CHECK_ROOM(cursor, packet.payload, plen);
470 /* Set destination to Ethernet broadcast address */
471 memset(packet.ethHdr.h_dest, 0xFF, ETH_ALEN);
472 memcpy(packet.ethHdr.h_source, conn->myEth, ETH_ALEN);
474 packet.ethHdr.h_proto = htons(Eth_PPPOE_Discovery);
475 packet.vertype = PPPOE_VER_TYPE(1, 1);
476 packet.code = CODE_PADI;
479 svc->type = TAG_SERVICE_NAME;
480 svc->length = htons(namelen);
481 CHECK_ROOM(cursor, packet.payload, namelen+TAG_HDR_SIZE);
483 if (conn->serviceName) {
484 memcpy(svc->payload, conn->serviceName, strlen(conn->serviceName));
486 cursor += namelen + TAG_HDR_SIZE;
488 /* If we're using Host-Uniq, copy it over */
489 if (conn->hostUniq.length) {
490 int len = ntohs(conn->hostUniq.length);
491 CHECK_ROOM(cursor, packet.payload, len + TAG_HDR_SIZE);
492 memcpy(cursor, &conn->hostUniq, len + TAG_HDR_SIZE);
493 cursor += len + TAG_HDR_SIZE;
494 plen += len + TAG_HDR_SIZE;
497 packet.length = htons(plen);
499 sendPacket(conn, conn->discoverySocket, &packet, (int) (plen + HDR_SIZE));
500 if (conn->debugFile) {
501 dumpPacket(conn->debugFile, &packet, "SENT");
502 fprintf(conn->debugFile, "\n");
503 fflush(conn->debugFile);
507 /**********************************************************************
508 *%FUNCTION: waitForPADO
510 * conn -- PPPoEConnection structure
511 * timeout -- how long to wait (in seconds)
515 * Waits for a PADO packet and copies useful information
516 ***********************************************************************/
518 waitForPADO(PPPoEConnection *conn, int timeout)
526 struct PacketCriteria pc;
528 pc.acNameOK = (conn->acName) ? 0 : 1;
529 pc.serviceNameOK = (conn->serviceName) ? 0 : 1;
531 pc.seenServiceName = 0;
535 if (BPF_BUFFER_IS_EMPTY) {
540 FD_SET(conn->discoverySocket, &readable);
543 r = select(conn->discoverySocket+1, &readable, NULL, NULL, &tv);
544 if (r >= 0 || errno != EINTR) break;
547 perror("select (waitForPADO)");
550 if (r == 0) return; /* Timed out */
554 receivePacket(conn->discoverySocket, &packet, &len);
557 if (ntohs(packet.length) + HDR_SIZE > len) {
558 fprintf(stderr, "Bogus PPPoE length field (%u)\n",
559 (unsigned int) ntohs(packet.length));
564 /* If it's not a Discovery packet, loop again */
565 if (etherType(&packet) != Eth_PPPOE_Discovery) continue;
568 if (conn->debugFile) {
569 dumpPacket(conn->debugFile, &packet, "RCVD");
570 fprintf(conn->debugFile, "\n");
571 fflush(conn->debugFile);
573 /* If it's not for us, loop again */
574 if (!packetIsForMe(conn, &packet)) continue;
576 if (packet.code == CODE_PADO) {
577 if (BROADCAST(packet.ethHdr.h_source)) {
578 fprintf(stderr, "Ignoring PADO packet from broadcast MAC address\n");
581 parsePacket(&packet, parsePADOTags, &pc);
584 if (!pc.seenACName) {
585 fprintf(stderr, "Ignoring PADO packet with no AC-Name tag\n");
588 if (!pc.seenServiceName) {
589 fprintf(stderr, "Ignoring PADO packet with no Service-Name tag\n");
593 if (pc.acNameOK && pc.serviceNameOK) {
594 memcpy(conn->peerEth, packet.ethHdr.h_source, ETH_ALEN);
595 if (conn->printACNames) {
596 printf("AC-Ethernet-Address: %02x:%02x:%02x:%02x:%02x:%02x\n",
597 (unsigned) conn->peerEth[0],
598 (unsigned) conn->peerEth[1],
599 (unsigned) conn->peerEth[2],
600 (unsigned) conn->peerEth[3],
601 (unsigned) conn->peerEth[4],
602 (unsigned) conn->peerEth[5]);
603 printf("--------------------------------------------------\n");
606 conn->discoveryState = STATE_RECEIVED_PADO;
610 } while (conn->discoveryState != STATE_RECEIVED_PADO);
613 /**********************************************************************
614 *%FUNCTION: discovery
616 * conn -- PPPoE connection info structure
620 * Performs the PPPoE discovery phase
621 ***********************************************************************/
623 discovery(PPPoEConnection *conn)
625 int padiAttempts = 0;
626 int timeout = conn->discoveryTimeout;
628 conn->discoverySocket =
629 openInterface(conn->ifName, Eth_PPPOE_Discovery, conn->myEth);
633 if (padiAttempts > conn->discoveryAttempts) {
634 fprintf(stderr, "Timeout waiting for PADO packets\n");
635 close(conn->discoverySocket);
636 conn->discoverySocket = -1;
640 conn->discoveryState = STATE_SENT_PADI;
641 waitForPADO(conn, timeout);
642 } while (!conn->numPADOs);
645 int main(int argc, char *argv[])
648 PPPoEConnection *conn;
650 conn = malloc(sizeof(PPPoEConnection));
654 memset(conn, 0, sizeof(PPPoEConnection));
656 conn->printACNames = 1;
657 conn->discoveryTimeout = PADI_TIMEOUT;
658 conn->discoveryAttempts = MAX_PADI_ATTEMPTS;
660 while ((opt = getopt(argc, argv, "I:D:VUQS:C:W:t:a:h")) > 0) {
663 conn->serviceName = xstrdup(optarg);
666 conn->acName = xstrdup(optarg);
669 if (sscanf(optarg, "%d", &conn->discoveryTimeout) != 1) {
670 fprintf(stderr, "Illegal argument to -t: Should be -t timeout\n");
673 if (conn->discoveryTimeout < 1) {
674 conn->discoveryTimeout = 1;
678 if (sscanf(optarg, "%d", &conn->discoveryAttempts) != 1) {
679 fprintf(stderr, "Illegal argument to -a: Should be -a attempts\n");
682 if (conn->discoveryAttempts < 1) {
683 conn->discoveryAttempts = 1;
687 if(conn->hostUniq.length) {
688 fprintf(stderr, "-U and -W are mutually exclusive\n");
691 pid_t pid = getpid();
692 conn->hostUniq.type = htons(TAG_HOST_UNIQ);
693 conn->hostUniq.length = htons(sizeof(pid));
694 memcpy(conn->hostUniq.payload, &pid, sizeof(pid));
698 if(conn->hostUniq.length) {
699 fprintf(stderr, "-U and -W are mutually exclusive\n");
702 if (!parseHostUniq(optarg, &conn->hostUniq)) {
703 fprintf(stderr, "Invalid host-uniq argument: %s\n", optarg);
708 conn->debugFile = fopen(optarg, "w");
709 if (!conn->debugFile) {
710 fprintf(stderr, "Could not open %s: %s\n",
711 optarg, strerror(errno));
714 fprintf(conn->debugFile, "pppoe-discovery from pppd %s\n", VERSION);
717 conn->ifName = xstrdup(optarg);
720 conn->printACNames = 0;
732 /* default interface name */
734 conn->ifName = strdup("eth0");
736 conn->discoverySocket = -1;
737 conn->sessionSocket = -1;
747 void fatal(char * fmt, ...)
751 vfprintf(stderr, fmt, ap);
757 void fatalSys(char const *str)
763 char *xstrdup(const char *s)
765 register char *ret = strdup(s);
773 fprintf(stderr, "Usage: pppoe-discovery [options]\n");
774 fprintf(stderr, "Options:\n");
775 fprintf(stderr, " -I if_name -- Specify interface (default eth0)\n");
776 fprintf(stderr, " -D filename -- Log debugging information in filename.\n");
778 " -t timeout -- Initial timeout for discovery packets in seconds\n"
779 " -a attempts -- Number of discovery attempts\n"
780 " -V -- Print version and exit.\n"
781 " -Q -- Quit Mode: Do not print access concentrator names\n"
782 " -S name -- Set desired service name.\n"
783 " -C name -- Set desired access concentrator name.\n"
784 " -U -- Use Host-Unique to allow multiple PPPoE sessions.\n"
785 " -W hexvalue -- Set the Host-Unique to the supplied hex string.\n"
786 " -h -- Print usage information.\n");
787 fprintf(stderr, "\npppoe-discovery from pppd " VERSION "\n");