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