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