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.
25 #ifdef HAVE_NETPACKET_PACKET_H
26 #include <netpacket/packet.h>
27 #elif defined(HAVE_LINUX_IF_PACKET_H)
28 #include <linux/if_packet.h>
31 #ifdef HAVE_NET_ETHERNET_H
32 #include <net/ethernet.h>
35 #ifdef HAVE_ASM_TYPES_H
36 #include <asm/types.h>
39 #ifdef HAVE_SYS_IOCTL_H
40 #include <sys/ioctl.h>
47 #ifdef HAVE_NET_IF_ARP_H
48 #include <net/if_arp.h>
51 char *xstrdup(const char *s);
59 void error(char *fmt, ...)
63 vfprintf(stderr, fmt, pvar);
67 /* Initialize frame types to RFC 2516 values. Some broken peers apparently
68 use different frame types... sigh... */
70 UINT16_t Eth_PPPOE_Discovery = ETH_PPPOE_DISCOVERY;
71 UINT16_t Eth_PPPOE_Session = ETH_PPPOE_SESSION;
73 /**********************************************************************
76 * packet -- a received PPPoE packet
78 * ethernet packet type (see /usr/include/net/ethertypes.h)
80 * Checks the ethernet packet header to determine its type.
81 * We should only be receveing DISCOVERY and SESSION types if the BPF
82 * is set up correctly. Logs an error if an unexpected type is received.
83 * Note that the ethernet type names come from "pppoe.h" and the packet
84 * packet structure names use the LINUX dialect to maintain consistency
85 * with the rest of this file. See the BSD section of "pppoe.h" for
86 * translations of the data structure names.
87 ***********************************************************************/
89 etherType(PPPoEPacket *packet)
91 UINT16_t type = (UINT16_t) ntohs(packet->ethHdr.h_proto);
92 if (type != Eth_PPPOE_Discovery && type != Eth_PPPOE_Session) {
93 fprintf(stderr, "Invalid ether type 0x%x\n", type);
98 /**********************************************************************
99 *%FUNCTION: openInterface
101 * ifname -- name of interface
102 * type -- Ethernet frame type
103 * hwaddr -- if non-NULL, set to the hardware address
105 * A raw socket for talking to the Ethernet card. Exits on error.
107 * Opens a raw Ethernet socket
108 ***********************************************************************/
110 openInterface(char const *ifname, UINT16_t type, unsigned char *hwaddr)
117 #ifdef HAVE_STRUCT_SOCKADDR_LL
118 struct sockaddr_ll sa;
123 memset(&sa, 0, sizeof(sa));
125 #ifdef HAVE_STRUCT_SOCKADDR_LL
133 if ((fd = socket(domain, stype, htons(type))) < 0) {
134 /* Give a more helpful message for the common error case */
135 if (errno == EPERM) {
136 rp_fatal("Cannot create raw socket -- pppoe must be run as root.");
141 if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &optval, sizeof(optval)) < 0) {
142 fatalSys("setsockopt");
145 /* Fill in hardware address */
147 strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
148 if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
149 fatalSys("ioctl(SIOCGIFHWADDR)");
151 memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
153 if (ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) {
155 sprintf(buffer, "Interface %.16s is not Ethernet", ifname);
159 if (NOT_UNICAST(hwaddr)) {
162 "Interface %.16s has broadcast/multicast MAC address??",
168 /* Sanity check on MTU */
169 strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
170 if (ioctl(fd, SIOCGIFMTU, &ifr) < 0) {
171 fatalSys("ioctl(SIOCGIFMTU)");
173 if (ifr.ifr_mtu < ETH_DATA_LEN) {
174 fprintf(stderr, "Interface %.16s has MTU of %d -- should be %d.\n",
175 ifname, ifr.ifr_mtu, ETH_DATA_LEN);
176 fprintf(stderr, "You may have serious connection problems.\n");
179 #ifdef HAVE_STRUCT_SOCKADDR_LL
180 /* Get interface index */
181 sa.sll_family = AF_PACKET;
182 sa.sll_protocol = htons(type);
184 strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
185 ifr.ifr_name[IFNAMSIZ - 1] = 0;
186 if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
187 fatalSys("ioctl(SIOCFIGINDEX): Could not get interface index");
189 sa.sll_ifindex = ifr.ifr_ifindex;
192 strcpy(sa.sa_data, ifname);
195 /* We're only interested in packets on specified interface */
196 if (bind(fd, (struct sockaddr *) &sa, sizeof(sa)) < 0) {
204 /***********************************************************************
205 *%FUNCTION: sendPacket
207 * sock -- socket to send to
208 * pkt -- the packet to transmit
209 * size -- size of packet (in bytes)
211 * 0 on success; -1 on failure
214 ***********************************************************************/
216 sendPacket(PPPoEConnection *conn, int sock, PPPoEPacket *pkt, int size)
218 #if defined(HAVE_STRUCT_SOCKADDR_LL)
219 if (send(sock, pkt, size, 0) < 0) {
220 sysErr("send (sendPacket)");
227 rp_fatal("relay and server not supported on Linux 2.0 kernels");
229 strcpy(sa.sa_data, conn->ifName);
230 if (sendto(sock, pkt, size, 0, &sa, sizeof(sa)) < 0) {
231 sysErr("sendto (sendPacket)");
238 /***********************************************************************
239 *%FUNCTION: receivePacket
241 * sock -- socket to read from
242 * pkt -- place to store the received packet
243 * size -- set to size of packet in bytes
245 * >= 0 if all OK; < 0 if error
248 ***********************************************************************/
250 receivePacket(int sock, PPPoEPacket *pkt, int *size)
252 if ((*size = recv(sock, pkt, sizeof(PPPoEPacket), 0)) < 0) {
253 sysErr("recv (receivePacket)");
259 /**********************************************************************
260 *%FUNCTION: parsePacket
262 * packet -- the PPPoE discovery packet to parse
263 * func -- function called for each tag in the packet
264 * extra -- an opaque data pointer supplied to parsing function
266 * 0 if everything went well; -1 if there was an error
268 * Parses a PPPoE discovery packet, calling "func" for each tag in the packet.
269 * "func" is passed the additional argument "extra".
270 ***********************************************************************/
272 parsePacket(PPPoEPacket *packet, ParseFunc *func, void *extra)
274 UINT16_t len = ntohs(packet->length);
275 unsigned char *curTag;
276 UINT16_t tagType, tagLen;
278 if (PPPOE_VER(packet->vertype) != 1) {
279 fprintf(stderr, "Invalid PPPoE version (%d)\n",
280 PPPOE_VER(packet->vertype));
283 if (PPPOE_TYPE(packet->vertype) != 1) {
284 fprintf(stderr, "Invalid PPPoE type (%d)\n",
285 PPPOE_TYPE(packet->vertype));
289 /* Do some sanity checks on packet */
290 if (len > ETH_JUMBO_LEN - PPPOE_OVERHEAD) { /* 6-byte overhead for PPPoE header */
291 fprintf(stderr, "Invalid PPPoE packet length (%u)\n", len);
295 /* Step through the tags */
296 curTag = packet->payload;
297 while(curTag - packet->payload < len) {
298 /* Alignment is not guaranteed, so do this by hand... */
299 tagType = (curTag[0] << 8) + curTag[1];
300 tagLen = (curTag[2] << 8) + curTag[3];
301 if (tagType == TAG_END_OF_LIST) {
304 if ((curTag - packet->payload) + tagLen + TAG_HDR_SIZE > len) {
305 fprintf(stderr, "Invalid PPPoE tag length (%u)\n", tagLen);
308 func(tagType, tagLen, curTag+TAG_HDR_SIZE, extra);
309 curTag = curTag + TAG_HDR_SIZE + tagLen;
314 /**********************************************************************
315 *%FUNCTION: parseForHostUniq
320 * extra -- user-supplied pointer. This is assumed to be a pointer to int.
324 * If a HostUnique tag is found which matches our PID, sets *extra to 1.
325 ***********************************************************************/
327 parseForHostUniq(UINT16_t type, UINT16_t len, unsigned char *data,
330 int *val = (int *) extra;
331 if (type == TAG_HOST_UNIQ && len == sizeof(pid_t)) {
333 memcpy(&tmp, data, len);
334 if (tmp == getpid()) {
340 /**********************************************************************
341 *%FUNCTION: packetIsForMe
343 * conn -- PPPoE connection info
344 * packet -- a received PPPoE packet
346 * 1 if packet is for this PPPoE daemon; 0 otherwise.
348 * If we are using the Host-Unique tag, verifies that packet contains
349 * our unique identifier.
350 ***********************************************************************/
352 packetIsForMe(PPPoEConnection *conn, PPPoEPacket *packet)
356 /* If packet is not directed to our MAC address, forget it */
357 if (memcmp(packet->ethHdr.h_dest, conn->myEth, ETH_ALEN)) return 0;
359 /* If we're not using the Host-Unique tag, then accept the packet */
360 if (!conn->hostUniq.length) return 1;
362 parsePacket(packet, parseForHostUniq, &forMe);
366 /**********************************************************************
367 *%FUNCTION: parsePADOTags
372 * extra -- extra user data. Should point to a PacketCriteria structure
373 * which gets filled in according to selected AC name and service
378 * Picks interesting tags out of a PADO packet
379 ***********************************************************************/
381 parsePADOTags(UINT16_t type, UINT16_t len, unsigned char *data,
384 struct PacketCriteria *pc = (struct PacketCriteria *) extra;
385 PPPoEConnection *conn = pc->conn;
391 if (conn->printACNames) {
392 printf("Access-Concentrator: %.*s\n", (int) len, data);
394 if (conn->acName && len == strlen(conn->acName) &&
395 !strncmp((char *) data, conn->acName, len)) {
399 case TAG_SERVICE_NAME:
400 pc->seenServiceName = 1;
401 if (conn->printACNames && len > 0) {
402 printf(" Service-Name: %.*s\n", (int) len, data);
404 if (conn->serviceName && len == strlen(conn->serviceName) &&
405 !strncmp((char *) data, conn->serviceName, len)) {
406 pc->serviceNameOK = 1;
410 if (conn->printACNames) {
411 printf("Got a cookie:");
412 /* Print first 20 bytes of cookie */
413 for (i=0; i<len && i < 20; i++) {
414 printf(" %02x", (unsigned) data[i]);
416 if (i < len) printf("...");
419 conn->cookie.type = htons(type);
420 conn->cookie.length = htons(len);
421 memcpy(conn->cookie.payload, data, len);
423 case TAG_RELAY_SESSION_ID:
424 if (conn->printACNames) {
425 printf("Got a Relay-ID:");
426 /* Print first 20 bytes of relay ID */
427 for (i=0; i<len && i < 20; i++) {
428 printf(" %02x", (unsigned) data[i]);
430 if (i < len) printf("...");
433 conn->relayId.type = htons(type);
434 conn->relayId.length = htons(len);
435 memcpy(conn->relayId.payload, data, len);
437 case TAG_SERVICE_NAME_ERROR:
438 if (conn->printACNames) {
439 printf("Got a Service-Name-Error tag: %.*s\n", (int) len, data);
442 case TAG_AC_SYSTEM_ERROR:
443 if (conn->printACNames) {
444 printf("Got a System-Error tag: %.*s\n", (int) len, data);
447 case TAG_GENERIC_ERROR:
448 if (conn->printACNames) {
449 printf("Got a Generic-Error tag: %.*s\n", (int) len, data);
455 /***********************************************************************
458 * conn -- PPPoEConnection structure
462 * Sends a PADI packet
463 ***********************************************************************/
465 sendPADI(PPPoEConnection *conn)
468 unsigned char *cursor = packet.payload;
469 PPPoETag *svc = (PPPoETag *) (&packet.payload);
470 UINT16_t namelen = 0;
473 if (conn->serviceName) {
474 namelen = (UINT16_t) strlen(conn->serviceName);
476 plen = TAG_HDR_SIZE + namelen;
477 CHECK_ROOM(cursor, packet.payload, plen);
479 /* Set destination to Ethernet broadcast address */
480 memset(packet.ethHdr.h_dest, 0xFF, ETH_ALEN);
481 memcpy(packet.ethHdr.h_source, conn->myEth, ETH_ALEN);
483 packet.ethHdr.h_proto = htons(Eth_PPPOE_Discovery);
484 packet.vertype = PPPOE_VER_TYPE(1, 1);
485 packet.code = CODE_PADI;
488 svc->type = TAG_SERVICE_NAME;
489 svc->length = htons(namelen);
490 CHECK_ROOM(cursor, packet.payload, namelen+TAG_HDR_SIZE);
492 if (conn->serviceName) {
493 memcpy(svc->payload, conn->serviceName, strlen(conn->serviceName));
495 cursor += namelen + TAG_HDR_SIZE;
497 /* If we're using Host-Uniq, copy it over */
498 if (conn->hostUniq.length) {
499 int len = ntohs(conn->hostUniq.length);
500 CHECK_ROOM(cursor, packet.payload, len + TAG_HDR_SIZE);
501 memcpy(cursor, &conn->hostUniq, len + TAG_HDR_SIZE);
502 cursor += len + TAG_HDR_SIZE;
503 plen += len + TAG_HDR_SIZE;
506 packet.length = htons(plen);
508 sendPacket(conn, conn->discoverySocket, &packet, (int) (plen + HDR_SIZE));
509 if (conn->debugFile) {
510 dumpPacket(conn->debugFile, &packet, "SENT");
511 fprintf(conn->debugFile, "\n");
512 fflush(conn->debugFile);
516 /**********************************************************************
517 *%FUNCTION: waitForPADO
519 * conn -- PPPoEConnection structure
520 * timeout -- how long to wait (in seconds)
524 * Waits for a PADO packet and copies useful information
525 ***********************************************************************/
527 waitForPADO(PPPoEConnection *conn, int timeout)
535 struct PacketCriteria pc;
537 pc.acNameOK = (conn->acName) ? 0 : 1;
538 pc.serviceNameOK = (conn->serviceName) ? 0 : 1;
540 pc.seenServiceName = 0;
544 if (BPF_BUFFER_IS_EMPTY) {
549 FD_SET(conn->discoverySocket, &readable);
552 r = select(conn->discoverySocket+1, &readable, NULL, NULL, &tv);
553 if (r >= 0 || errno != EINTR) break;
556 perror("select (waitForPADO)");
559 if (r == 0) return; /* Timed out */
563 receivePacket(conn->discoverySocket, &packet, &len);
566 if (ntohs(packet.length) + HDR_SIZE > len) {
567 fprintf(stderr, "Bogus PPPoE length field (%u)\n",
568 (unsigned int) ntohs(packet.length));
573 /* If it's not a Discovery packet, loop again */
574 if (etherType(&packet) != Eth_PPPOE_Discovery) continue;
577 if (conn->debugFile) {
578 dumpPacket(conn->debugFile, &packet, "RCVD");
579 fprintf(conn->debugFile, "\n");
580 fflush(conn->debugFile);
582 /* If it's not for us, loop again */
583 if (!packetIsForMe(conn, &packet)) continue;
585 if (packet.code == CODE_PADO) {
586 if (BROADCAST(packet.ethHdr.h_source)) {
587 fprintf(stderr, "Ignoring PADO packet from broadcast MAC address\n");
590 parsePacket(&packet, parsePADOTags, &pc);
593 if (!pc.seenACName) {
594 fprintf(stderr, "Ignoring PADO packet with no AC-Name tag\n");
597 if (!pc.seenServiceName) {
598 fprintf(stderr, "Ignoring PADO packet with no Service-Name tag\n");
602 if (pc.acNameOK && pc.serviceNameOK) {
603 memcpy(conn->peerEth, packet.ethHdr.h_source, ETH_ALEN);
604 if (conn->printACNames) {
605 printf("AC-Ethernet-Address: %02x:%02x:%02x:%02x:%02x:%02x\n",
606 (unsigned) conn->peerEth[0],
607 (unsigned) conn->peerEth[1],
608 (unsigned) conn->peerEth[2],
609 (unsigned) conn->peerEth[3],
610 (unsigned) conn->peerEth[4],
611 (unsigned) conn->peerEth[5]);
612 printf("--------------------------------------------------\n");
615 conn->discoveryState = STATE_RECEIVED_PADO;
619 } while (conn->discoveryState != STATE_RECEIVED_PADO);
622 /**********************************************************************
623 *%FUNCTION: discovery
625 * conn -- PPPoE connection info structure
629 * Performs the PPPoE discovery phase
630 ***********************************************************************/
632 discovery(PPPoEConnection *conn)
634 int padiAttempts = 0;
635 int timeout = conn->discoveryTimeout;
637 conn->discoverySocket =
638 openInterface(conn->ifName, Eth_PPPOE_Discovery, conn->myEth);
642 if (padiAttempts > conn->discoveryAttempts) {
643 fprintf(stderr, "Timeout waiting for PADO packets\n");
644 close(conn->discoverySocket);
645 conn->discoverySocket = -1;
649 conn->discoveryState = STATE_SENT_PADI;
650 waitForPADO(conn, timeout);
651 } while (!conn->numPADOs);
654 int main(int argc, char *argv[])
657 PPPoEConnection *conn;
659 conn = malloc(sizeof(PPPoEConnection));
663 memset(conn, 0, sizeof(PPPoEConnection));
665 conn->printACNames = 1;
666 conn->discoveryTimeout = PADI_TIMEOUT;
667 conn->discoveryAttempts = MAX_PADI_ATTEMPTS;
669 while ((opt = getopt(argc, argv, "I:D:VUQS:C:W:t:a:h")) > 0) {
672 conn->serviceName = xstrdup(optarg);
675 conn->acName = xstrdup(optarg);
678 if (sscanf(optarg, "%d", &conn->discoveryTimeout) != 1) {
679 fprintf(stderr, "Illegal argument to -t: Should be -t timeout\n");
682 if (conn->discoveryTimeout < 1) {
683 conn->discoveryTimeout = 1;
687 if (sscanf(optarg, "%d", &conn->discoveryAttempts) != 1) {
688 fprintf(stderr, "Illegal argument to -a: Should be -a attempts\n");
691 if (conn->discoveryAttempts < 1) {
692 conn->discoveryAttempts = 1;
696 if(conn->hostUniq.length) {
697 fprintf(stderr, "-U and -W are mutually exclusive\n");
700 pid_t pid = getpid();
701 conn->hostUniq.type = htons(TAG_HOST_UNIQ);
702 conn->hostUniq.length = htons(sizeof(pid));
703 memcpy(conn->hostUniq.payload, &pid, sizeof(pid));
707 if(conn->hostUniq.length) {
708 fprintf(stderr, "-U and -W are mutually exclusive\n");
711 if (!parseHostUniq(optarg, &conn->hostUniq)) {
712 fprintf(stderr, "Invalid host-uniq argument: %s\n", optarg);
717 conn->debugFile = fopen(optarg, "w");
718 if (!conn->debugFile) {
719 fprintf(stderr, "Could not open %s: %s\n",
720 optarg, strerror(errno));
723 fprintf(conn->debugFile, "pppoe-discovery %s\n", RP_VERSION);
726 conn->ifName = xstrdup(optarg);
729 conn->printACNames = 0;
741 /* default interface name */
743 conn->ifName = strdup("eth0");
745 conn->discoverySocket = -1;
746 conn->sessionSocket = -1;
756 void rp_fatal(char const *str)
758 fprintf(stderr, "%s\n", str);
762 void fatalSys(char const *str)
768 void sysErr(char const *str)
773 char *xstrdup(const char *s)
775 register char *ret = strdup(s);
783 fprintf(stderr, "Usage: pppoe-discovery [options]\n");
784 fprintf(stderr, "Options:\n");
785 fprintf(stderr, " -I if_name -- Specify interface (default eth0)\n");
786 fprintf(stderr, " -D filename -- Log debugging information in filename.\n");
788 " -t timeout -- Initial timeout for discovery packets in seconds\n"
789 " -a attempts -- Number of discovery attempts\n"
790 " -V -- Print version and exit.\n"
791 " -Q -- Quit Mode: Do not print access concentrator names\n"
792 " -S name -- Set desired service name.\n"
793 " -C name -- Set desired access concentrator name.\n"
794 " -U -- Use Host-Unique to allow multiple PPPoE sessions.\n"
795 " -W hexvalue -- Set the Host-Unique to the supplied hex string.\n"
796 " -h -- Print usage information.\n");
797 fprintf(stderr, "\nVersion " RP_VERSION "\n");