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 rp_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) {
152 sprintf(buffer, "Interface %.16s is not Ethernet", ifname);
156 if (NOT_UNICAST(hwaddr)) {
159 "Interface %.16s has broadcast/multicast MAC address??",
165 /* Sanity check on MTU */
166 strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
167 if (ioctl(fd, SIOCGIFMTU, &ifr) < 0) {
168 fatalSys("ioctl(SIOCGIFMTU)");
170 if (ifr.ifr_mtu < ETH_DATA_LEN) {
171 fprintf(stderr, "Interface %.16s has MTU of %d -- should be %d.\n",
172 ifname, ifr.ifr_mtu, ETH_DATA_LEN);
173 fprintf(stderr, "You may have serious connection problems.\n");
176 #ifdef HAVE_STRUCT_SOCKADDR_LL
177 /* Get interface index */
178 sa.sll_family = AF_PACKET;
179 sa.sll_protocol = htons(type);
181 strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
182 ifr.ifr_name[IFNAMSIZ - 1] = 0;
183 if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
184 fatalSys("ioctl(SIOCFIGINDEX): Could not get interface index");
186 sa.sll_ifindex = ifr.ifr_ifindex;
189 strcpy(sa.sa_data, ifname);
192 /* We're only interested in packets on specified interface */
193 if (bind(fd, (struct sockaddr *) &sa, sizeof(sa)) < 0) {
201 /***********************************************************************
202 *%FUNCTION: sendPacket
204 * sock -- socket to send to
205 * pkt -- the packet to transmit
206 * size -- size of packet (in bytes)
208 * 0 on success; -1 on failure
211 ***********************************************************************/
213 sendPacket(PPPoEConnection *conn, int sock, PPPoEPacket *pkt, int size)
215 #if defined(HAVE_STRUCT_SOCKADDR_LL)
216 if (send(sock, pkt, size, 0) < 0) {
217 sysErr("send (sendPacket)");
224 rp_fatal("relay and server not supported on Linux 2.0 kernels");
226 strcpy(sa.sa_data, conn->ifName);
227 if (sendto(sock, pkt, size, 0, &sa, sizeof(sa)) < 0) {
228 sysErr("sendto (sendPacket)");
235 /***********************************************************************
236 *%FUNCTION: receivePacket
238 * sock -- socket to read from
239 * pkt -- place to store the received packet
240 * size -- set to size of packet in bytes
242 * >= 0 if all OK; < 0 if error
245 ***********************************************************************/
247 receivePacket(int sock, PPPoEPacket *pkt, int *size)
249 if ((*size = recv(sock, pkt, sizeof(PPPoEPacket), 0)) < 0) {
250 sysErr("recv (receivePacket)");
256 /**********************************************************************
257 *%FUNCTION: parsePacket
259 * packet -- the PPPoE discovery packet to parse
260 * func -- function called for each tag in the packet
261 * extra -- an opaque data pointer supplied to parsing function
263 * 0 if everything went well; -1 if there was an error
265 * Parses a PPPoE discovery packet, calling "func" for each tag in the packet.
266 * "func" is passed the additional argument "extra".
267 ***********************************************************************/
269 parsePacket(PPPoEPacket *packet, ParseFunc *func, void *extra)
271 UINT16_t len = ntohs(packet->length);
272 unsigned char *curTag;
273 UINT16_t tagType, tagLen;
275 if (PPPOE_VER(packet->vertype) != 1) {
276 fprintf(stderr, "Invalid PPPoE version (%d)\n",
277 PPPOE_VER(packet->vertype));
280 if (PPPOE_TYPE(packet->vertype) != 1) {
281 fprintf(stderr, "Invalid PPPoE type (%d)\n",
282 PPPOE_TYPE(packet->vertype));
286 /* Do some sanity checks on packet */
287 if (len > ETH_JUMBO_LEN - PPPOE_OVERHEAD) { /* 6-byte overhead for PPPoE header */
288 fprintf(stderr, "Invalid PPPoE packet length (%u)\n", len);
292 /* Step through the tags */
293 curTag = packet->payload;
294 while(curTag - packet->payload < len) {
295 /* Alignment is not guaranteed, so do this by hand... */
296 tagType = (curTag[0] << 8) + curTag[1];
297 tagLen = (curTag[2] << 8) + curTag[3];
298 if (tagType == TAG_END_OF_LIST) {
301 if ((curTag - packet->payload) + tagLen + TAG_HDR_SIZE > len) {
302 fprintf(stderr, "Invalid PPPoE tag length (%u)\n", tagLen);
305 func(tagType, tagLen, curTag+TAG_HDR_SIZE, extra);
306 curTag = curTag + TAG_HDR_SIZE + tagLen;
311 /**********************************************************************
312 *%FUNCTION: parseForHostUniq
317 * extra -- user-supplied pointer. This is assumed to be a pointer to int.
321 * If a HostUnique tag is found which matches our PID, sets *extra to 1.
322 ***********************************************************************/
324 parseForHostUniq(UINT16_t type, UINT16_t len, unsigned char *data,
327 PPPoETag *tag = extra;
329 if (type == TAG_HOST_UNIQ && len == ntohs(tag->length))
330 tag->length = memcmp(data, tag->payload, len);
333 /**********************************************************************
334 *%FUNCTION: packetIsForMe
336 * conn -- PPPoE connection info
337 * packet -- a received PPPoE packet
339 * 1 if packet is for this PPPoE daemon; 0 otherwise.
341 * If we are using the Host-Unique tag, verifies that packet contains
342 * our unique identifier.
343 ***********************************************************************/
345 packetIsForMe(PPPoEConnection *conn, PPPoEPacket *packet)
347 PPPoETag hostUniq = conn->hostUniq;
349 /* If packet is not directed to our MAC address, forget it */
350 if (memcmp(packet->ethHdr.h_dest, conn->myEth, ETH_ALEN)) return 0;
352 /* If we're not using the Host-Unique tag, then accept the packet */
353 if (!conn->hostUniq.length) return 1;
355 parsePacket(packet, parseForHostUniq, &hostUniq);
356 return !hostUniq.length;
359 /**********************************************************************
360 *%FUNCTION: parsePADOTags
365 * extra -- extra user data. Should point to a PacketCriteria structure
366 * which gets filled in according to selected AC name and service
371 * Picks interesting tags out of a PADO packet
372 ***********************************************************************/
374 parsePADOTags(UINT16_t type, UINT16_t len, unsigned char *data,
377 struct PacketCriteria *pc = (struct PacketCriteria *) extra;
378 PPPoEConnection *conn = pc->conn;
384 if (conn->printACNames) {
385 printf("Access-Concentrator: %.*s\n", (int) len, data);
387 if (conn->acName && len == strlen(conn->acName) &&
388 !strncmp((char *) data, conn->acName, len)) {
392 case TAG_SERVICE_NAME:
393 pc->seenServiceName = 1;
394 if (conn->printACNames && len > 0) {
395 printf(" Service-Name: %.*s\n", (int) len, data);
397 if (conn->serviceName && len == strlen(conn->serviceName) &&
398 !strncmp((char *) data, conn->serviceName, len)) {
399 pc->serviceNameOK = 1;
403 if (conn->printACNames) {
404 printf("Got a cookie:");
405 /* Print first 20 bytes of cookie */
406 for (i=0; i<len && i < 20; i++) {
407 printf(" %02x", (unsigned) data[i]);
409 if (i < len) printf("...");
412 conn->cookie.type = htons(type);
413 conn->cookie.length = htons(len);
414 memcpy(conn->cookie.payload, data, len);
416 case TAG_RELAY_SESSION_ID:
417 if (conn->printACNames) {
418 printf("Got a Relay-ID:");
419 /* Print first 20 bytes of relay ID */
420 for (i=0; i<len && i < 20; i++) {
421 printf(" %02x", (unsigned) data[i]);
423 if (i < len) printf("...");
426 conn->relayId.type = htons(type);
427 conn->relayId.length = htons(len);
428 memcpy(conn->relayId.payload, data, len);
430 case TAG_SERVICE_NAME_ERROR:
431 if (conn->printACNames) {
432 printf("Got a Service-Name-Error tag: %.*s\n", (int) len, data);
435 case TAG_AC_SYSTEM_ERROR:
436 if (conn->printACNames) {
437 printf("Got a System-Error tag: %.*s\n", (int) len, data);
440 case TAG_GENERIC_ERROR:
441 if (conn->printACNames) {
442 printf("Got a Generic-Error tag: %.*s\n", (int) len, data);
448 /***********************************************************************
451 * conn -- PPPoEConnection structure
455 * Sends a PADI packet
456 ***********************************************************************/
458 sendPADI(PPPoEConnection *conn)
461 unsigned char *cursor = packet.payload;
462 PPPoETag *svc = (PPPoETag *) (&packet.payload);
463 UINT16_t namelen = 0;
466 if (conn->serviceName) {
467 namelen = (UINT16_t) strlen(conn->serviceName);
469 plen = TAG_HDR_SIZE + namelen;
470 CHECK_ROOM(cursor, packet.payload, plen);
472 /* Set destination to Ethernet broadcast address */
473 memset(packet.ethHdr.h_dest, 0xFF, ETH_ALEN);
474 memcpy(packet.ethHdr.h_source, conn->myEth, ETH_ALEN);
476 packet.ethHdr.h_proto = htons(Eth_PPPOE_Discovery);
477 packet.vertype = PPPOE_VER_TYPE(1, 1);
478 packet.code = CODE_PADI;
481 svc->type = TAG_SERVICE_NAME;
482 svc->length = htons(namelen);
483 CHECK_ROOM(cursor, packet.payload, namelen+TAG_HDR_SIZE);
485 if (conn->serviceName) {
486 memcpy(svc->payload, conn->serviceName, strlen(conn->serviceName));
488 cursor += namelen + TAG_HDR_SIZE;
490 /* If we're using Host-Uniq, copy it over */
491 if (conn->hostUniq.length) {
492 int len = ntohs(conn->hostUniq.length);
493 CHECK_ROOM(cursor, packet.payload, len + TAG_HDR_SIZE);
494 memcpy(cursor, &conn->hostUniq, len + TAG_HDR_SIZE);
495 cursor += len + TAG_HDR_SIZE;
496 plen += len + TAG_HDR_SIZE;
499 packet.length = htons(plen);
501 sendPacket(conn, conn->discoverySocket, &packet, (int) (plen + HDR_SIZE));
502 if (conn->debugFile) {
503 dumpPacket(conn->debugFile, &packet, "SENT");
504 fprintf(conn->debugFile, "\n");
505 fflush(conn->debugFile);
509 /**********************************************************************
510 *%FUNCTION: waitForPADO
512 * conn -- PPPoEConnection structure
513 * timeout -- how long to wait (in seconds)
517 * Waits for a PADO packet and copies useful information
518 ***********************************************************************/
520 waitForPADO(PPPoEConnection *conn, int timeout)
528 struct PacketCriteria pc;
530 pc.acNameOK = (conn->acName) ? 0 : 1;
531 pc.serviceNameOK = (conn->serviceName) ? 0 : 1;
533 pc.seenServiceName = 0;
537 if (BPF_BUFFER_IS_EMPTY) {
542 FD_SET(conn->discoverySocket, &readable);
545 r = select(conn->discoverySocket+1, &readable, NULL, NULL, &tv);
546 if (r >= 0 || errno != EINTR) break;
549 perror("select (waitForPADO)");
552 if (r == 0) return; /* Timed out */
556 receivePacket(conn->discoverySocket, &packet, &len);
559 if (ntohs(packet.length) + HDR_SIZE > len) {
560 fprintf(stderr, "Bogus PPPoE length field (%u)\n",
561 (unsigned int) ntohs(packet.length));
566 /* If it's not a Discovery packet, loop again */
567 if (etherType(&packet) != Eth_PPPOE_Discovery) continue;
570 if (conn->debugFile) {
571 dumpPacket(conn->debugFile, &packet, "RCVD");
572 fprintf(conn->debugFile, "\n");
573 fflush(conn->debugFile);
575 /* If it's not for us, loop again */
576 if (!packetIsForMe(conn, &packet)) continue;
578 if (packet.code == CODE_PADO) {
579 if (BROADCAST(packet.ethHdr.h_source)) {
580 fprintf(stderr, "Ignoring PADO packet from broadcast MAC address\n");
583 parsePacket(&packet, parsePADOTags, &pc);
586 if (!pc.seenACName) {
587 fprintf(stderr, "Ignoring PADO packet with no AC-Name tag\n");
590 if (!pc.seenServiceName) {
591 fprintf(stderr, "Ignoring PADO packet with no Service-Name tag\n");
595 if (pc.acNameOK && pc.serviceNameOK) {
596 memcpy(conn->peerEth, packet.ethHdr.h_source, ETH_ALEN);
597 if (conn->printACNames) {
598 printf("AC-Ethernet-Address: %02x:%02x:%02x:%02x:%02x:%02x\n",
599 (unsigned) conn->peerEth[0],
600 (unsigned) conn->peerEth[1],
601 (unsigned) conn->peerEth[2],
602 (unsigned) conn->peerEth[3],
603 (unsigned) conn->peerEth[4],
604 (unsigned) conn->peerEth[5]);
605 printf("--------------------------------------------------\n");
608 conn->discoveryState = STATE_RECEIVED_PADO;
612 } while (conn->discoveryState != STATE_RECEIVED_PADO);
615 /**********************************************************************
616 *%FUNCTION: discovery
618 * conn -- PPPoE connection info structure
622 * Performs the PPPoE discovery phase
623 ***********************************************************************/
625 discovery(PPPoEConnection *conn)
627 int padiAttempts = 0;
628 int timeout = conn->discoveryTimeout;
630 conn->discoverySocket =
631 openInterface(conn->ifName, Eth_PPPOE_Discovery, conn->myEth);
635 if (padiAttempts > conn->discoveryAttempts) {
636 fprintf(stderr, "Timeout waiting for PADO packets\n");
637 close(conn->discoverySocket);
638 conn->discoverySocket = -1;
642 conn->discoveryState = STATE_SENT_PADI;
643 waitForPADO(conn, timeout);
644 } while (!conn->numPADOs);
647 int main(int argc, char *argv[])
650 PPPoEConnection *conn;
652 conn = malloc(sizeof(PPPoEConnection));
656 memset(conn, 0, sizeof(PPPoEConnection));
658 conn->printACNames = 1;
659 conn->discoveryTimeout = PADI_TIMEOUT;
660 conn->discoveryAttempts = MAX_PADI_ATTEMPTS;
662 while ((opt = getopt(argc, argv, "I:D:VUQS:C:W:t:a:h")) > 0) {
665 conn->serviceName = xstrdup(optarg);
668 conn->acName = xstrdup(optarg);
671 if (sscanf(optarg, "%d", &conn->discoveryTimeout) != 1) {
672 fprintf(stderr, "Illegal argument to -t: Should be -t timeout\n");
675 if (conn->discoveryTimeout < 1) {
676 conn->discoveryTimeout = 1;
680 if (sscanf(optarg, "%d", &conn->discoveryAttempts) != 1) {
681 fprintf(stderr, "Illegal argument to -a: Should be -a attempts\n");
684 if (conn->discoveryAttempts < 1) {
685 conn->discoveryAttempts = 1;
689 if(conn->hostUniq.length) {
690 fprintf(stderr, "-U and -W are mutually exclusive\n");
693 pid_t pid = getpid();
694 conn->hostUniq.type = htons(TAG_HOST_UNIQ);
695 conn->hostUniq.length = htons(sizeof(pid));
696 memcpy(conn->hostUniq.payload, &pid, sizeof(pid));
700 if(conn->hostUniq.length) {
701 fprintf(stderr, "-U and -W are mutually exclusive\n");
704 if (!parseHostUniq(optarg, &conn->hostUniq)) {
705 fprintf(stderr, "Invalid host-uniq argument: %s\n", optarg);
710 conn->debugFile = fopen(optarg, "w");
711 if (!conn->debugFile) {
712 fprintf(stderr, "Could not open %s: %s\n",
713 optarg, strerror(errno));
716 fprintf(conn->debugFile, "pppoe-discovery %s\n", RP_VERSION);
719 conn->ifName = xstrdup(optarg);
722 conn->printACNames = 0;
734 /* default interface name */
736 conn->ifName = strdup("eth0");
738 conn->discoverySocket = -1;
739 conn->sessionSocket = -1;
749 void rp_fatal(char const *str)
751 fprintf(stderr, "%s\n", str);
755 void fatalSys(char const *str)
761 void sysErr(char const *str)
766 char *xstrdup(const char *s)
768 register char *ret = strdup(s);
776 fprintf(stderr, "Usage: pppoe-discovery [options]\n");
777 fprintf(stderr, "Options:\n");
778 fprintf(stderr, " -I if_name -- Specify interface (default eth0)\n");
779 fprintf(stderr, " -D filename -- Log debugging information in filename.\n");
781 " -t timeout -- Initial timeout for discovery packets in seconds\n"
782 " -a attempts -- Number of discovery attempts\n"
783 " -V -- Print version and exit.\n"
784 " -Q -- Quit Mode: Do not print access concentrator names\n"
785 " -S name -- Set desired service name.\n"
786 " -C name -- Set desired access concentrator name.\n"
787 " -U -- Use Host-Unique to allow multiple PPPoE sessions.\n"
788 " -W hexvalue -- Set the Host-Unique to the supplied hex string.\n"
789 " -h -- Print usage information.\n");
790 fprintf(stderr, "\nVersion " RP_VERSION "\n");