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