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