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>
50 char *xstrdup(const char *s);
58 void error(char *fmt, ...)
62 vfprintf(stderr, fmt, pvar);
66 /* Initialize frame types to RFC 2516 values. Some broken peers apparently
67 use different frame types... sigh... */
69 UINT16_t Eth_PPPOE_Discovery = ETH_PPPOE_DISCOVERY;
70 UINT16_t Eth_PPPOE_Session = ETH_PPPOE_SESSION;
72 /**********************************************************************
75 * packet -- a received PPPoE packet
77 * ethernet packet type (see /usr/include/net/ethertypes.h)
79 * Checks the ethernet packet header to determine its type.
80 * We should only be receveing DISCOVERY and SESSION types if the BPF
81 * is set up correctly. Logs an error if an unexpected type is received.
82 * Note that the ethernet type names come from "pppoe.h" and the packet
83 * packet structure names use the LINUX dialect to maintain consistency
84 * with the rest of this file. See the BSD section of "pppoe.h" for
85 * translations of the data structure names.
86 ***********************************************************************/
88 etherType(PPPoEPacket *packet)
90 UINT16_t type = (UINT16_t) ntohs(packet->ethHdr.h_proto);
91 if (type != Eth_PPPOE_Discovery && type != Eth_PPPOE_Session) {
92 fprintf(stderr, "Invalid ether type 0x%x\n", type);
97 /**********************************************************************
98 *%FUNCTION: openInterface
100 * ifname -- name of interface
101 * type -- Ethernet frame type
102 * hwaddr -- if non-NULL, set to the hardware address
104 * A raw socket for talking to the Ethernet card. Exits on error.
106 * Opens a raw Ethernet socket
107 ***********************************************************************/
109 openInterface(char const *ifname, UINT16_t type, unsigned char *hwaddr)
116 #ifdef HAVE_STRUCT_SOCKADDR_LL
117 struct sockaddr_ll sa;
122 memset(&sa, 0, sizeof(sa));
124 #ifdef HAVE_STRUCT_SOCKADDR_LL
132 if ((fd = socket(domain, stype, htons(type))) < 0) {
133 /* Give a more helpful message for the common error case */
134 if (errno == EPERM) {
135 fatal("Cannot create raw socket -- pppoe must be run as root.");
140 if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &optval, sizeof(optval)) < 0) {
141 fatalSys("setsockopt");
144 /* Fill in hardware address */
146 strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
147 if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
148 fatalSys("ioctl(SIOCGIFHWADDR)");
150 memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
152 if (ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) {
153 fatal("Interface %.16s is not Ethernet", ifname);
156 if (NOT_UNICAST(hwaddr)) {
157 fatal("Interface %.16s has broadcast/multicast MAC address??", ifname);
161 /* Sanity check on MTU */
162 strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
163 if (ioctl(fd, SIOCGIFMTU, &ifr) < 0) {
164 fatalSys("ioctl(SIOCGIFMTU)");
166 if (ifr.ifr_mtu < ETH_DATA_LEN) {
167 fprintf(stderr, "Interface %.16s has MTU of %d -- should be %d.\n",
168 ifname, ifr.ifr_mtu, ETH_DATA_LEN);
169 fprintf(stderr, "You may have serious connection problems.\n");
172 #ifdef HAVE_STRUCT_SOCKADDR_LL
173 /* Get interface index */
174 sa.sll_family = AF_PACKET;
175 sa.sll_protocol = htons(type);
177 strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
178 ifr.ifr_name[IFNAMSIZ - 1] = 0;
179 if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
180 fatalSys("ioctl(SIOCFIGINDEX): Could not get interface index");
182 sa.sll_ifindex = ifr.ifr_ifindex;
185 strcpy(sa.sa_data, ifname);
188 /* We're only interested in packets on specified interface */
189 if (bind(fd, (struct sockaddr *) &sa, sizeof(sa)) < 0) {
197 /***********************************************************************
198 *%FUNCTION: sendPacket
200 * sock -- socket to send to
201 * pkt -- the packet to transmit
202 * size -- size of packet (in bytes)
204 * 0 on success; -1 on failure
207 ***********************************************************************/
209 sendPacket(PPPoEConnection *conn, int sock, PPPoEPacket *pkt, int size)
211 #if defined(HAVE_STRUCT_SOCKADDR_LL)
212 if (send(sock, pkt, size, 0) < 0) {
213 fatalSys("send (sendPacket)");
220 fatal("relay and server not supported on Linux 2.0 kernels");
222 strcpy(sa.sa_data, conn->ifName);
223 if (sendto(sock, pkt, size, 0, &sa, sizeof(sa)) < 0) {
224 fatalSys("sendto (sendPacket)");
231 /***********************************************************************
232 *%FUNCTION: receivePacket
234 * sock -- socket to read from
235 * pkt -- place to store the received packet
236 * size -- set to size of packet in bytes
238 * >= 0 if all OK; < 0 if error
241 ***********************************************************************/
243 receivePacket(int sock, PPPoEPacket *pkt, int *size)
245 if ((*size = recv(sock, pkt, sizeof(PPPoEPacket), 0)) < 0) {
246 fatalSys("recv (receivePacket)");
252 /**********************************************************************
253 *%FUNCTION: parsePacket
255 * packet -- the PPPoE discovery packet to parse
256 * func -- function called for each tag in the packet
257 * extra -- an opaque data pointer supplied to parsing function
259 * 0 if everything went well; -1 if there was an error
261 * Parses a PPPoE discovery packet, calling "func" for each tag in the packet.
262 * "func" is passed the additional argument "extra".
263 ***********************************************************************/
265 parsePacket(PPPoEPacket *packet, ParseFunc *func, void *extra)
267 UINT16_t len = ntohs(packet->length);
268 unsigned char *curTag;
269 UINT16_t tagType, tagLen;
271 if (PPPOE_VER(packet->vertype) != 1) {
272 fprintf(stderr, "Invalid PPPoE version (%d)\n",
273 PPPOE_VER(packet->vertype));
276 if (PPPOE_TYPE(packet->vertype) != 1) {
277 fprintf(stderr, "Invalid PPPoE type (%d)\n",
278 PPPOE_TYPE(packet->vertype));
282 /* Do some sanity checks on packet */
283 if (len > ETH_JUMBO_LEN - PPPOE_OVERHEAD) { /* 6-byte overhead for PPPoE header */
284 fprintf(stderr, "Invalid PPPoE packet length (%u)\n", len);
288 /* Step through the tags */
289 curTag = packet->payload;
290 while(curTag - packet->payload < len) {
291 /* Alignment is not guaranteed, so do this by hand... */
292 tagType = (curTag[0] << 8) + curTag[1];
293 tagLen = (curTag[2] << 8) + curTag[3];
294 if (tagType == TAG_END_OF_LIST) {
297 if ((curTag - packet->payload) + tagLen + TAG_HDR_SIZE > len) {
298 fprintf(stderr, "Invalid PPPoE tag length (%u)\n", tagLen);
301 func(tagType, tagLen, curTag+TAG_HDR_SIZE, extra);
302 curTag = curTag + TAG_HDR_SIZE + tagLen;
307 /**********************************************************************
308 *%FUNCTION: parseForHostUniq
313 * extra -- user-supplied pointer. This is assumed to be a pointer to int.
317 * If a HostUnique tag is found which matches our PID, sets *extra to 1.
318 ***********************************************************************/
320 parseForHostUniq(UINT16_t type, UINT16_t len, unsigned char *data,
323 PPPoETag *tag = extra;
325 if (type == TAG_HOST_UNIQ && len == ntohs(tag->length))
326 tag->length = memcmp(data, tag->payload, len);
329 /**********************************************************************
330 *%FUNCTION: packetIsForMe
332 * conn -- PPPoE connection info
333 * packet -- a received PPPoE packet
335 * 1 if packet is for this PPPoE daemon; 0 otherwise.
337 * If we are using the Host-Unique tag, verifies that packet contains
338 * our unique identifier.
339 ***********************************************************************/
341 packetIsForMe(PPPoEConnection *conn, PPPoEPacket *packet)
343 PPPoETag hostUniq = conn->hostUniq;
345 /* If packet is not directed to our MAC address, forget it */
346 if (memcmp(packet->ethHdr.h_dest, conn->myEth, ETH_ALEN)) return 0;
348 /* If we're not using the Host-Unique tag, then accept the packet */
349 if (!conn->hostUniq.length) return 1;
351 parsePacket(packet, parseForHostUniq, &hostUniq);
352 return !hostUniq.length;
355 /**********************************************************************
356 *%FUNCTION: parsePADOTags
361 * extra -- extra user data. Should point to a PacketCriteria structure
362 * which gets filled in according to selected AC name and service
367 * Picks interesting tags out of a PADO packet
368 ***********************************************************************/
370 parsePADOTags(UINT16_t type, UINT16_t len, unsigned char *data,
373 struct PacketCriteria *pc = (struct PacketCriteria *) extra;
374 PPPoEConnection *conn = pc->conn;
380 if (pppoe_verbose >= 1) {
381 printf("Access-Concentrator: %.*s\n", (int) len, data);
383 if (conn->acName && len == strlen(conn->acName) &&
384 !strncmp((char *) data, conn->acName, len)) {
388 case TAG_SERVICE_NAME:
389 pc->seenServiceName = 1;
390 if (pppoe_verbose >= 1 && len > 0) {
391 printf(" Service-Name: %.*s\n", (int) len, data);
393 if (conn->serviceName && len == strlen(conn->serviceName) &&
394 !strncmp((char *) data, conn->serviceName, len)) {
395 pc->serviceNameOK = 1;
399 if (pppoe_verbose >= 1) {
400 printf("Got a cookie:");
401 /* Print first 20 bytes of cookie */
402 for (i=0; i<len && i < 20; i++) {
403 printf(" %02x", (unsigned) data[i]);
405 if (i < len) printf("...");
408 conn->cookie.type = htons(type);
409 conn->cookie.length = htons(len);
410 memcpy(conn->cookie.payload, data, len);
412 case TAG_RELAY_SESSION_ID:
413 if (pppoe_verbose >= 1) {
414 printf("Got a Relay-ID:");
415 /* Print first 20 bytes of relay ID */
416 for (i=0; i<len && i < 20; i++) {
417 printf(" %02x", (unsigned) data[i]);
419 if (i < len) printf("...");
422 conn->relayId.type = htons(type);
423 conn->relayId.length = htons(len);
424 memcpy(conn->relayId.payload, data, len);
426 case TAG_SERVICE_NAME_ERROR:
427 if (pppoe_verbose >= 1) {
428 printf("Got a Service-Name-Error tag: %.*s\n", (int) len, data);
431 case TAG_AC_SYSTEM_ERROR:
432 if (pppoe_verbose >= 1) {
433 printf("Got a System-Error tag: %.*s\n", (int) len, data);
436 case TAG_GENERIC_ERROR:
437 if (pppoe_verbose >= 1) {
438 printf("Got a Generic-Error tag: %.*s\n", (int) len, data);
444 /***********************************************************************
447 * conn -- PPPoEConnection structure
451 * Sends a PADI packet
452 ***********************************************************************/
454 sendPADI(PPPoEConnection *conn)
457 unsigned char *cursor = packet.payload;
458 PPPoETag *svc = (PPPoETag *) (&packet.payload);
459 UINT16_t namelen = 0;
462 if (conn->serviceName) {
463 namelen = (UINT16_t) strlen(conn->serviceName);
465 plen = TAG_HDR_SIZE + namelen;
466 CHECK_ROOM(cursor, packet.payload, plen);
468 /* Set destination to Ethernet broadcast address */
469 memset(packet.ethHdr.h_dest, 0xFF, ETH_ALEN);
470 memcpy(packet.ethHdr.h_source, conn->myEth, ETH_ALEN);
472 packet.ethHdr.h_proto = htons(Eth_PPPOE_Discovery);
473 packet.vertype = PPPOE_VER_TYPE(1, 1);
474 packet.code = CODE_PADI;
477 svc->type = TAG_SERVICE_NAME;
478 svc->length = htons(namelen);
479 CHECK_ROOM(cursor, packet.payload, namelen+TAG_HDR_SIZE);
481 if (conn->serviceName) {
482 memcpy(svc->payload, conn->serviceName, strlen(conn->serviceName));
484 cursor += namelen + TAG_HDR_SIZE;
486 /* If we're using Host-Uniq, copy it over */
487 if (conn->hostUniq.length) {
488 int len = ntohs(conn->hostUniq.length);
489 CHECK_ROOM(cursor, packet.payload, len + TAG_HDR_SIZE);
490 memcpy(cursor, &conn->hostUniq, len + TAG_HDR_SIZE);
491 cursor += len + TAG_HDR_SIZE;
492 plen += len + TAG_HDR_SIZE;
495 packet.length = htons(plen);
497 sendPacket(conn, conn->discoverySocket, &packet, (int) (plen + HDR_SIZE));
498 if (conn->debugFile) {
499 dumpPacket(conn->debugFile, &packet, "SENT");
500 fprintf(conn->debugFile, "\n");
501 fflush(conn->debugFile);
505 /**********************************************************************
506 *%FUNCTION: waitForPADO
508 * conn -- PPPoEConnection structure
509 * timeout -- how long to wait (in seconds)
513 * Waits for a PADO packet and copies useful information
514 ***********************************************************************/
516 waitForPADO(PPPoEConnection *conn, int timeout)
524 struct PacketCriteria pc;
526 pc.acNameOK = (conn->acName) ? 0 : 1;
527 pc.serviceNameOK = (conn->serviceName) ? 0 : 1;
529 pc.seenServiceName = 0;
533 if (BPF_BUFFER_IS_EMPTY) {
538 FD_SET(conn->discoverySocket, &readable);
541 r = select(conn->discoverySocket+1, &readable, NULL, NULL, &tv);
542 if (r >= 0 || errno != EINTR) break;
545 perror("select (waitForPADO)");
548 if (r == 0) return; /* Timed out */
552 receivePacket(conn->discoverySocket, &packet, &len);
555 if (ntohs(packet.length) + HDR_SIZE > len) {
556 fprintf(stderr, "Bogus PPPoE length field (%u)\n",
557 (unsigned int) ntohs(packet.length));
562 /* If it's not a Discovery packet, loop again */
563 if (etherType(&packet) != Eth_PPPOE_Discovery) continue;
566 if (conn->debugFile) {
567 dumpPacket(conn->debugFile, &packet, "RCVD");
568 fprintf(conn->debugFile, "\n");
569 fflush(conn->debugFile);
571 /* If it's not for us, loop again */
572 if (!packetIsForMe(conn, &packet)) continue;
574 if (packet.code == CODE_PADO) {
575 if (BROADCAST(packet.ethHdr.h_source)) {
576 fprintf(stderr, "Ignoring PADO packet from broadcast MAC address\n");
579 parsePacket(&packet, parsePADOTags, &pc);
582 if (!pc.seenACName) {
583 fprintf(stderr, "Ignoring PADO packet with no AC-Name tag\n");
586 if (!pc.seenServiceName) {
587 fprintf(stderr, "Ignoring PADO packet with no Service-Name tag\n");
591 if (pc.acNameOK && pc.serviceNameOK) {
592 memcpy(conn->peerEth, packet.ethHdr.h_source, ETH_ALEN);
593 if (pppoe_verbose >= 1) {
594 printf("AC-Ethernet-Address: %02x:%02x:%02x:%02x:%02x:%02x\n",
595 (unsigned) conn->peerEth[0],
596 (unsigned) conn->peerEth[1],
597 (unsigned) conn->peerEth[2],
598 (unsigned) conn->peerEth[3],
599 (unsigned) conn->peerEth[4],
600 (unsigned) conn->peerEth[5]);
601 printf("--------------------------------------------------\n");
604 conn->discoveryState = STATE_RECEIVED_PADO;
608 } while (conn->discoveryState != STATE_RECEIVED_PADO);
611 /**********************************************************************
612 *%FUNCTION: discovery
614 * conn -- PPPoE connection info structure
618 * Performs the PPPoE discovery phase
619 ***********************************************************************/
621 discovery(PPPoEConnection *conn)
623 int padiAttempts = 0;
624 int timeout = conn->discoveryTimeout;
626 conn->discoverySocket =
627 openInterface(conn->ifName, Eth_PPPOE_Discovery, conn->myEth);
631 if (padiAttempts > conn->discoveryAttempts) {
632 fprintf(stderr, "Timeout waiting for PADO packets\n");
633 close(conn->discoverySocket);
634 conn->discoverySocket = -1;
638 conn->discoveryState = STATE_SENT_PADI;
639 waitForPADO(conn, timeout);
640 } while (!conn->numPADOs);
643 int main(int argc, char *argv[])
646 PPPoEConnection *conn;
648 conn = malloc(sizeof(PPPoEConnection));
652 memset(conn, 0, sizeof(PPPoEConnection));
655 conn->discoveryTimeout = PADI_TIMEOUT;
656 conn->discoveryAttempts = MAX_PADI_ATTEMPTS;
658 while ((opt = getopt(argc, argv, "I:D:VUQS:C:W:t:a:h")) > 0) {
661 conn->serviceName = xstrdup(optarg);
664 conn->acName = xstrdup(optarg);
667 if (sscanf(optarg, "%d", &conn->discoveryTimeout) != 1) {
668 fprintf(stderr, "Illegal argument to -t: Should be -t timeout\n");
671 if (conn->discoveryTimeout < 1) {
672 conn->discoveryTimeout = 1;
676 if (sscanf(optarg, "%d", &conn->discoveryAttempts) != 1) {
677 fprintf(stderr, "Illegal argument to -a: Should be -a attempts\n");
680 if (conn->discoveryAttempts < 1) {
681 conn->discoveryAttempts = 1;
685 if(conn->hostUniq.length) {
686 fprintf(stderr, "-U and -W are mutually exclusive\n");
689 pid_t pid = getpid();
690 conn->hostUniq.type = htons(TAG_HOST_UNIQ);
691 conn->hostUniq.length = htons(sizeof(pid));
692 memcpy(conn->hostUniq.payload, &pid, sizeof(pid));
696 if(conn->hostUniq.length) {
697 fprintf(stderr, "-U and -W are mutually exclusive\n");
700 if (!parseHostUniq(optarg, &conn->hostUniq)) {
701 fprintf(stderr, "Invalid host-uniq argument: %s\n", optarg);
706 conn->debugFile = fopen(optarg, "w");
707 if (!conn->debugFile) {
708 fprintf(stderr, "Could not open %s: %s\n",
709 optarg, strerror(errno));
712 fprintf(conn->debugFile, "pppoe-discovery from pppd %s\n", VERSION);
715 conn->ifName = xstrdup(optarg);
730 /* default interface name */
732 conn->ifName = strdup("eth0");
734 conn->discoverySocket = -1;
735 conn->sessionSocket = -1;
745 void fatal(char * fmt, ...)
749 vfprintf(stderr, fmt, ap);
755 void fatalSys(char const *str)
761 char *xstrdup(const char *s)
763 register char *ret = strdup(s);
771 fprintf(stderr, "Usage: pppoe-discovery [options]\n");
772 fprintf(stderr, "Options:\n");
773 fprintf(stderr, " -I if_name -- Specify interface (default eth0)\n");
774 fprintf(stderr, " -D filename -- Log debugging information in filename.\n");
776 " -t timeout -- Initial timeout for discovery packets in seconds\n"
777 " -a attempts -- Number of discovery attempts\n"
778 " -V -- Print version and exit.\n"
779 " -Q -- Quit Mode: Do not print access concentrator names\n"
780 " -S name -- Set desired service name.\n"
781 " -C name -- Set desired access concentrator name.\n"
782 " -U -- Use Host-Unique to allow multiple PPPoE sessions.\n"
783 " -W hexvalue -- Set the Host-Unique to the supplied hex string.\n"
784 " -h -- Print usage information.\n");
785 fprintf(stderr, "\npppoe-discovery from pppd " VERSION "\n");