xref: /freebsd/libexec/pppoed/pppoed.c (revision 77a0943ded95b9e6438f7db70c4a28e4d93946d4)
1 /*-
2  * Copyright (c) 1999 Brian Somers <brian@Awfulhak.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD$
27  */
28 
29 #include <sys/param.h>
30 #include <sys/socket.h>
31 #include <sys/un.h>
32 #include <netinet/in.h>
33 #include <arpa/inet.h>
34 #include <netdb.h>
35 #include <netgraph.h>
36 #include <net/ethernet.h>
37 #include <netinet/in_systm.h>
38 #include <netinet/ip.h>
39 #include <netgraph/ng_ether.h>
40 #include <netgraph/ng_message.h>
41 #include <netgraph/ng_pppoe.h>
42 #include <netgraph/ng_socket.h>
43 
44 #include <errno.h>
45 #include <paths.h>
46 #include <signal.h>
47 #include <stdio.h>
48 #include <stdarg.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <sysexits.h>
52 #include <sys/fcntl.h>
53 #ifndef NOKLDLOAD
54 #include <sys/linker.h>
55 #include <sys/module.h>
56 #endif
57 #include <sys/uio.h>
58 #include <sys/wait.h>
59 #include <syslog.h>
60 #include <termios.h>
61 #include <unistd.h>
62 
63 
64 #define DEFAULT_EXEC_PREFIX "exec /usr/sbin/ppp -direct "
65 
66 static int
67 usage(const char *prog)
68 {
69   fprintf(stderr, "Usage: %s [-Fd] [-P pidfile] [-a name] [-e exec]"
70           " [-p provider] interface\n", prog);
71   return EX_USAGE;
72 }
73 
74 const char *pidfile;
75 
76 static void
77 Fairwell(int sig)
78 {
79   char buf[] = "Received signal XX, exiting";
80 
81   /* No stdio in a signal handler */
82   buf[16] = '0' + ((sig / 10) % 10);
83   buf[17] = '0' + (sig % 10);
84 
85   syslog(LOG_INFO, "%s", buf);
86 
87   if (pidfile)
88     remove(pidfile);
89 
90   signal(sig, SIG_DFL);
91   raise(sig);
92 }
93 
94 static int
95 ConfigureNode(const char *prog, const char *iface, const char *provider,
96               int cs, int ds, int debug, struct ngm_connect *ngc)
97 {
98   /*
99    * We're going to do this with the passed `ds' & `cs' descriptors:
100    *
101    * .---------.
102    * |  ether  |
103    * | <iface> |
104    * `---------'
105    *  (orphan)                                     ds    cs
106    *     |                                         |     |
107    *     |                                         |     |
108    * (ethernet)                                    |     |
109    * .---------.                                .-----------.
110    * |  pppoe  |                                |  socket   |
111    * | <iface> |(pppoe-<pid>)<---->(pppoe-<pid>)| <unnamed> |
112    * `---------                                 `-----------'
113    * (exec-<pid>)
114    *     ^                .-----------.      .-------------.
115    *     |                |   socket  |      | ppp -direct |
116    *     `--->(exec-<pid>)| <unnamed> |--fd--|  provider   |
117    *                      `-----------'      `-------------'
118    *
119    * where there are potentially many ppp processes running off of the
120    * same PPPoE node.
121    * The exec-<pid> hook isn't made 'till we Spawn().
122    */
123 
124   char *epath, *spath;
125   struct ngpppoe_init_data *data;
126   const struct hooklist *hlist;
127   const struct nodeinfo *ninfo;
128   const struct linkinfo *nlink;
129   struct ngm_mkpeer mkp;
130   struct ng_mesg *resp;
131   u_char rbuf[2048];
132   int f, plen;
133 
134   /*
135    * Ask for a list of hooks attached to the "ether" node.  This node should
136    * magically exist as a way of hooking stuff onto an ethernet device
137    */
138   epath = (char *)alloca(strlen(iface) + 2);
139   sprintf(epath, "%s:", iface);
140 
141   if (debug)
142     fprintf(stderr, "Sending NGM_LISTHOOKS to %s\n", epath);
143 
144   if (NgSendMsg(cs, epath, NGM_GENERIC_COOKIE, NGM_LISTHOOKS, NULL, 0) < 0) {
145     if (errno == ENOENT)
146       fprintf(stderr, "%s Cannot send a netgraph message: Invalid interface\n",
147               epath);
148     else
149       fprintf(stderr, "%s Cannot send a netgraph message: %s\n",
150               epath, strerror(errno));
151     return EX_UNAVAILABLE;
152   }
153 
154   /* Get our list back */
155   resp = (struct ng_mesg *)rbuf;
156   if (NgRecvMsg(cs, resp, sizeof rbuf, NULL) < 0) {
157     perror("Cannot get netgraph response");
158     return EX_UNAVAILABLE;
159   }
160 
161   hlist = (const struct hooklist *)resp->data;
162   ninfo = &hlist->nodeinfo;
163 
164   if (debug)
165     fprintf(stderr, "Got reply from id [%x]: Type %s with %d hooks\n",
166             ninfo->id, ninfo->type, ninfo->hooks);
167 
168   /* Make sure we've got the right type of node */
169   if (strncmp(ninfo->type, NG_ETHER_NODE_TYPE, sizeof NG_ETHER_NODE_TYPE - 1)) {
170     fprintf(stderr, "%s Unexpected node type ``%s'' (wanted ``"
171             NG_ETHER_NODE_TYPE "'')\n", epath, ninfo->type);
172     return EX_DATAERR;
173   }
174 
175   /* look for a hook already attached.  */
176   for (f = 0; f < ninfo->hooks; f++) {
177     nlink = &hlist->link[f];
178 
179     if (debug)
180       fprintf(stderr, "  Got [%x]:%s -> [%x]:%s\n", ninfo->id,
181               nlink->ourhook, nlink->nodeinfo.id, nlink->peerhook);
182 
183     if (!strcmp(nlink->ourhook, NG_ETHER_HOOK_ORPHAN) ||
184         !strcmp(nlink->ourhook, NG_ETHER_HOOK_DIVERT)) {
185       /*
186        * Something is using the data coming out of this `ether' node.
187        * If it's a PPPoE node, we use that node, otherwise we complain that
188        * someone else is using the node.
189        */
190       if (strcmp(nlink->nodeinfo.type, NG_PPPOE_NODE_TYPE)) {
191         fprintf(stderr, "%s Node type %s is currently active\n",
192                 epath, nlink->nodeinfo.type);
193         return EX_UNAVAILABLE;
194       }
195       break;
196     }
197   }
198 
199   if (f == ninfo->hooks) {
200     /*
201      * Create a new PPPoE node connected to the `ether' node using
202      * the magic `orphan' and `ethernet' hooks
203      */
204     snprintf(mkp.type, sizeof mkp.type, "%s", NG_PPPOE_NODE_TYPE);
205     snprintf(mkp.ourhook, sizeof mkp.ourhook, "%s", NG_ETHER_HOOK_ORPHAN);
206     snprintf(mkp.peerhook, sizeof mkp.peerhook, "%s", NG_PPPOE_HOOK_ETHERNET);
207 
208     if (debug)
209       fprintf(stderr, "Send MKPEER: %s%s -> [type %s]:%s\n", epath,
210               mkp.ourhook, mkp.type, mkp.peerhook);
211 
212     if (NgSendMsg(cs, epath, NGM_GENERIC_COOKIE,
213                   NGM_MKPEER, &mkp, sizeof mkp) < 0) {
214       fprintf(stderr, "%s Cannot create a peer PPPoE node: %s\n",
215               epath, strerror(errno));
216       return EX_OSERR;
217     }
218   }
219 
220   /* Connect the PPPoE node to our socket node.  */
221   snprintf(ngc->path, sizeof ngc->path, "%s%s", epath, NG_ETHER_HOOK_ORPHAN);
222   snprintf(ngc->ourhook, sizeof ngc->ourhook, "pppoe-%ld", (long)getpid());
223   memcpy(ngc->peerhook, ngc->ourhook, sizeof ngc->peerhook);
224 
225   if (NgSendMsg(cs, ".:", NGM_GENERIC_COOKIE,
226                 NGM_CONNECT, ngc, sizeof *ngc) < 0) {
227     perror("Cannot CONNECT PPPoE and socket nodes");
228     return EX_OSERR;
229   }
230 
231   plen = strlen(provider);
232 
233   data = (struct ngpppoe_init_data *)alloca(sizeof *data + plen);
234   snprintf(data->hook, sizeof data->hook, "%s", ngc->peerhook);
235   memcpy(data->data, provider, plen);
236   data->data_len = plen;
237 
238   spath = (char *)alloca(strlen(ngc->peerhook) + 3);
239   strcpy(spath, ".:");
240   strcpy(spath + 2, ngc->ourhook);
241 
242   if (debug) {
243     if (provider)
244       fprintf(stderr, "Sending PPPOE_LISTEN to %s, provider %s\n",
245               spath, provider);
246     else
247       fprintf(stderr, "Sending PPPOE_LISTEN to %s\n", spath);
248   }
249 
250   if (NgSendMsg(cs, spath, NGM_PPPOE_COOKIE, NGM_PPPOE_LISTEN,
251                 data, sizeof *data + plen) == -1) {
252     fprintf(stderr, "%s: Cannot LISTEN on netgraph node: %s\n",
253             spath, strerror(errno));
254     return EX_OSERR;
255   }
256 
257   return 0;
258 }
259 
260 static void
261 Spawn(const char *prog, const char *acname, const char *exec,
262       struct ngm_connect ngc, int cs, int ds, void *request, int sz,
263       int debug)
264 {
265   char msgbuf[sizeof(struct ng_mesg) + sizeof(struct ngpppoe_sts)];
266   struct ng_mesg *rep = (struct ng_mesg *)msgbuf;
267   struct ngpppoe_sts *sts = (struct ngpppoe_sts *)(msgbuf + sizeof *rep);
268   struct ngpppoe_init_data *data;
269   char unknown[14], *path;
270   const char *msg;
271   int ret, slen;
272 
273   switch ((ret = fork())) {
274     case -1:
275       syslog(LOG_ERR, "fork: %m");
276       break;
277 
278     case 0:
279       switch (fork()) {
280         case 0:
281           break;
282         case -1:
283           _exit(errno);
284         default:
285           _exit(0);
286       }
287       close(cs);
288       close(ds);
289 
290       /* Create a new socket node */
291       if (debug)
292         syslog(LOG_INFO, "Creating a new socket node");
293 
294       if (NgMkSockNode(NULL, &cs, &ds) == -1) {
295         syslog(LOG_ERR, "Cannot create netgraph socket node: %m");
296         _exit(EX_CANTCREAT);
297       }
298 
299       /* Connect the PPPoE node to our new socket node.  */
300       snprintf(ngc.ourhook, sizeof ngc.ourhook, "exec-%ld", (long)getpid());
301       memcpy(ngc.peerhook, ngc.ourhook, sizeof ngc.peerhook);
302 
303       if (debug)
304         syslog(LOG_INFO, "Sending CONNECT from .:%s -> %s.%s",
305                ngc.ourhook, ngc.path, ngc.peerhook);
306       if (NgSendMsg(cs, ".:", NGM_GENERIC_COOKIE,
307                     NGM_CONNECT, &ngc, sizeof ngc) < 0) {
308         syslog(LOG_ERR, "Cannot CONNECT PPPoE and socket nodes: %m");
309         _exit(EX_OSERR);
310       }
311 
312       /*
313        * If we tell the socket node not to LINGER, it will go away when
314        * the last hook is removed.
315        */
316       if (debug)
317         syslog(LOG_INFO, "Sending NGM_SOCK_CMD_NOLINGER to socket");
318       if (NgSendMsg(cs, ".:", NGM_SOCKET_COOKIE,
319                     NGM_SOCK_CMD_NOLINGER, NULL, 0) < 0) {
320         syslog(LOG_ERR, "Cannot send NGM_SOCK_CMD_NOLINGER: %m");
321         _exit(EX_OSERR);
322       }
323 
324       /* Put the PPPoE node into OFFER mode */
325       slen = strlen(acname);
326       data = (struct ngpppoe_init_data *)alloca(sizeof *data + slen);
327       snprintf(data->hook, sizeof data->hook, "%s", ngc.ourhook);
328       memcpy(data->data, acname, slen);
329       data->data_len = slen;
330 
331       path = (char *)alloca(strlen(ngc.ourhook) + 3);
332       strcpy(path, ".:");
333       strcpy(path + 2, ngc.ourhook);
334 
335       syslog(LOG_INFO, "Offering to %s as access concentrator %s",
336              path, acname);
337       if (NgSendMsg(cs, path, NGM_PPPOE_COOKIE, NGM_PPPOE_OFFER,
338                     data, sizeof *data + slen) == -1) {
339         syslog(LOG_INFO, "%s: Cannot OFFER on netgraph node: %m", path);
340         _exit(EX_OSERR);
341       }
342 
343       /* And send our request data to the waiting node */
344       if (debug)
345         syslog(LOG_INFO, "Sending original request to %s (%d bytes)", path, sz);
346       if (NgSendData(ds, ngc.ourhook, request, sz) == -1) {
347         syslog(LOG_ERR, "Cannot send original request to %s: %m", path);
348         _exit(EX_OSERR);
349       }
350 
351       /* Then wait for a success indication */
352 
353       if (debug)
354         syslog(LOG_INFO, "Waiting for a SUCCESS reply %s", path);
355 
356       do {
357         if (NgRecvMsg(cs, rep, sizeof msgbuf, NULL) < 0) {
358           syslog(LOG_ERR, "%s: Cannot receive a message: %m", path);
359           _exit(EX_OSERR);
360         }
361 
362         if (rep->header.version != NG_VERSION) {
363           syslog(LOG_ERR, "%ld: Unexpected netgraph version, expected %ld",
364                  (long)rep->header.version, (long)NG_VERSION);
365           _exit(EX_PROTOCOL);
366         }
367 
368         if (rep->header.typecookie != NGM_PPPOE_COOKIE) {
369           syslog(LOG_INFO, "%ld: Unexpected netgraph cookie, expected %ld",
370                  (long)rep->header.typecookie, (long)NGM_PPPOE_COOKIE);
371           continue;
372         }
373 
374         switch (rep->header.cmd) {
375           case NGM_PPPOE_SET_FLAG:	msg = "SET_FLAG";	break;
376           case NGM_PPPOE_CONNECT:	msg = "CONNECT";	break;
377           case NGM_PPPOE_LISTEN:	msg = "LISTEN";		break;
378           case NGM_PPPOE_OFFER:		msg = "OFFER";		break;
379           case NGM_PPPOE_SUCCESS:	msg = "SUCCESS";	break;
380           case NGM_PPPOE_FAIL:		msg = "FAIL";		break;
381           case NGM_PPPOE_CLOSE:		msg = "CLOSE";		break;
382           case NGM_PPPOE_GET_STATUS:	msg = "GET_STATUS";	break;
383           default:
384             snprintf(unknown, sizeof unknown, "<%d>", (int)rep->header.cmd);
385             msg = unknown;
386             break;
387         }
388 
389         switch (rep->header.cmd) {
390           case NGM_PPPOE_FAIL:
391           case NGM_PPPOE_CLOSE:
392             syslog(LOG_ERR, "Received NGM_PPPOE_%s (hook \"%s\")",
393                    msg, sts->hook);
394             _exit(0);
395         }
396 
397         syslog(LOG_INFO, "Received NGM_PPPOE_%s (hook \"%s\")", msg, sts->hook);
398       } while (rep->header.cmd != NGM_PPPOE_SUCCESS);
399 
400       dup2(ds, STDIN_FILENO);
401       dup2(ds, STDOUT_FILENO);
402       close(ds);
403       close(cs);
404 
405       setsid();
406       syslog(LOG_INFO, "Executing: %s", exec);
407       execlp(_PATH_BSHELL, _PATH_BSHELL, "-c", exec, NULL);
408       syslog(LOG_ERR, "execlp failed: %m");
409       _exit(EX_OSFILE);
410 
411     default:
412       wait(&ret);
413       errno = ret;
414       if (errno)
415         syslog(LOG_ERR, "Second fork failed: %m");
416       break;
417   }
418 }
419 
420 #ifndef NOKLDLOAD
421 int
422 LoadModules(void)
423 {
424   const char *module[] = { "netgraph", "ng_socket", "ng_ether", "ng_pppoe" };
425   int f;
426 
427   for (f = 0; f < sizeof module / sizeof *module; f++)
428     if (modfind(module[f]) == -1 && kldload(module[f]) == -1) {
429       fprintf(stderr, "kldload: %s: %s\n", module[f], strerror(errno));
430       return 0;
431     }
432 
433   return 1;
434 }
435 #endif
436 
437 void
438 nglog(const char *fmt, ...)
439 {
440   char nfmt[256];
441   va_list ap;
442 
443   snprintf(nfmt, sizeof nfmt, "%s: %s", fmt, strerror(errno));
444   va_start(ap, fmt);
445   vsyslog(LOG_INFO, nfmt, ap);
446   va_end(ap);
447 }
448 
449 void
450 nglogx(const char *fmt, ...)
451 {
452   va_list ap;
453 
454   va_start(ap, fmt);
455   vsyslog(LOG_INFO, fmt, ap);
456   va_end(ap);
457 }
458 
459 int
460 main(int argc, char **argv)
461 {
462   char hostname[MAXHOSTNAMELEN], *exec, rhook[NG_HOOKLEN + 1];
463   unsigned char response[1024];
464   const char *prog, *provider, *acname;
465   struct ngm_connect ngc;
466   int ch, cs, ds, ret, optF, optd, optn, sz, f;
467 
468   prog = strrchr(argv[0], '/');
469   prog = prog ? prog + 1 : argv[0];
470   pidfile = NULL;
471   exec = NULL;
472   acname = NULL;
473   provider = "";
474   optF = optd = optn = 0;
475 
476   while ((ch = getopt(argc, argv, "FP:a:de:n:p:")) != -1) {
477     switch (ch) {
478       case 'F':
479         optF = 1;
480         break;
481 
482       case 'P':
483         pidfile = optarg;
484         break;
485 
486       case 'a':
487         acname = optarg;
488         break;
489 
490       case 'd':
491         optd = 1;
492         break;
493 
494       case 'e':
495         exec = optarg;
496         break;
497 
498       case 'n':
499         optn = 1;
500         NgSetDebug(atoi(optarg));
501         break;
502 
503       case 'p':
504         provider = optarg;
505         break;
506 
507       default:
508         return usage(prog);
509     }
510   }
511 
512   if (optind >= argc || optind + 2 < argc)
513     return usage(prog);
514 
515   if (exec == NULL) {
516     if (provider == NULL) {
517       fprintf(stderr, "%s: Either a provider or an exec command"
518               " must be given\n", prog);
519       return usage(prog);
520     }
521     exec = (char *)alloca(sizeof DEFAULT_EXEC_PREFIX + strlen(provider));
522     if (exec == NULL) {
523       fprintf(stderr, "%s: Cannot allocate %d bytes\n", prog,
524               (int)(sizeof DEFAULT_EXEC_PREFIX) + strlen(provider));
525       return EX_OSERR;
526     }
527     strcpy(exec, DEFAULT_EXEC_PREFIX);
528     strcpy(exec + sizeof DEFAULT_EXEC_PREFIX - 1, provider);
529   }
530 
531   if (acname == NULL) {
532     char *dot;
533 
534     if (gethostname(hostname, sizeof hostname))
535       strcpy(hostname, "localhost");
536     else if ((dot = strchr(hostname, '.')))
537       *dot = '\0';
538 
539     acname = hostname;
540   }
541 
542 #ifndef NOKLDLOAD
543   if (!LoadModules())
544     return EX_UNAVAILABLE;
545 #endif
546 
547   /* Create a socket node */
548   if (NgMkSockNode(NULL, &cs, &ds) == -1) {
549     perror("Cannot create netgraph socket node");
550     return EX_CANTCREAT;
551   }
552 
553   /* Connect it up (and fill in `ngc') */
554   if ((ret = ConfigureNode(prog, argv[optind], provider, cs, ds,
555                            optd, &ngc)) != 0) {
556     close(cs);
557     close(ds);
558     return ret;
559   }
560 
561   if (!optF && daemon(1, 0) == -1) {
562     perror("daemon()");
563     close(cs);
564     close(ds);
565     return EX_OSERR;
566   }
567 
568 
569   if (pidfile != NULL) {
570     FILE *fp;
571 
572     if ((fp = fopen(pidfile, "w")) == NULL) {
573       perror(pidfile);
574       close(cs);
575       close(ds);
576       return EX_CANTCREAT;
577     } else {
578       fprintf(fp, "%d\n", (int)getpid());
579       fclose(fp);
580     }
581   }
582 
583   openlog(prog, LOG_PID | (optF ? LOG_PERROR : 0), LOG_DAEMON);
584   if (!optF && optn)
585     NgSetErrLog(nglog, nglogx);
586 
587   signal(SIGHUP, Fairwell);
588   signal(SIGINT, Fairwell);
589   signal(SIGQUIT, Fairwell);
590   signal(SIGTERM, Fairwell);
591 
592   while (1) {
593     if (*provider)
594       syslog(LOG_INFO, "Listening as provider %s", provider);
595     else
596       syslog(LOG_INFO, "Listening");
597 
598     switch (sz = NgRecvData(ds, response, sizeof response, rhook)) {
599       case -1:
600         syslog(LOG_INFO, "NgRecvData: %m");
601         break;
602       case 0:
603         syslog(LOG_INFO, "NgRecvData: socket closed");
604         break;
605       default:
606         if (optd) {
607           char *dbuf, *ptr;
608 
609           ptr = dbuf = alloca(sz * 2 + 1);
610           for (f = 0; f < sz; f++, ptr += 2)
611             sprintf(ptr, "%02x", (u_char)response[f]);
612           *ptr = '\0';
613           syslog(LOG_INFO, "Got %d bytes of data: %s", sz, dbuf);
614         }
615     }
616     if (sz <= 0) {
617       ret = EX_UNAVAILABLE;
618       break;
619     }
620     Spawn(prog, acname, exec, ngc, cs, ds, response, sz, optd);
621   }
622 
623   return ret;
624 }
625