]> git.ozlabs.org Git - ppp.git/blob - pppd/plugins/rp-pppoe/pppoe-discovery.c
f19c6d8b58318203430401ab641236be82d24c4e
[ppp.git] / pppd / plugins / rp-pppoe / pppoe-discovery.c
1 /*
2  * Perform PPPoE discovery
3  *
4  * Copyright (C) 2000-2001 by Roaring Penguin Software Inc.
5  * Copyright (C) 2004 Marco d'Itri <md@linux.it>
6  *
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.
9  *
10  */
11
12 #include <stdarg.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <unistd.h>
16 #include <errno.h>
17 #include <string.h>
18 #include <time.h>
19
20 #include "pppoe.h"
21
22 #ifdef HAVE_UNISTD_H
23 #include <unistd.h>
24 #endif
25
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>
30 #endif
31
32 #ifdef HAVE_NET_ETHERNET_H
33 #include <net/ethernet.h>
34 #endif
35
36 #ifdef HAVE_ASM_TYPES_H
37 #include <asm/types.h>
38 #endif
39
40 #ifdef HAVE_SYS_IOCTL_H
41 #include <sys/ioctl.h>
42 #endif
43
44 #include <errno.h>
45 #include <stdlib.h>
46 #include <string.h>
47
48 #ifdef HAVE_NET_IF_ARP_H
49 #include <net/if_arp.h>
50 #endif
51
52 char *xstrdup(const char *s);
53 void usage(void);
54
55 void die(int status)
56 {
57         exit(status);
58 }
59
60 void error(char *fmt, ...)
61 {
62     va_list pvar;
63     va_start(pvar, fmt);
64     vfprintf(stderr, fmt, pvar);
65     va_end(pvar);
66 }
67
68 /* Initialize frame types to RFC 2516 values.  Some broken peers apparently
69    use different frame types... sigh... */
70
71 UINT16_t Eth_PPPOE_Discovery = ETH_PPPOE_DISCOVERY;
72 UINT16_t Eth_PPPOE_Session   = ETH_PPPOE_SESSION;
73
74 /**********************************************************************
75 *%FUNCTION: etherType
76 *%ARGUMENTS:
77 * packet -- a received PPPoE packet
78 *%RETURNS:
79 * ethernet packet type (see /usr/include/net/ethertypes.h)
80 *%DESCRIPTION:
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 ***********************************************************************/
89 UINT16_t
90 etherType(PPPoEPacket *packet)
91 {
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);
95     }
96     return type;
97 }
98
99 /**********************************************************************
100 *%FUNCTION: openInterface
101 *%ARGUMENTS:
102 * ifname -- name of interface
103 * type -- Ethernet frame type
104 * hwaddr -- if non-NULL, set to the hardware address
105 *%RETURNS:
106 * A raw socket for talking to the Ethernet card.  Exits on error.
107 *%DESCRIPTION:
108 * Opens a raw Ethernet socket
109 ***********************************************************************/
110 int
111 openInterface(char const *ifname, UINT16_t type, unsigned char *hwaddr)
112 {
113     int optval=1;
114     int fd;
115     struct ifreq ifr;
116     int domain, stype;
117
118 #ifdef HAVE_STRUCT_SOCKADDR_LL
119     struct sockaddr_ll sa;
120 #else
121     struct sockaddr sa;
122 #endif
123
124     memset(&sa, 0, sizeof(sa));
125
126 #ifdef HAVE_STRUCT_SOCKADDR_LL
127     domain = PF_PACKET;
128     stype = SOCK_RAW;
129 #else
130     domain = PF_INET;
131     stype = SOCK_PACKET;
132 #endif
133
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             rp_fatal("Cannot create raw socket -- pppoe must be run as root.");
138         }
139         fatalSys("socket");
140     }
141
142     if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, &optval, sizeof(optval)) < 0) {
143         fatalSys("setsockopt");
144     }
145
146     /* Fill in hardware address */
147     if (hwaddr) {
148         strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
149         if (ioctl(fd, SIOCGIFHWADDR, &ifr) < 0) {
150             fatalSys("ioctl(SIOCGIFHWADDR)");
151         }
152         memcpy(hwaddr, ifr.ifr_hwaddr.sa_data, ETH_ALEN);
153 #ifdef ARPHRD_ETHER
154         if (ifr.ifr_hwaddr.sa_family != ARPHRD_ETHER) {
155             char buffer[256];
156             sprintf(buffer, "Interface %.16s is not Ethernet", ifname);
157             rp_fatal(buffer);
158         }
159 #endif
160         if (NOT_UNICAST(hwaddr)) {
161             char buffer[256];
162             sprintf(buffer,
163                     "Interface %.16s has broadcast/multicast MAC address??",
164                     ifname);
165             rp_fatal(buffer);
166         }
167     }
168
169     /* Sanity check on MTU */
170     strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name));
171     if (ioctl(fd, SIOCGIFMTU, &ifr) < 0) {
172         fatalSys("ioctl(SIOCGIFMTU)");
173     }
174     if (ifr.ifr_mtu < ETH_DATA_LEN) {
175         fprintf(stderr, "Interface %.16s has MTU of %d -- should be %d.\n",
176               ifname, ifr.ifr_mtu, ETH_DATA_LEN);
177         fprintf(stderr, "You may have serious connection problems.\n");
178     }
179
180 #ifdef HAVE_STRUCT_SOCKADDR_LL
181     /* Get interface index */
182     sa.sll_family = AF_PACKET;
183     sa.sll_protocol = htons(type);
184
185     strncpy(ifr.ifr_name, ifname, IFNAMSIZ);
186     ifr.ifr_name[IFNAMSIZ - 1] = 0;
187     if (ioctl(fd, SIOCGIFINDEX, &ifr) < 0) {
188         fatalSys("ioctl(SIOCFIGINDEX): Could not get interface index");
189     }
190     sa.sll_ifindex = ifr.ifr_ifindex;
191
192 #else
193     strcpy(sa.sa_data, ifname);
194 #endif
195
196     /* We're only interested in packets on specified interface */
197     if (bind(fd, (struct sockaddr *) &sa, sizeof(sa)) < 0) {
198         fatalSys("bind");
199     }
200
201     return fd;
202 }
203
204
205 /***********************************************************************
206 *%FUNCTION: sendPacket
207 *%ARGUMENTS:
208 * sock -- socket to send to
209 * pkt -- the packet to transmit
210 * size -- size of packet (in bytes)
211 *%RETURNS:
212 * 0 on success; -1 on failure
213 *%DESCRIPTION:
214 * Transmits a packet
215 ***********************************************************************/
216 int
217 sendPacket(PPPoEConnection *conn, int sock, PPPoEPacket *pkt, int size)
218 {
219 #if defined(HAVE_STRUCT_SOCKADDR_LL)
220     if (send(sock, pkt, size, 0) < 0) {
221         sysErr("send (sendPacket)");
222         return -1;
223     }
224 #else
225     struct sockaddr sa;
226
227     if (!conn) {
228         rp_fatal("relay and server not supported on Linux 2.0 kernels");
229     }
230     strcpy(sa.sa_data, conn->ifName);
231     if (sendto(sock, pkt, size, 0, &sa, sizeof(sa)) < 0) {
232         sysErr("sendto (sendPacket)");
233         return -1;
234     }
235 #endif
236     return 0;
237 }
238
239 /***********************************************************************
240 *%FUNCTION: receivePacket
241 *%ARGUMENTS:
242 * sock -- socket to read from
243 * pkt -- place to store the received packet
244 * size -- set to size of packet in bytes
245 *%RETURNS:
246 * >= 0 if all OK; < 0 if error
247 *%DESCRIPTION:
248 * Receives a packet
249 ***********************************************************************/
250 int
251 receivePacket(int sock, PPPoEPacket *pkt, int *size)
252 {
253     if ((*size = recv(sock, pkt, sizeof(PPPoEPacket), 0)) < 0) {
254         sysErr("recv (receivePacket)");
255         return -1;
256     }
257     return 0;
258 }
259
260 /**********************************************************************
261 *%FUNCTION: parsePacket
262 *%ARGUMENTS:
263 * packet -- the PPPoE discovery packet to parse
264 * func -- function called for each tag in the packet
265 * extra -- an opaque data pointer supplied to parsing function
266 *%RETURNS:
267 * 0 if everything went well; -1 if there was an error
268 *%DESCRIPTION:
269 * Parses a PPPoE discovery packet, calling "func" for each tag in the packet.
270 * "func" is passed the additional argument "extra".
271 ***********************************************************************/
272 int
273 parsePacket(PPPoEPacket *packet, ParseFunc *func, void *extra)
274 {
275     UINT16_t len = ntohs(packet->length);
276     unsigned char *curTag;
277     UINT16_t tagType, tagLen;
278
279     if (PPPOE_VER(packet->vertype) != 1) {
280         fprintf(stderr, "Invalid PPPoE version (%d)\n",
281                 PPPOE_VER(packet->vertype));
282         return -1;
283     }
284     if (PPPOE_TYPE(packet->vertype) != 1) {
285         fprintf(stderr, "Invalid PPPoE type (%d)\n",
286                 PPPOE_TYPE(packet->vertype));
287         return -1;
288     }
289
290     /* Do some sanity checks on packet */
291     if (len > ETH_JUMBO_LEN - PPPOE_OVERHEAD) { /* 6-byte overhead for PPPoE header */
292         fprintf(stderr, "Invalid PPPoE packet length (%u)\n", len);
293         return -1;
294     }
295
296     /* Step through the tags */
297     curTag = packet->payload;
298     while(curTag - packet->payload < len) {
299         /* Alignment is not guaranteed, so do this by hand... */
300         tagType = (curTag[0] << 8) + curTag[1];
301         tagLen = (curTag[2] << 8) + curTag[3];
302         if (tagType == TAG_END_OF_LIST) {
303             return 0;
304         }
305         if ((curTag - packet->payload) + tagLen + TAG_HDR_SIZE > len) {
306             fprintf(stderr, "Invalid PPPoE tag length (%u)\n", tagLen);
307             return -1;
308         }
309         func(tagType, tagLen, curTag+TAG_HDR_SIZE, extra);
310         curTag = curTag + TAG_HDR_SIZE + tagLen;
311     }
312     return 0;
313 }
314
315 /**********************************************************************
316 *%FUNCTION: parseForHostUniq
317 *%ARGUMENTS:
318 * type -- tag type
319 * len -- tag length
320 * data -- tag data.
321 * extra -- user-supplied pointer.  This is assumed to be a pointer to int.
322 *%RETURNS:
323 * Nothing
324 *%DESCRIPTION:
325 * If a HostUnique tag is found which matches our PID, sets *extra to 1.
326 ***********************************************************************/
327 void
328 parseForHostUniq(UINT16_t type, UINT16_t len, unsigned char *data,
329                  void *extra)
330 {
331     int *val = (int *) extra;
332     if (type == TAG_HOST_UNIQ && len == sizeof(pid_t)) {
333         pid_t tmp;
334         memcpy(&tmp, data, len);
335         if (tmp == getpid()) {
336             *val = 1;
337         }
338     }
339 }
340
341 /**********************************************************************
342 *%FUNCTION: packetIsForMe
343 *%ARGUMENTS:
344 * conn -- PPPoE connection info
345 * packet -- a received PPPoE packet
346 *%RETURNS:
347 * 1 if packet is for this PPPoE daemon; 0 otherwise.
348 *%DESCRIPTION:
349 * If we are using the Host-Unique tag, verifies that packet contains
350 * our unique identifier.
351 ***********************************************************************/
352 int
353 packetIsForMe(PPPoEConnection *conn, PPPoEPacket *packet)
354 {
355     int forMe = 0;
356
357     /* If packet is not directed to our MAC address, forget it */
358     if (memcmp(packet->ethHdr.h_dest, conn->myEth, ETH_ALEN)) return 0;
359
360     /* If we're not using the Host-Unique tag, then accept the packet */
361     if (!conn->hostUniq.length) return 1;
362
363     parsePacket(packet, parseForHostUniq, &forMe);
364     return forMe;
365 }
366
367 /**********************************************************************
368 *%FUNCTION: parsePADOTags
369 *%ARGUMENTS:
370 * type -- tag type
371 * len -- tag length
372 * data -- tag data
373 * extra -- extra user data.  Should point to a PacketCriteria structure
374 *          which gets filled in according to selected AC name and service
375 *          name.
376 *%RETURNS:
377 * Nothing
378 *%DESCRIPTION:
379 * Picks interesting tags out of a PADO packet
380 ***********************************************************************/
381 void
382 parsePADOTags(UINT16_t type, UINT16_t len, unsigned char *data,
383               void *extra)
384 {
385     struct PacketCriteria *pc = (struct PacketCriteria *) extra;
386     PPPoEConnection *conn = pc->conn;
387     int i;
388
389     switch(type) {
390     case TAG_AC_NAME:
391         pc->seenACName = 1;
392         if (conn->printACNames) {
393             printf("Access-Concentrator: %.*s\n", (int) len, data);
394         }
395         if (conn->acName && len == strlen(conn->acName) &&
396             !strncmp((char *) data, conn->acName, len)) {
397             pc->acNameOK = 1;
398         }
399         break;
400     case TAG_SERVICE_NAME:
401         pc->seenServiceName = 1;
402         if (conn->printACNames && len > 0) {
403             printf("       Service-Name: %.*s\n", (int) len, data);
404         }
405         if (conn->serviceName && len == strlen(conn->serviceName) &&
406             !strncmp((char *) data, conn->serviceName, len)) {
407             pc->serviceNameOK = 1;
408         }
409         break;
410     case TAG_AC_COOKIE:
411         if (conn->printACNames) {
412             printf("Got a cookie:");
413             /* Print first 20 bytes of cookie */
414             for (i=0; i<len && i < 20; i++) {
415                 printf(" %02x", (unsigned) data[i]);
416             }
417             if (i < len) printf("...");
418             printf("\n");
419         }
420         conn->cookie.type = htons(type);
421         conn->cookie.length = htons(len);
422         memcpy(conn->cookie.payload, data, len);
423         break;
424     case TAG_RELAY_SESSION_ID:
425         if (conn->printACNames) {
426             printf("Got a Relay-ID:");
427             /* Print first 20 bytes of relay ID */
428             for (i=0; i<len && i < 20; i++) {
429                 printf(" %02x", (unsigned) data[i]);
430             }
431             if (i < len) printf("...");
432             printf("\n");
433         }
434         conn->relayId.type = htons(type);
435         conn->relayId.length = htons(len);
436         memcpy(conn->relayId.payload, data, len);
437         break;
438     case TAG_SERVICE_NAME_ERROR:
439         if (conn->printACNames) {
440             printf("Got a Service-Name-Error tag: %.*s\n", (int) len, data);
441         }
442         break;
443     case TAG_AC_SYSTEM_ERROR:
444         if (conn->printACNames) {
445             printf("Got a System-Error tag: %.*s\n", (int) len, data);
446         }
447         break;
448     case TAG_GENERIC_ERROR:
449         if (conn->printACNames) {
450             printf("Got a Generic-Error tag: %.*s\n", (int) len, data);
451         }
452         break;
453     }
454 }
455
456 /***********************************************************************
457 *%FUNCTION: sendPADI
458 *%ARGUMENTS:
459 * conn -- PPPoEConnection structure
460 *%RETURNS:
461 * Nothing
462 *%DESCRIPTION:
463 * Sends a PADI packet
464 ***********************************************************************/
465 void
466 sendPADI(PPPoEConnection *conn)
467 {
468     PPPoEPacket packet;
469     unsigned char *cursor = packet.payload;
470     PPPoETag *svc = (PPPoETag *) (&packet.payload);
471     UINT16_t namelen = 0;
472     UINT16_t plen;
473
474     if (conn->serviceName) {
475         namelen = (UINT16_t) strlen(conn->serviceName);
476     }
477     plen = TAG_HDR_SIZE + namelen;
478     CHECK_ROOM(cursor, packet.payload, plen);
479
480     /* Set destination to Ethernet broadcast address */
481     memset(packet.ethHdr.h_dest, 0xFF, ETH_ALEN);
482     memcpy(packet.ethHdr.h_source, conn->myEth, ETH_ALEN);
483
484     packet.ethHdr.h_proto = htons(Eth_PPPOE_Discovery);
485     packet.vertype = PPPOE_VER_TYPE(1, 1);
486     packet.code = CODE_PADI;
487     packet.session = 0;
488
489     svc->type = TAG_SERVICE_NAME;
490     svc->length = htons(namelen);
491     CHECK_ROOM(cursor, packet.payload, namelen+TAG_HDR_SIZE);
492
493     if (conn->serviceName) {
494         memcpy(svc->payload, conn->serviceName, strlen(conn->serviceName));
495     }
496     cursor += namelen + TAG_HDR_SIZE;
497
498     /* If we're using Host-Uniq, copy it over */
499     if (conn->hostUniq.length) {
500         int len = ntohs(conn->hostUniq.length);
501         CHECK_ROOM(cursor, packet.payload, len + TAG_HDR_SIZE);
502         memcpy(cursor, &conn->hostUniq, len + TAG_HDR_SIZE);
503         cursor += len + TAG_HDR_SIZE;
504         plen += len + TAG_HDR_SIZE;
505     }
506
507     packet.length = htons(plen);
508
509     sendPacket(conn, conn->discoverySocket, &packet, (int) (plen + HDR_SIZE));
510     if (conn->debugFile) {
511         dumpPacket(conn->debugFile, &packet, "SENT");
512         fprintf(conn->debugFile, "\n");
513         fflush(conn->debugFile);
514     }
515 }
516
517 /**********************************************************************
518 *%FUNCTION: waitForPADO
519 *%ARGUMENTS:
520 * conn -- PPPoEConnection structure
521 * timeout -- how long to wait (in seconds)
522 *%RETURNS:
523 * Nothing
524 *%DESCRIPTION:
525 * Waits for a PADO packet and copies useful information
526 ***********************************************************************/
527 void
528 waitForPADO(PPPoEConnection *conn, int timeout)
529 {
530     fd_set readable;
531     int r;
532     struct timeval tv;
533     PPPoEPacket packet;
534     int len;
535
536     struct PacketCriteria pc;
537     pc.conn          = conn;
538     pc.acNameOK      = (conn->acName)      ? 0 : 1;
539     pc.serviceNameOK = (conn->serviceName) ? 0 : 1;
540     pc.seenACName    = 0;
541     pc.seenServiceName = 0;
542     conn->error = 0;
543         
544     do {
545         if (BPF_BUFFER_IS_EMPTY) {
546             tv.tv_sec = timeout;
547             tv.tv_usec = 0;
548         
549             FD_ZERO(&readable);
550             FD_SET(conn->discoverySocket, &readable);
551
552             while(1) {
553                 r = select(conn->discoverySocket+1, &readable, NULL, NULL, &tv);
554                 if (r >= 0 || errno != EINTR) break;
555             }
556             if (r < 0) {
557                 perror("select (waitForPADO)");
558                 return;
559             }
560             if (r == 0) return;        /* Timed out */
561         }
562         
563         /* Get the packet */
564         receivePacket(conn->discoverySocket, &packet, &len);
565
566         /* Check length */
567         if (ntohs(packet.length) + HDR_SIZE > len) {
568             fprintf(stderr, "Bogus PPPoE length field (%u)\n",
569                    (unsigned int) ntohs(packet.length));
570             continue;
571         }
572
573 #ifdef USE_BPF
574         /* If it's not a Discovery packet, loop again */
575         if (etherType(&packet) != Eth_PPPOE_Discovery) continue;
576 #endif
577
578         if (conn->debugFile) {
579             dumpPacket(conn->debugFile, &packet, "RCVD");
580             fprintf(conn->debugFile, "\n");
581             fflush(conn->debugFile);
582         }
583         /* If it's not for us, loop again */
584         if (!packetIsForMe(conn, &packet)) continue;
585
586         if (packet.code == CODE_PADO) {
587             if (BROADCAST(packet.ethHdr.h_source)) {
588                 fprintf(stderr, "Ignoring PADO packet from broadcast MAC address\n");
589                 continue;
590             }
591             parsePacket(&packet, parsePADOTags, &pc);
592             if (conn->error)
593                 return;
594             if (!pc.seenACName) {
595                 fprintf(stderr, "Ignoring PADO packet with no AC-Name tag\n");
596                 continue;
597             }
598             if (!pc.seenServiceName) {
599                 fprintf(stderr, "Ignoring PADO packet with no Service-Name tag\n");
600                 continue;
601             }
602             conn->numPADOs++;
603             if (pc.acNameOK && pc.serviceNameOK) {
604                 memcpy(conn->peerEth, packet.ethHdr.h_source, ETH_ALEN);
605                 if (conn->printACNames) {
606                     printf("AC-Ethernet-Address: %02x:%02x:%02x:%02x:%02x:%02x\n",
607                            (unsigned) conn->peerEth[0], 
608                            (unsigned) conn->peerEth[1],
609                            (unsigned) conn->peerEth[2],
610                            (unsigned) conn->peerEth[3],
611                            (unsigned) conn->peerEth[4],
612                            (unsigned) conn->peerEth[5]);
613                     printf("--------------------------------------------------\n");
614                     continue;
615                 }
616                 conn->discoveryState = STATE_RECEIVED_PADO;
617                 break;
618             }
619         }
620     } while (conn->discoveryState != STATE_RECEIVED_PADO);
621 }
622
623 /**********************************************************************
624 *%FUNCTION: discovery
625 *%ARGUMENTS:
626 * conn -- PPPoE connection info structure
627 *%RETURNS:
628 * Nothing
629 *%DESCRIPTION:
630 * Performs the PPPoE discovery phase
631 ***********************************************************************/
632 void
633 discovery(PPPoEConnection *conn)
634 {
635     int padiAttempts = 0;
636     int timeout = conn->discoveryTimeout;
637
638     conn->discoverySocket =
639         openInterface(conn->ifName, Eth_PPPOE_Discovery, conn->myEth);
640
641     do {
642         padiAttempts++;
643         if (padiAttempts > conn->discoveryAttempts) {
644             fprintf(stderr, "Timeout waiting for PADO packets\n");
645             close(conn->discoverySocket);
646             conn->discoverySocket = -1;
647             return;
648         }
649         sendPADI(conn);
650         conn->discoveryState = STATE_SENT_PADI;
651         waitForPADO(conn, timeout);
652     } while (!conn->numPADOs);
653 }
654
655 int main(int argc, char *argv[])
656 {
657     int opt;
658     PPPoEConnection *conn;
659
660     conn = malloc(sizeof(PPPoEConnection));
661     if (!conn)
662         fatalSys("malloc");
663
664     memset(conn, 0, sizeof(PPPoEConnection));
665
666     conn->printACNames = 1;
667     conn->discoveryTimeout = PADI_TIMEOUT;
668     conn->discoveryAttempts = MAX_PADI_ATTEMPTS;
669
670     while ((opt = getopt(argc, argv, "I:D:VUQS:C:W:t:a:h")) > 0) {
671         switch(opt) {
672         case 'S':
673             conn->serviceName = xstrdup(optarg);
674             break;
675         case 'C':
676             conn->acName = xstrdup(optarg);
677             break;
678         case 't':
679             if (sscanf(optarg, "%d", &conn->discoveryTimeout) != 1) {
680                 fprintf(stderr, "Illegal argument to -t: Should be -t timeout\n");
681                 exit(EXIT_FAILURE);
682             }
683             if (conn->discoveryTimeout < 1) {
684                 conn->discoveryTimeout = 1;
685             }
686             break;
687         case 'a':
688             if (sscanf(optarg, "%d", &conn->discoveryAttempts) != 1) {
689                 fprintf(stderr, "Illegal argument to -a: Should be -a attempts\n");
690                 exit(EXIT_FAILURE);
691             }
692             if (conn->discoveryAttempts < 1) {
693                 conn->discoveryAttempts = 1;
694             }
695             break;
696         case 'U':
697             if(conn->hostUniq.length) {
698                 fprintf(stderr, "-U and -W are mutually exclusive\n");
699                 exit(EXIT_FAILURE);
700             } else {
701                 pid_t pid = getpid();
702                 conn->hostUniq.type = htons(TAG_HOST_UNIQ);
703                 conn->hostUniq.length = htons(sizeof(pid));
704                 memcpy(conn->hostUniq.payload, &pid, sizeof(pid));
705             }
706             break;
707         case 'W':
708             if(conn->hostUniq.length) {
709                 fprintf(stderr, "-U and -W are mutually exclusive\n");
710                 exit(EXIT_FAILURE);
711             }
712             if (!parseHostUniq(optarg, &conn->hostUniq)) {
713                 fprintf(stderr, "Invalid host-uniq argument: %s\n", optarg);
714                 exit(EXIT_FAILURE);
715             }
716             break;
717         case 'D':
718             conn->debugFile = fopen(optarg, "w");
719             if (!conn->debugFile) {
720                 fprintf(stderr, "Could not open %s: %s\n",
721                         optarg, strerror(errno));
722                 exit(1);
723             }
724             fprintf(conn->debugFile, "pppoe-discovery %s\n", RP_VERSION);
725             break;
726         case 'I':
727             conn->ifName = xstrdup(optarg);
728             break;
729         case 'Q':
730             conn->printACNames = 0;
731             break;
732         case 'V':
733         case 'h':
734             usage();
735             exit(0);
736         default:
737             usage();
738             exit(1);
739         }
740     }
741
742     /* default interface name */
743     if (!conn->ifName)
744         conn->ifName = strdup("eth0");
745
746     conn->discoverySocket = -1;
747     conn->sessionSocket = -1;
748
749     discovery(conn);
750
751     if (!conn->numPADOs)
752         exit(1);
753     else
754         exit(0);
755 }
756
757 void rp_fatal(char const *str)
758 {
759     fprintf(stderr, "%s\n", str);
760     exit(1);
761 }
762
763 void fatalSys(char const *str)
764 {
765     perror(str);
766     exit(1);
767 }
768
769 void sysErr(char const *str)
770 {
771     rp_fatal(str);
772 }
773
774 char *xstrdup(const char *s)
775 {
776     register char *ret = strdup(s);
777     if (!ret)
778         sysErr("strdup");
779     return ret;
780 }
781
782 void usage(void)
783 {
784     fprintf(stderr, "Usage: pppoe-discovery [options]\n");
785     fprintf(stderr, "Options:\n");
786     fprintf(stderr, "   -I if_name     -- Specify interface (default eth0)\n");
787     fprintf(stderr, "   -D filename    -- Log debugging information in filename.\n");
788     fprintf(stderr,
789             "   -t timeout     -- Initial timeout for discovery packets in seconds\n"
790             "   -a attempts    -- Number of discovery attempts\n"
791             "   -V             -- Print version and exit.\n"
792             "   -Q             -- Quit Mode: Do not print access concentrator names\n"
793             "   -S name        -- Set desired service name.\n"
794             "   -C name        -- Set desired access concentrator name.\n"
795             "   -U             -- Use Host-Unique to allow multiple PPPoE sessions.\n"
796             "   -W hexvalue    -- Set the Host-Unique to the supplied hex string.\n"
797             "   -h             -- Print usage information.\n");
798     fprintf(stderr, "\nVersion " RP_VERSION "\n");
799 }