]> git.ozlabs.org Git - ppp.git/blob - pppd/plugins/rp-pppoe/pppoe-discovery.c
Fix -W option for pppoe-discovery utility (#157)
[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     PPPoETag *tag = extra;
332
333     if (type == TAG_HOST_UNIQ && len == ntohs(tag->length))
334         tag->length = memcmp(data, tag->payload, len);
335 }
336
337 /**********************************************************************
338 *%FUNCTION: packetIsForMe
339 *%ARGUMENTS:
340 * conn -- PPPoE connection info
341 * packet -- a received PPPoE packet
342 *%RETURNS:
343 * 1 if packet is for this PPPoE daemon; 0 otherwise.
344 *%DESCRIPTION:
345 * If we are using the Host-Unique tag, verifies that packet contains
346 * our unique identifier.
347 ***********************************************************************/
348 int
349 packetIsForMe(PPPoEConnection *conn, PPPoEPacket *packet)
350 {
351     PPPoETag hostUniq = conn->hostUniq;
352
353     /* If packet is not directed to our MAC address, forget it */
354     if (memcmp(packet->ethHdr.h_dest, conn->myEth, ETH_ALEN)) return 0;
355
356     /* If we're not using the Host-Unique tag, then accept the packet */
357     if (!conn->hostUniq.length) return 1;
358
359     parsePacket(packet, parseForHostUniq, &hostUniq);
360     return !hostUniq.length;
361 }
362
363 /**********************************************************************
364 *%FUNCTION: parsePADOTags
365 *%ARGUMENTS:
366 * type -- tag type
367 * len -- tag length
368 * data -- tag data
369 * extra -- extra user data.  Should point to a PacketCriteria structure
370 *          which gets filled in according to selected AC name and service
371 *          name.
372 *%RETURNS:
373 * Nothing
374 *%DESCRIPTION:
375 * Picks interesting tags out of a PADO packet
376 ***********************************************************************/
377 void
378 parsePADOTags(UINT16_t type, UINT16_t len, unsigned char *data,
379               void *extra)
380 {
381     struct PacketCriteria *pc = (struct PacketCriteria *) extra;
382     PPPoEConnection *conn = pc->conn;
383     int i;
384
385     switch(type) {
386     case TAG_AC_NAME:
387         pc->seenACName = 1;
388         if (conn->printACNames) {
389             printf("Access-Concentrator: %.*s\n", (int) len, data);
390         }
391         if (conn->acName && len == strlen(conn->acName) &&
392             !strncmp((char *) data, conn->acName, len)) {
393             pc->acNameOK = 1;
394         }
395         break;
396     case TAG_SERVICE_NAME:
397         pc->seenServiceName = 1;
398         if (conn->printACNames && len > 0) {
399             printf("       Service-Name: %.*s\n", (int) len, data);
400         }
401         if (conn->serviceName && len == strlen(conn->serviceName) &&
402             !strncmp((char *) data, conn->serviceName, len)) {
403             pc->serviceNameOK = 1;
404         }
405         break;
406     case TAG_AC_COOKIE:
407         if (conn->printACNames) {
408             printf("Got a cookie:");
409             /* Print first 20 bytes of cookie */
410             for (i=0; i<len && i < 20; i++) {
411                 printf(" %02x", (unsigned) data[i]);
412             }
413             if (i < len) printf("...");
414             printf("\n");
415         }
416         conn->cookie.type = htons(type);
417         conn->cookie.length = htons(len);
418         memcpy(conn->cookie.payload, data, len);
419         break;
420     case TAG_RELAY_SESSION_ID:
421         if (conn->printACNames) {
422             printf("Got a Relay-ID:");
423             /* Print first 20 bytes of relay ID */
424             for (i=0; i<len && i < 20; i++) {
425                 printf(" %02x", (unsigned) data[i]);
426             }
427             if (i < len) printf("...");
428             printf("\n");
429         }
430         conn->relayId.type = htons(type);
431         conn->relayId.length = htons(len);
432         memcpy(conn->relayId.payload, data, len);
433         break;
434     case TAG_SERVICE_NAME_ERROR:
435         if (conn->printACNames) {
436             printf("Got a Service-Name-Error tag: %.*s\n", (int) len, data);
437         }
438         break;
439     case TAG_AC_SYSTEM_ERROR:
440         if (conn->printACNames) {
441             printf("Got a System-Error tag: %.*s\n", (int) len, data);
442         }
443         break;
444     case TAG_GENERIC_ERROR:
445         if (conn->printACNames) {
446             printf("Got a Generic-Error tag: %.*s\n", (int) len, data);
447         }
448         break;
449     }
450 }
451
452 /***********************************************************************
453 *%FUNCTION: sendPADI
454 *%ARGUMENTS:
455 * conn -- PPPoEConnection structure
456 *%RETURNS:
457 * Nothing
458 *%DESCRIPTION:
459 * Sends a PADI packet
460 ***********************************************************************/
461 void
462 sendPADI(PPPoEConnection *conn)
463 {
464     PPPoEPacket packet;
465     unsigned char *cursor = packet.payload;
466     PPPoETag *svc = (PPPoETag *) (&packet.payload);
467     UINT16_t namelen = 0;
468     UINT16_t plen;
469
470     if (conn->serviceName) {
471         namelen = (UINT16_t) strlen(conn->serviceName);
472     }
473     plen = TAG_HDR_SIZE + namelen;
474     CHECK_ROOM(cursor, packet.payload, plen);
475
476     /* Set destination to Ethernet broadcast address */
477     memset(packet.ethHdr.h_dest, 0xFF, ETH_ALEN);
478     memcpy(packet.ethHdr.h_source, conn->myEth, ETH_ALEN);
479
480     packet.ethHdr.h_proto = htons(Eth_PPPOE_Discovery);
481     packet.vertype = PPPOE_VER_TYPE(1, 1);
482     packet.code = CODE_PADI;
483     packet.session = 0;
484
485     svc->type = TAG_SERVICE_NAME;
486     svc->length = htons(namelen);
487     CHECK_ROOM(cursor, packet.payload, namelen+TAG_HDR_SIZE);
488
489     if (conn->serviceName) {
490         memcpy(svc->payload, conn->serviceName, strlen(conn->serviceName));
491     }
492     cursor += namelen + TAG_HDR_SIZE;
493
494     /* If we're using Host-Uniq, copy it over */
495     if (conn->hostUniq.length) {
496         int len = ntohs(conn->hostUniq.length);
497         CHECK_ROOM(cursor, packet.payload, len + TAG_HDR_SIZE);
498         memcpy(cursor, &conn->hostUniq, len + TAG_HDR_SIZE);
499         cursor += len + TAG_HDR_SIZE;
500         plen += len + TAG_HDR_SIZE;
501     }
502
503     packet.length = htons(plen);
504
505     sendPacket(conn, conn->discoverySocket, &packet, (int) (plen + HDR_SIZE));
506     if (conn->debugFile) {
507         dumpPacket(conn->debugFile, &packet, "SENT");
508         fprintf(conn->debugFile, "\n");
509         fflush(conn->debugFile);
510     }
511 }
512
513 /**********************************************************************
514 *%FUNCTION: waitForPADO
515 *%ARGUMENTS:
516 * conn -- PPPoEConnection structure
517 * timeout -- how long to wait (in seconds)
518 *%RETURNS:
519 * Nothing
520 *%DESCRIPTION:
521 * Waits for a PADO packet and copies useful information
522 ***********************************************************************/
523 void
524 waitForPADO(PPPoEConnection *conn, int timeout)
525 {
526     fd_set readable;
527     int r;
528     struct timeval tv;
529     PPPoEPacket packet;
530     int len;
531
532     struct PacketCriteria pc;
533     pc.conn          = conn;
534     pc.acNameOK      = (conn->acName)      ? 0 : 1;
535     pc.serviceNameOK = (conn->serviceName) ? 0 : 1;
536     pc.seenACName    = 0;
537     pc.seenServiceName = 0;
538     conn->error = 0;
539         
540     do {
541         if (BPF_BUFFER_IS_EMPTY) {
542             tv.tv_sec = timeout;
543             tv.tv_usec = 0;
544         
545             FD_ZERO(&readable);
546             FD_SET(conn->discoverySocket, &readable);
547
548             while(1) {
549                 r = select(conn->discoverySocket+1, &readable, NULL, NULL, &tv);
550                 if (r >= 0 || errno != EINTR) break;
551             }
552             if (r < 0) {
553                 perror("select (waitForPADO)");
554                 return;
555             }
556             if (r == 0) return;        /* Timed out */
557         }
558         
559         /* Get the packet */
560         receivePacket(conn->discoverySocket, &packet, &len);
561
562         /* Check length */
563         if (ntohs(packet.length) + HDR_SIZE > len) {
564             fprintf(stderr, "Bogus PPPoE length field (%u)\n",
565                    (unsigned int) ntohs(packet.length));
566             continue;
567         }
568
569 #ifdef USE_BPF
570         /* If it's not a Discovery packet, loop again */
571         if (etherType(&packet) != Eth_PPPOE_Discovery) continue;
572 #endif
573
574         if (conn->debugFile) {
575             dumpPacket(conn->debugFile, &packet, "RCVD");
576             fprintf(conn->debugFile, "\n");
577             fflush(conn->debugFile);
578         }
579         /* If it's not for us, loop again */
580         if (!packetIsForMe(conn, &packet)) continue;
581
582         if (packet.code == CODE_PADO) {
583             if (BROADCAST(packet.ethHdr.h_source)) {
584                 fprintf(stderr, "Ignoring PADO packet from broadcast MAC address\n");
585                 continue;
586             }
587             parsePacket(&packet, parsePADOTags, &pc);
588             if (conn->error)
589                 return;
590             if (!pc.seenACName) {
591                 fprintf(stderr, "Ignoring PADO packet with no AC-Name tag\n");
592                 continue;
593             }
594             if (!pc.seenServiceName) {
595                 fprintf(stderr, "Ignoring PADO packet with no Service-Name tag\n");
596                 continue;
597             }
598             conn->numPADOs++;
599             if (pc.acNameOK && pc.serviceNameOK) {
600                 memcpy(conn->peerEth, packet.ethHdr.h_source, ETH_ALEN);
601                 if (conn->printACNames) {
602                     printf("AC-Ethernet-Address: %02x:%02x:%02x:%02x:%02x:%02x\n",
603                            (unsigned) conn->peerEth[0], 
604                            (unsigned) conn->peerEth[1],
605                            (unsigned) conn->peerEth[2],
606                            (unsigned) conn->peerEth[3],
607                            (unsigned) conn->peerEth[4],
608                            (unsigned) conn->peerEth[5]);
609                     printf("--------------------------------------------------\n");
610                     continue;
611                 }
612                 conn->discoveryState = STATE_RECEIVED_PADO;
613                 break;
614             }
615         }
616     } while (conn->discoveryState != STATE_RECEIVED_PADO);
617 }
618
619 /**********************************************************************
620 *%FUNCTION: discovery
621 *%ARGUMENTS:
622 * conn -- PPPoE connection info structure
623 *%RETURNS:
624 * Nothing
625 *%DESCRIPTION:
626 * Performs the PPPoE discovery phase
627 ***********************************************************************/
628 void
629 discovery(PPPoEConnection *conn)
630 {
631     int padiAttempts = 0;
632     int timeout = conn->discoveryTimeout;
633
634     conn->discoverySocket =
635         openInterface(conn->ifName, Eth_PPPOE_Discovery, conn->myEth);
636
637     do {
638         padiAttempts++;
639         if (padiAttempts > conn->discoveryAttempts) {
640             fprintf(stderr, "Timeout waiting for PADO packets\n");
641             close(conn->discoverySocket);
642             conn->discoverySocket = -1;
643             return;
644         }
645         sendPADI(conn);
646         conn->discoveryState = STATE_SENT_PADI;
647         waitForPADO(conn, timeout);
648     } while (!conn->numPADOs);
649 }
650
651 int main(int argc, char *argv[])
652 {
653     int opt;
654     PPPoEConnection *conn;
655
656     conn = malloc(sizeof(PPPoEConnection));
657     if (!conn)
658         fatalSys("malloc");
659
660     memset(conn, 0, sizeof(PPPoEConnection));
661
662     conn->printACNames = 1;
663     conn->discoveryTimeout = PADI_TIMEOUT;
664     conn->discoveryAttempts = MAX_PADI_ATTEMPTS;
665
666     while ((opt = getopt(argc, argv, "I:D:VUQS:C:W:t:a:h")) > 0) {
667         switch(opt) {
668         case 'S':
669             conn->serviceName = xstrdup(optarg);
670             break;
671         case 'C':
672             conn->acName = xstrdup(optarg);
673             break;
674         case 't':
675             if (sscanf(optarg, "%d", &conn->discoveryTimeout) != 1) {
676                 fprintf(stderr, "Illegal argument to -t: Should be -t timeout\n");
677                 exit(EXIT_FAILURE);
678             }
679             if (conn->discoveryTimeout < 1) {
680                 conn->discoveryTimeout = 1;
681             }
682             break;
683         case 'a':
684             if (sscanf(optarg, "%d", &conn->discoveryAttempts) != 1) {
685                 fprintf(stderr, "Illegal argument to -a: Should be -a attempts\n");
686                 exit(EXIT_FAILURE);
687             }
688             if (conn->discoveryAttempts < 1) {
689                 conn->discoveryAttempts = 1;
690             }
691             break;
692         case 'U':
693             if(conn->hostUniq.length) {
694                 fprintf(stderr, "-U and -W are mutually exclusive\n");
695                 exit(EXIT_FAILURE);
696             } else {
697                 pid_t pid = getpid();
698                 conn->hostUniq.type = htons(TAG_HOST_UNIQ);
699                 conn->hostUniq.length = htons(sizeof(pid));
700                 memcpy(conn->hostUniq.payload, &pid, sizeof(pid));
701             }
702             break;
703         case 'W':
704             if(conn->hostUniq.length) {
705                 fprintf(stderr, "-U and -W are mutually exclusive\n");
706                 exit(EXIT_FAILURE);
707             }
708             if (!parseHostUniq(optarg, &conn->hostUniq)) {
709                 fprintf(stderr, "Invalid host-uniq argument: %s\n", optarg);
710                 exit(EXIT_FAILURE);
711             }
712             break;
713         case 'D':
714             conn->debugFile = fopen(optarg, "w");
715             if (!conn->debugFile) {
716                 fprintf(stderr, "Could not open %s: %s\n",
717                         optarg, strerror(errno));
718                 exit(1);
719             }
720             fprintf(conn->debugFile, "pppoe-discovery %s\n", RP_VERSION);
721             break;
722         case 'I':
723             conn->ifName = xstrdup(optarg);
724             break;
725         case 'Q':
726             conn->printACNames = 0;
727             break;
728         case 'V':
729         case 'h':
730             usage();
731             exit(0);
732         default:
733             usage();
734             exit(1);
735         }
736     }
737
738     /* default interface name */
739     if (!conn->ifName)
740         conn->ifName = strdup("eth0");
741
742     conn->discoverySocket = -1;
743     conn->sessionSocket = -1;
744
745     discovery(conn);
746
747     if (!conn->numPADOs)
748         exit(1);
749     else
750         exit(0);
751 }
752
753 void rp_fatal(char const *str)
754 {
755     fprintf(stderr, "%s\n", str);
756     exit(1);
757 }
758
759 void fatalSys(char const *str)
760 {
761     perror(str);
762     exit(1);
763 }
764
765 void sysErr(char const *str)
766 {
767     rp_fatal(str);
768 }
769
770 char *xstrdup(const char *s)
771 {
772     register char *ret = strdup(s);
773     if (!ret)
774         sysErr("strdup");
775     return ret;
776 }
777
778 void usage(void)
779 {
780     fprintf(stderr, "Usage: pppoe-discovery [options]\n");
781     fprintf(stderr, "Options:\n");
782     fprintf(stderr, "   -I if_name     -- Specify interface (default eth0)\n");
783     fprintf(stderr, "   -D filename    -- Log debugging information in filename.\n");
784     fprintf(stderr,
785             "   -t timeout     -- Initial timeout for discovery packets in seconds\n"
786             "   -a attempts    -- Number of discovery attempts\n"
787             "   -V             -- Print version and exit.\n"
788             "   -Q             -- Quit Mode: Do not print access concentrator names\n"
789             "   -S name        -- Set desired service name.\n"
790             "   -C name        -- Set desired access concentrator name.\n"
791             "   -U             -- Use Host-Unique to allow multiple PPPoE sessions.\n"
792             "   -W hexvalue    -- Set the Host-Unique to the supplied hex string.\n"
793             "   -h             -- Print usage information.\n");
794     fprintf(stderr, "\nVersion " RP_VERSION "\n");
795 }