Correct PPTP server firewall rules chain.
[tomato/davidwu.git] / release / src / router / xl2tpd / xl2tpd.c
blob7dacee777b02968aed02dbd4a41dc34e279042e4
1 /*
2 * Layer Two Tunnelling Protocol Daemon
3 * Copyright (C) 1998 Adtran, Inc.
4 * Copyright (C) 2002 Jeff McAdams
7 * Mark Spencer
9 * This software is distributed under the terms
10 * of the GPL, which you should have received
11 * along with this source.
13 * Main Daemon source.
17 #define _ISOC99_SOURCE
18 #define _XOPEN_SOURCE
19 #define _BSD_SOURCE
20 #define _XOPEN_SOURCE_EXTENDED
21 #define _GNU_SOURCE
23 #include <stdlib.h>
24 #include <sys/types.h>
25 #include <sys/utsname.h>
26 #include <sys/stat.h>
27 #include <sys/wait.h>
28 #include <stdio.h>
29 #include <stdarg.h>
30 #include <errno.h>
31 #include <unistd.h>
32 #include <time.h>
33 #if (__GLIBC__ < 2)
34 # if defined(FREEBSD) || defined(OPENBSD)
35 # include <sys/signal.h>
36 # elif defined(LINUX)
37 # include <bsd/signal.h>
38 # elif defined(SOLARIS)
39 # include <signal.h>
40 # endif
41 #else
42 # include <signal.h>
43 #endif
44 #ifndef LINUX
45 # include <sys/socket.h>
46 #endif
47 #include <netdb.h>
48 #include <string.h>
49 #include <strings.h>
50 #include <fcntl.h>
51 #include <netinet/in.h>
52 #include <arpa/inet.h>
53 #include <net/route.h>
54 #include <features.h>
55 #include <resolv.h>
56 #include <sys/ioctl.h>
57 #include "l2tp.h"
59 struct tunnel_list tunnels;
60 int rand_source;
61 int ppd = 1; /* Packet processing delay */
62 int control_fd; /* descriptor of control area */
63 char *args;
65 char *dial_no_tmp; /* jz: Dialnumber for Outgoing Call */
66 int switch_io = 0; /* jz: Switch for Incoming or Outgoing Call */
68 static void open_controlfd(void);
70 volatile sig_atomic_t sigterm_received;
71 volatile sig_atomic_t sigint_received;
72 volatile sig_atomic_t sigchld_received;
73 volatile sig_atomic_t sigusr1_received;;
74 volatile sig_atomic_t sighup_received;
76 void init_tunnel_list (struct tunnel_list *t)
78 t->head = NULL;
79 t->count = 0;
80 t->calls = 0;
83 /* Now sends to syslog instead - MvO */
84 void show_status (void)
86 struct schedule_entry *se;
87 struct tunnel *t;
88 struct call *c;
89 struct lns *tlns;
90 struct lac *tlac;
91 struct host *h;
92 unsigned long cnt = 0;
94 int s = 0;
95 l2tp_log (LOG_WARNING, "====== xl2tpd statistics ========\n");
96 l2tp_log (LOG_WARNING, " Scheduler entries:\n");
97 se = events;
98 while (se)
100 s++;
101 t = (struct tunnel *) se->data;
102 tlac = (struct lac *) se->data;
103 c = (struct call *) se->data;
104 if (se->func == &hello)
106 l2tp_log (LOG_WARNING, "%d: HELLO to %d\n", s, t->tid);
108 else if (se->func == &magic_lac_dial)
110 l2tp_log (LOG_WARNING, "%d: Magic dial on %s\n", s, tlac->entname);
112 else if (se->func == &send_zlb)
114 l2tp_log (LOG_WARNING, "%d: Send payload ZLB on call %d:%d\n", s,
115 c->container->tid, c->cid);
117 else if (se->func == &dethrottle)
119 l2tp_log (LOG_WARNING, "%d: Dethrottle call %d:%d\n", s, c->container->tid,
120 c->cid);
122 else if (se->func == &control_xmit)
124 l2tp_log (LOG_WARNING, "%d: Control xmit on %d\n", s,((struct buffer *)se->data)->tunnel->tid);
126 else
127 l2tp_log (LOG_WARNING, "%d: Unknown event\n", s);
128 se = se->next;
130 l2tp_log (LOG_WARNING, "Total Events scheduled: %d\n", s);
131 l2tp_log (LOG_WARNING, "Number of tunnels open: %d\n", tunnels.count);
132 t = tunnels.head;
133 while (t)
135 l2tp_log (LOG_WARNING, "Tunnel %s, ID = %d (local), %d (remote) to %s:%d,"
136 " control_seq_num = %d, control_rec_seq_num = %d,"
137 " cLr = %d, call count = %d ref=%u/refhim=%u",
138 (t->lac ? t->lac->entname : (t->lns ? t->lns->entname : "")),
139 t->ourtid, t->tid, IPADDY (t->peer.sin_addr),
140 ntohs (t->peer.sin_port), t->control_seq_num,
141 t->control_rec_seq_num, t->cLr, t->count,
142 t->refme, t->refhim);
143 c = t->call_head;
144 while (c)
146 cnt++;
147 l2tp_log (LOG_WARNING,
148 "Call %s # %lu, ID = %d (local), %d (remote), serno = %u,"
149 " data_seq_num = %d, data_rec_seq_num = %d,"
150 " pLr = %d, tx = %u bytes (%u), rx= %u bytes (%u)",
151 (c->lac ? c->lac->
152 entname : (c->lns ? c->lns->entname : "")),
153 cnt, c->ourcid,
154 c->cid, c->serno, c->data_seq_num, c->data_rec_seq_num,
155 c->pLr, c->tx_bytes, c->tx_pkts, c->rx_bytes, c->rx_pkts);
156 c = c->next;
158 t = t->next;
160 l2tp_log (LOG_WARNING, "==========Config File===========\n");
161 tlns = lnslist;
162 while (tlns)
164 l2tp_log (LOG_WARNING, "LNS entry %s\n",
165 tlns->entname[0] ? tlns->entname : "(unnamed)");
166 tlns = tlns->next;
168 tlac = laclist;
169 while (tlac)
171 l2tp_log (LOG_WARNING, "LAC entry %s, LNS is/are:",
172 tlac->entname[0] ? tlac->entname : "(unnamed)");
173 h = tlac->lns;
174 if (h)
176 while (h)
178 l2tp_log (LOG_WARNING, " %s", h->hostname);
179 h = h->next;
182 else
183 l2tp_log (LOG_WARNING, " [none]");
184 tlac = tlac->next;
186 l2tp_log (LOG_WARNING, "================================\n");
189 void null_handler(int sig)
191 /* FIXME
192 * A sighup is received when a call is terminated, unknown origine ..
193 * I catch it and ll looks good, but ..
197 void status_handler (int sig)
199 show_status ();
202 void child_handler (int signal)
205 * Oops, somebody we launched was killed.
206 * It's time to reap them and close that call.
207 * But first, we have to find out what PID died.
208 * unfortunately, pppd will
210 struct tunnel *t;
211 struct call *c;
212 pid_t pid;
213 int status;
214 /* Keep looping until all are cleared */
215 for(;;)
217 pid = waitpid (-1, &status, WNOHANG);
218 if (pid < 1)
221 * Oh well, nobody there. Maybe we reaped it
222 * somewhere else already
224 return;
226 /* find the call that "owned" the pppd which just died */
227 t = tunnels.head;
228 while (t)
230 c = t->call_head;
231 t = t->next;
232 while (c)
234 if (c->pppd == pid)
236 if ( WIFEXITED( status ) )
238 l2tp_log (LOG_DEBUG, "%s : pppd exited for call %d with code %d\n", __FUNCTION__,
239 c->cid, WEXITSTATUS( status ) );
241 else if( WIFSIGNALED( status ) )
243 l2tp_log (LOG_DEBUG, "%s : pppd terminated for call %d by signal %d\n", __FUNCTION__,
244 c->cid, WTERMSIG( status ) );
246 else
248 l2tp_log (LOG_DEBUG, "%s : pppd exited for call %d for unknown reason\n", __FUNCTION__,
249 c->cid );
251 c->needclose = -1;
253 * OK...pppd died, we can go ahead and close the pty for
254 * it
256 #ifdef USE_KERNEL
257 if (!kernel_support)
258 #endif
259 close (c->fd);
260 c->fd = -1;
262 * terminate tunnel and call loops, returning to the
263 * for(;;) loop (and possibly get the next pid)
265 t = NULL;
266 break;
268 c = c->next;
274 void death_handler (int signal)
277 * If we get here, somebody terminated us with a kill or a control-c.
278 * we call call_close on each tunnel twice to get a StopCCN out
279 * for each one (we can't pause to make sure it's received.
280 * Then we close the connections
282 struct tunnel *st, *st2;
283 int sec;
284 l2tp_log (LOG_CRIT, "%s: Fatal signal %d received\n", __FUNCTION__, signal);
285 #ifdef USE_KERNEL
286 if (kernel_support || signal != SIGTERM) {
287 #else
288 if (signal != SIGTERM) {
289 #endif
290 st = tunnels.head;
291 while (st)
293 st2 = st->next;
294 strcpy (st->self->errormsg, "Server closing");
295 sec = st->self->closing;
296 if (st->lac)
297 st->lac->redial = 0;
298 call_close (st->self);
299 if (!sec)
301 st->self->closing = -1;
302 call_close (st->self);
304 st = st2;
308 /* erase pid and control files */
309 unlink (gconfig.pidfile);
310 unlink (gconfig.controlfile);
312 exit (1);
315 void sigterm_handler(int sig)
317 sigterm_received = 1;
320 void sigint_handler(int sig)
322 sigint_received = 1;
325 void sigchld_handler(int sig)
327 sigchld_received = 1;
330 void sigusr1_handler(int sig)
332 sigusr1_received = 1;
335 void sighup_handler(int sig)
337 sighup_received = 1;
340 void process_signal(void)
342 if (sigterm_received) { sigterm_received = 0; death_handler(SIGTERM); }
343 if (sigint_received) { sigint_received = 0; death_handler(SIGINT); }
344 if (sigchld_received) { sigchld_received = 0; child_handler(SIGCHLD); }
345 if (sigusr1_received) { sigusr1_received = 0; status_handler(SIGUSR1); }
346 if (sighup_received) { sighup_received = 0; null_handler(SIGHUP); }
349 int start_pppd (struct call *c, struct ppp_opts *opts)
351 /* char a, b; */
352 char tty[512];
353 char *stropt[80];
354 struct ppp_opts *p;
355 #ifdef USE_KERNEL
356 struct sockaddr_pppol2tp sax;
357 int flags;
358 #endif
359 int pos = 1;
360 int fd2 = -1;
361 #ifdef DEBUG_PPPD
362 int x;
363 #endif
364 struct termios ptyconf;
365 struct call *sc;
366 struct tunnel *st;
368 p = opts;
369 stropt[0] = strdup (PPPD);
370 while (p)
372 stropt[pos] = (char *) malloc (strlen (p->option) + 1);
373 strncpy (stropt[pos], p->option, strlen (p->option) + 1);
374 pos++;
375 p = p->next;
377 stropt[pos] = NULL;
378 if (c->pppd > 0)
380 l2tp_log(LOG_WARNING, "%s: PPP already started on call!\n", __FUNCTION__);
381 return -EINVAL;
383 if (c->fd > -1)
385 l2tp_log (LOG_WARNING, "%s: file descriptor already assigned!\n",
386 __FUNCTION__);
387 return -EINVAL;
390 #ifdef USE_KERNEL
391 if (kernel_support)
393 fd2 = socket(AF_PPPOX, SOCK_DGRAM, PX_PROTO_OL2TP);
394 if (fd2 < 0) {
395 l2tp_log (LOG_WARNING, "%s: Unable to allocate PPPoL2TP socket.\n",
396 __FUNCTION__);
397 return -EINVAL;
399 flags = fcntl(fd2, F_GETFL);
400 if (flags == -1 || fcntl(fd2, F_SETFL, flags | O_NONBLOCK) == -1) {
401 l2tp_log (LOG_WARNING, "%s: Unable to set PPPoL2TP socket nonblock.\n",
402 __FUNCTION__);
403 return -EINVAL;
405 sax.sa_family = AF_PPPOX;
406 sax.sa_protocol = PX_PROTO_OL2TP;
407 sax.pppol2tp.pid = 0;
408 sax.pppol2tp.fd = c->container->udp_fd;
409 sax.pppol2tp.addr.sin_addr.s_addr = c->container->peer.sin_addr.s_addr;
410 sax.pppol2tp.addr.sin_port = c->container->peer.sin_port;
411 sax.pppol2tp.addr.sin_family = AF_INET;
412 sax.pppol2tp.s_tunnel = c->container->ourtid;
413 sax.pppol2tp.s_session = c->ourcid;
414 sax.pppol2tp.d_tunnel = c->container->tid;
415 sax.pppol2tp.d_session = c->cid;
416 if (connect(fd2, (struct sockaddr *)&sax, sizeof(sax)) < 0) {
417 l2tp_log (LOG_WARNING, "%s: Unable to connect PPPoL2TP socket.\n",
418 __FUNCTION__);
419 close(fd2);
420 return -EINVAL;
422 stropt[pos++] = strdup ("plugin");
423 stropt[pos++] = strdup ("pppol2tp.so");
424 stropt[pos++] = strdup ("pppol2tp");
425 stropt[pos] = (char *) malloc (10);
426 snprintf (stropt[pos], 10, "%d", fd2);
427 pos++;
428 stropt[pos] = NULL;
430 else
431 #endif
433 if ((c->fd = getPtyMaster (tty, sizeof(tty))) < 0)
435 l2tp_log (LOG_WARNING, "%s: unable to allocate pty, abandoning!\n",
436 __FUNCTION__);
437 return -EINVAL;
440 /* set fd opened above to not echo so we don't see read our own packets
441 back of the file descriptor that we just wrote them to */
442 tcgetattr (c->fd, &ptyconf);
443 *(c->oldptyconf) = ptyconf;
444 ptyconf.c_cflag &= ~(ICANON | ECHO);
445 ptyconf.c_lflag &= ~ECHO;
446 tcsetattr (c->fd, TCSANOW, &ptyconf);
447 if(fcntl(c->fd, F_SETFL, O_NONBLOCK)!=0) {
448 l2tp_log(LOG_WARNING, "failed to set nonblock: %s\n", strerror(errno));
449 return -EINVAL;
452 fd2 = open (tty, O_RDWR);
453 if (fd2 < 0) {
454 l2tp_log (LOG_WARNING, "unable to open tty %s, cannot start pppd", tty);
455 return -EINVAL;
457 stropt[pos++] = strdup(tty);
458 stropt[pos] = NULL;
461 #ifdef DEBUG_PPPD
462 l2tp_log (LOG_DEBUG, "%s: I'm running: \n", __FUNCTION__);
463 for (x = 0; stropt[x]; x++)
465 l2tp_log (LOG_DEBUG, "\"%s\" \n", stropt[x]);
467 #endif
468 #ifdef __uClinux__
469 c->pppd = vfork ();
470 #else
471 c->pppd = fork ();
472 #endif
474 if (c->pppd < 0)
476 /* parent */
477 l2tp_log(LOG_WARNING,"%s: unable to fork(), abandoning!\n", __FUNCTION__);
478 return -EINVAL;
480 else if (!c->pppd)
482 /* child */
484 close (0); /* redundant; the dup2() below would do that, too */
485 close (1); /* ditto */
486 /* close (2); No, we want to keep the connection to /dev/null. */
487 #ifdef USE_KERNEL
488 if (!kernel_support)
489 #endif
492 /* connect the pty to stdin and stdout */
493 dup2 (fd2, 0);
494 dup2 (fd2, 1);
495 close(fd2);
497 /* close all the calls pty fds */
498 st = tunnels.head;
499 while (st)
501 sc = st->call_head;
502 while (sc)
504 #ifdef USE_KERNEL
505 if (kernel_support) {
506 close(st->udp_fd); /* tunnel UDP fd */
507 close(st->pppox_fd); /* tunnel PPPoX fd */
508 } else
509 #endif
510 close (sc->fd); /* call pty fd */
511 sc = sc->next;
513 st = st->next;
516 /* close the UDP socket fd */
517 close (server_socket);
519 /* close the control pipe fd */
520 close (control_fd);
522 if( c->dialing[0] )
524 setenv( "CALLER_ID", c->dialing, 1 );
526 execv (PPPD, stropt);
527 l2tp_log (LOG_WARNING, "%s: Exec of %s failed!\n", __FUNCTION__, PPPD);
528 _exit (1);
530 close (fd2);
531 pos = 0;
532 while (stropt[pos])
534 free (stropt[pos]);
535 pos++;
537 return 0;
540 void destroy_tunnel (struct tunnel *t)
543 * Immediately destroy a tunnel (and all its calls)
544 * and free its resources. This may be called
545 * by the tunnel itself,so it needs to be
546 * "suicide safe"
549 struct call *c, *me;
550 struct tunnel *p;
551 struct timeval tv;
552 if (!t)
553 return;
556 * Save ourselves until the very
557 * end, since we might be calling this ourselves.
558 * We must divorce ourself from the tunnel
559 * structure, however, to avoid recursion
560 * because of the logic of the destroy_call
562 me = t->self;
565 * Destroy all the member calls
567 c = t->call_head;
568 while (c)
570 destroy_call (c);
571 c = c->next;
574 * Remove ourselves from the list of tunnels
577 if (tunnels.head == t)
579 tunnels.head = t->next;
580 tunnels.count--;
582 else
584 p = tunnels.head;
585 if (p)
587 while (p->next && (p->next != t))
588 p = p->next;
589 if (p->next)
591 p->next = t->next;
592 tunnels.count--;
594 else
596 l2tp_log (LOG_WARNING,
597 "%s: unable to locate tunnel in tunnel list\n",
598 __FUNCTION__);
601 else
603 l2tp_log (LOG_WARNING, "%s: tunnel list is empty!\n", __FUNCTION__);
606 if (t->lac)
608 t->lac->t = NULL;
609 if (t->lac->redial && (t->lac->rtimeout > 0) && !t->lac->rsched &&
610 t->lac->active)
612 l2tp_log (LOG_INFO, "Will redial in %d seconds\n",
613 t->lac->rtimeout);
614 tv.tv_sec = t->lac->rtimeout;
615 tv.tv_usec = 0;
616 t->lac->rsched = schedule (tv, magic_lac_dial, t->lac);
619 /* XXX L2TP/IPSec: remove relevant SAs here? NTB 20011010
620 * XXX But what if another tunnel is using same SA?
622 if (t->lns)
623 t->lns->t = NULL;
624 if (t->chal_us.challenge)
625 free (t->chal_us.challenge);
626 if (t->chal_them.challenge)
627 free (t->chal_them.challenge);
628 /* we need no free(t->chal_us.vector) here because we malloc() and free()
629 the memory pointed to by t->chal_us.vector at some other place */
630 if (t->chal_them.vector)
631 free (t->chal_them.vector);
632 if (t->pppox_fd > -1 )
633 close (t->pppox_fd);
634 if (t->udp_fd > -1 )
635 close (t->udp_fd);
636 route_del(&t->rt);
637 free (t);
638 free (me);
641 struct tunnel *l2tp_call (char *host, int port, struct lac *lac,
642 struct lns *lns)
645 * Establish a tunnel from us to host
646 * on port port
648 struct call *tmp = NULL;
649 struct hostent *hp;
650 struct in_addr addr;
652 #if !defined(__UCLIBC__) \
653 || (__UCLIBC_MAJOR__ == 0 \
654 && (__UCLIBC_MINOR__ < 9 || (__UCLIBC_MINOR__ == 9 && __UCLIBC_SUBLEVEL__ < 31)))
655 /* force ns refresh from resolv.conf with uClibc pre-0.9.31 */
656 res_init();
657 #endif
659 port = htons (port);
660 hp = gethostbyname (host);
661 if (!hp)
663 l2tp_log (LOG_WARNING, "Host name lookup failed for %s.\n",
664 host);
665 return NULL;
667 bcopy (hp->h_addr, &addr.s_addr, hp->h_length);
668 /* Force creation of a new tunnel
669 and set it's tid to 0 to cause
670 negotiation to occur */
672 * to do IPsec properly here, we need to set a socket policy,
673 * and/or communicate with pluto.
675 tmp = get_call (0, 0, addr, port, IPSEC_SAREF_NULL, IPSEC_SAREF_NULL);
676 if (!tmp)
678 l2tp_log (LOG_WARNING, "%s: Unable to create tunnel to %s.\n", __FUNCTION__,
679 host);
680 return NULL;
682 tmp->container->tid = 0;
683 tmp->container->lac = lac;
684 tmp->container->lns = lns;
685 tmp->lac = lac;
686 tmp->lns = lns;
687 if (lac)
688 lac->t = tmp->container;
689 if (lns)
690 lns->t = tmp->container;
692 * Since our state is 0, we will establish a tunnel now
694 l2tp_log (LOG_NOTICE, "Connecting to host %s, port %d\n", host,
695 ntohs (port));
696 control_finish (tmp->container, tmp);
697 return tmp->container;
700 void magic_lac_tunnel (void *data)
702 struct lac *lac;
703 lac = (struct lac *) data;
704 if (!lac)
706 l2tp_log (LOG_WARNING, "%s: magic_lac_tunnel: called on NULL lac!\n",
707 __FUNCTION__);
708 return;
710 if (lac->lns)
712 /* FIXME: I should try different LNS's if I get failures */
713 l2tp_call (lac->lns->hostname, lac->lns->port, lac, NULL);
714 return;
716 else if (deflac && deflac->lns)
718 l2tp_call (deflac->lns->hostname, deflac->lns->port, lac, NULL);
719 return;
721 else
723 l2tp_log (LOG_WARNING, "%s: Unable to find hostname to dial for '%s'\n",
724 __FUNCTION__, lac->entname);
725 return;
729 struct call *lac_call (int tid, struct lac *lac, struct lns *lns)
731 struct tunnel *t = tunnels.head;
732 struct call *tmp;
733 while (t)
735 if (t->ourtid == tid)
737 tmp = new_call (t);
738 if (!tmp)
740 l2tp_log (LOG_WARNING, "%s: unable to create new call\n",
741 __FUNCTION__);
742 return NULL;
744 tmp->next = t->call_head;
745 t->call_head = tmp;
746 t->count++;
747 tmp->cid = 0;
748 tmp->lac = lac;
749 tmp->lns = lns;
750 if (lac)
751 lac->c = tmp;
752 l2tp_log (LOG_NOTICE, "Calling on tunnel %d\n", tid);
753 strcpy (tmp->dial_no, dial_no_tmp); /* jz: copy dialnumber to tmp->dial_no */
754 control_finish (t, tmp);
755 return tmp;
757 t = t->next;
759 l2tp_log (LOG_DEBUG, "%s: No such tunnel %d to generate call.\n", __FUNCTION__,
760 tid);
761 return NULL;
764 void magic_lac_dial (void *data)
766 struct lac *lac;
767 lac = (struct lac *) data;
768 if (!lac)
770 l2tp_log (LOG_WARNING, "%s : called on NULL lac!\n", __FUNCTION__);
771 return;
773 if (!lac->active)
775 l2tp_log (LOG_DEBUG, "%s: LAC %s not active", __FUNCTION__, lac->entname);
776 return;
778 lac->rsched = NULL;
779 lac->rtries++;
780 if (lac->rmax && (lac->rtries > lac->rmax))
782 l2tp_log (LOG_INFO, "%s: maximum retries exceeded.\n", __FUNCTION__);
783 return;
785 if (!lac->t)
787 #ifdef DEGUG_MAGIC
788 l2tp_log (LOG_DEBUG, "%s : tunnel not up! Connecting!\n", __FUNCTION__);
789 #endif
790 magic_lac_tunnel (lac);
791 return;
793 lac_call (lac->t->ourtid, lac, NULL);
796 void lac_hangup (int cid)
798 struct tunnel *t = tunnels.head;
799 struct call *tmp;
800 while (t)
802 tmp = t->call_head;
803 while (tmp)
805 if (tmp->ourcid == cid)
807 l2tp_log (LOG_INFO,
808 "%s :Hanging up call %d, Local: %d, Remote: %d\n",
809 __FUNCTION__, tmp->serno, tmp->ourcid, tmp->cid);
810 strcpy (tmp->errormsg, "Goodbye!");
811 /* tmp->needclose = -1; */
812 kill (tmp->pppd, SIGTERM);
813 return;
815 tmp = tmp->next;
817 t = t->next;
819 l2tp_log (LOG_DEBUG, "%s : No such call %d to hang up.\n", __FUNCTION__, cid);
820 return;
823 void lac_disconnect (int tid)
825 struct tunnel *t = tunnels.head;
826 while (t)
828 if (t->ourtid == tid)
830 l2tp_log (LOG_INFO,
831 "Disconnecting from %s, Local: %d, Remote: %d\n",
832 IPADDY (t->peer.sin_addr), t->ourtid, t->tid);
833 t->self->needclose = -1;
834 strcpy (t->self->errormsg, "Goodbye!");
835 call_close (t->self);
836 return;
838 t = t->next;
840 l2tp_log (LOG_DEBUG, "No such tunnel %d to hang up.\n", tid);
841 return;
844 struct tunnel *new_tunnel ()
846 struct tunnel *tmp = malloc (sizeof (struct tunnel));
847 unsigned char entropy_buf[2] = "\0";
848 if (!tmp)
849 return NULL;
850 tmp->control_seq_num = 0;
851 tmp->control_rec_seq_num = 0;
852 tmp->cLr = 0;
853 tmp->call_head = NULL;
854 tmp->next = NULL;
855 tmp->debug = -1;
856 tmp->tid = -1;
857 tmp->hello = NULL;
858 #ifndef TESTING
859 /* while(get_call((tmp->ourtid = rand() & 0xFFFF),0,0,0)); */
860 /* tmp->ourtid = rand () & 0xFFFF; */
861 /* get_entropy((char *)&tmp->ourtid, 2); */
862 get_entropy(entropy_buf, 2);
864 unsigned short *temp;
865 temp = (unsigned short *)entropy_buf;
866 tmp->ourtid = *temp & 0xFFFF;
867 #ifdef DEBUG_ENTROPY
868 l2tp_log(LOG_DEBUG, "ourtid = %u, entropy_buf = %hx\n", tmp->ourtid, *temp);
869 #endif
872 #else
873 tmp->ourtid = 0x6227;
874 #endif
875 tmp->nego = 0;
876 tmp->count = 0;
877 tmp->state = 0; /* Nothing */
878 tmp->peer.sin_family = AF_INET;
879 tmp->peer.sin_port = 0;
880 bzero (&(tmp->peer.sin_addr), sizeof (tmp->peer.sin_addr));
881 #ifdef SANITY
882 tmp->sanity = -1;
883 #endif
884 tmp->qtid = -1;
885 tmp->ourfc = ASYNC_FRAMING | SYNC_FRAMING;
886 tmp->ourbc = 0;
887 tmp->ourtb = (((_u64) rand ()) << 32) | ((_u64) rand ());
888 tmp->fc = -1; /* These really need to be specified by the peer */
889 tmp->bc = -1; /* And we want to know if they forgot */
890 tmp->hostname[0] = 0;
891 tmp->vendor[0] = 0;
892 tmp->secret[0] = 0;
893 if (!(tmp->self = new_call (tmp)))
895 free (tmp);
896 return NULL;
898 tmp->ourrws = DEFAULT_RWS_SIZE;
899 tmp->self->ourfbit = FBIT;
900 tmp->rxspeed = DEFAULT_RX_BPS;
901 tmp->txspeed = DEFAULT_TX_BPS;
902 tmp->lac = NULL;
903 tmp->lns = NULL;
904 tmp->chal_us.state = 0;
905 tmp->chal_us.secret[0] = 0;
906 memset (tmp->chal_us.reply, 0, MD_SIG_SIZE);
907 tmp->chal_us.challenge = NULL;
908 tmp->chal_us.chal_len = 0;
909 tmp->chal_them.state = 0;
910 tmp->chal_them.secret[0] = 0;
911 memset (tmp->chal_them.reply, 0, MD_SIG_SIZE);
912 tmp->chal_them.challenge = NULL;
913 tmp->chal_them.chal_len = 0;
914 tmp->chal_them.vector = (unsigned char *) malloc (VECTOR_SIZE);
915 tmp->chal_us.vector = NULL;
916 tmp->hbit = 0;
917 return tmp;
920 void write_res (FILE* res_file, const char *fmt, ...)
922 if (!res_file || ferror (res_file) || feof (res_file))
923 return;
924 va_list args;
925 va_start (args, fmt);
926 vfprintf (res_file, fmt, args);
927 va_end (args);
930 int parse_one_line_lac (char* bufp, struct lac *tc)
932 /* FIXME: I should check for incompatible options */
933 char *s, *d, *t;
934 int linenum = 0;
936 s = strtok (bufp, ";");
937 // parse options token by token
938 while (s != NULL)
940 linenum++;
942 while ((*s < 33) && *s)
943 s++; /* Skip over beginning white space */
944 t = s + strlen (s);
945 while ((t >= s) && (*t < 33))
946 *(t--) = 0; /* Ditch trailing white space */
947 if (!strlen (s))
948 continue;
949 if (!(t = strchr (s, '=')))
951 l2tp_log (LOG_WARNING, "%s: token %d: no '=' in data\n",
952 __FUNCTION__, linenum);
953 return -1;
955 d = t;
956 d--;
957 t++;
958 while ((d >= s) && (*d < 33))
959 d--;
960 d++;
961 *d = 0;
962 while (*t && (*t < 33))
963 t++;
964 #ifdef DEBUG_CONTROL
965 l2tp_log (LOG_DEBUG, "%s: field is %s, value is %s\n",
966 __FUNCTION__, s, t);
967 #endif
968 /* Okay, bit twidling is done. Let's handle this */
970 switch (parse_one_option (s, t, CONTEXT_LAC, tc))
972 case -1:
973 l2tp_log (LOG_WARNING, "%s: error token %d\n",
974 __FUNCTION__, linenum);
975 return -1;
976 case -2:
977 l2tp_log (LOG_CRIT, "%s: token %d: Unknown field '%s'\n",
978 __FUNCTION__, linenum, s);
979 return -1;
982 s = strtok (NULL, ";");
984 return 0;
987 void do_control ()
989 char buf[CONTROL_PIPE_MESSAGE_SIZE];
990 char *bufp; /* current buffer pointer */
991 char *host;
992 char *tunstr;
993 char *callstr;
995 char *authname = NULL;
996 char *password = NULL;
997 char delims[] = " ";
998 char *sub_str; /* jz: use by the strtok function */
999 char *tmp_ptr; /* jz: use by the strtok function */
1000 struct lac *lac;
1001 struct lac *prev_lac; /* for lac removing */
1002 int call;
1003 int tunl;
1004 int cnt = -1;
1005 int done = 0;
1007 bzero(buf, sizeof(buf));
1008 buf[0]='\0';
1010 char* res_filename; /* name of file to write result of command */
1011 FILE* resf; /* stream for write result of command */
1013 while (!done)
1015 cnt = read (control_fd, buf, sizeof (buf));
1016 if (cnt <= 0)
1018 if(cnt < 0 && errno != EINTR) {
1019 perror("controlfd");
1021 done = 1;
1022 break;
1025 if (buf[cnt - 1] == '\n')
1026 buf[--cnt] = 0;
1027 #ifdef DEBUG_CONTROL
1028 l2tp_log (LOG_DEBUG, "%s: Got message %s (%d bytes long)\n",
1029 __FUNCTION__, buf, cnt);
1030 #endif
1031 bufp = buf;
1032 /* check if caller want to get result */
1033 if (bufp[0] == '@')
1035 /* parse filename (@/path/to/file *...), where * is command */
1036 res_filename = &bufp[1];
1037 int fnlength = strcspn(res_filename, " ");
1038 if ((fnlength == 0) || (res_filename[fnlength] == '\0')){
1039 l2tp_log (LOG_DEBUG,
1040 "%s: Can't parse result filename or command\n",
1041 __FUNCTION__
1043 continue;
1045 res_filename[fnlength] = '\0';
1046 bufp = &res_filename[fnlength + 1]; /* skip filename in bufp */
1048 /*FIXME: check quotes to allow filenames with spaces?
1049 (do not forget quotes escaping to allow filenames with quotes)*/
1051 /*FIXME: write to res_filename may cause SIGPIPE, need to catch it*/
1052 resf = fopen (res_filename, "w");
1053 if (!resf) {
1054 l2tp_log (LOG_DEBUG, "%s: Can't open result file %s\n",
1055 __FUNCTION__, res_filename);
1056 continue;
1058 } else
1059 resf = NULL;
1061 switch (bufp[0])
1063 case 't':
1064 host = strchr (bufp, ' ') + 1;
1065 #ifdef DEBUG_CONTROL
1066 l2tp_log (LOG_DEBUG, "%s: Attempting to tunnel to %s\n",
1067 __FUNCTION__, host);
1068 #endif
1069 if (l2tp_call (host, UDP_LISTEN_PORT, NULL, NULL))
1070 write_res (resf, "%02i OK\n", 0);
1071 else
1072 write_res (resf, "%02i Error\n", 1);
1073 break;
1074 case 'c':
1075 switch_io = 1; /* jz: Switch for Incoming - Outgoing Calls */
1077 tunstr = strtok (&bufp[1], delims);
1079 /* Are these passed on the command line? */
1080 authname = strtok (NULL, delims);
1081 password = strtok (NULL, delims);
1083 lac = laclist;
1084 while (lac && strcasecmp (lac->entname, tunstr)!=0)
1086 lac = lac->next;
1089 if(lac) {
1090 lac->active = -1;
1091 lac->rtries = 0;
1092 if (authname != NULL)
1093 strncpy (lac->authname, authname, STRLEN);
1094 if (password != NULL)
1095 strncpy (lac->password, password, STRLEN);
1096 if (!lac->c)
1098 magic_lac_dial (lac);
1099 write_res (resf, "%02i OK\n", 0);
1100 } else {
1101 l2tp_log (LOG_DEBUG,
1102 "Session '%s' already active!\n", lac->entname);
1103 write_res (resf, "%02i Session '%s' already active!\n", 1,
1104 lac->entname);
1106 break;
1109 /* did not find a tunnel by name, look by number */
1110 tunl = atoi (tunstr);
1111 if (!tunl)
1113 l2tp_log (LOG_DEBUG, "No such tunnel '%s'\n", tunstr);
1114 write_res (resf, "%02i No such tunnel '%s'\n", 1, tunstr);
1115 break;
1117 #ifdef DEBUG_CONTROL
1118 l2tp_log (LOG_DEBUG, "%s: Attempting to call on tunnel %d\n",
1119 __FUNCTION__, tunl);
1120 #endif
1121 if (lac_call (tunl, NULL, NULL))
1122 write_res (resf, "%02i OK\n", 0);
1123 else
1124 write_res (resf, "%02i Error\n", 1);
1125 break;
1127 case 'o': /* jz: option 'o' for doing a outgoing call */
1128 switch_io = 0; /* jz: Switch for incoming - outgoing Calls */
1130 sub_str = strchr (bufp, ' ') + 1;
1131 tunstr = strtok (sub_str, " "); /* jz: using strtok function to get */
1132 tmp_ptr = strtok (NULL, " "); /* params out of the pipe */
1133 strcpy (dial_no_tmp, tmp_ptr);
1135 lac = laclist;
1136 while (lac && strcasecmp (lac->entname, tunstr)!=0)
1138 lac = lac->next;
1141 if(lac) {
1142 lac->active = -1;
1143 lac->rtries = 0;
1144 if (!lac->c)
1146 magic_lac_dial (lac);
1147 write_res (resf, "%02i OK\n", 0);
1148 } else {
1149 l2tp_log (LOG_DEBUG, "Session '%s' already active!\n",
1150 lac->entname);
1151 write_res (resf, "%02i Session '%s' already active!\n", 1,
1152 lac->entname);
1154 break;
1157 /* did not find a tunnel by name, look by number */
1158 tunl = atoi (tunstr);
1159 if (!tunl)
1161 l2tp_log (LOG_DEBUG, "No such tunnel '%s'\n", tunstr);
1162 write_res (resf, "%02i No such tunnel '%s'\n", 1, tunstr);
1163 break;
1165 #ifdef DEBUG_CONTROL
1166 l2tp_log (LOG_DEBUG, "%s: Attempting to call on tunnel %d\n",
1167 __FUNCTION__, tunl);
1168 #endif
1169 if (lac_call (tunl, NULL, NULL))
1170 write_res (resf, "%02i OK\n", 0);
1171 else
1172 write_res (resf, "%02i Error\n", 1);
1173 break;
1175 case 'h':
1176 callstr = strchr (bufp, ' ') + 1;
1177 call = atoi (callstr);
1178 #ifdef DEBUG_CONTROL
1179 l2tp_log (LOG_DEBUG, "%s: Attempting to hangup call %d\n", __FUNCTION__,
1180 call);
1181 #endif
1182 lac_hangup (call);
1183 write_res (resf, "%02i OK\n", 0);
1184 break;
1186 case 'd':
1187 tunstr = strchr (bufp, ' ') + 1;
1188 lac = laclist;
1189 while (lac)
1191 if (!strcasecmp (lac->entname, tunstr))
1193 lac->active = 0;
1194 lac->rtries = 0;
1195 if (lac->t)
1197 lac_disconnect (lac->t->ourtid);
1198 write_res (resf, "%02i OK\n", 0);
1199 } else {
1200 l2tp_log (LOG_DEBUG, "Session '%s' not up\n",
1201 lac->entname);
1202 write_res (resf, "%02i Session '%s' not up\n", 1,
1203 lac->entname);
1205 break;
1207 lac = lac->next;
1209 if (lac)
1210 break;
1211 tunl = atoi (tunstr);
1212 if (!tunl)
1214 l2tp_log (LOG_DEBUG, "No such tunnel '%s'\n", tunstr);
1215 write_res (resf, "%02i No such tunnel '%s'\n", 1, tunstr);
1216 break;
1218 #ifdef DEBUG_CONTROL
1219 l2tp_log (LOG_DEBUG, "%s: Attempting to disconnect tunnel %d\n",
1220 __FUNCTION__, tunl);
1221 #endif
1222 lac_disconnect (tunl);
1223 write_res (resf, "%02i OK\n", 0);
1224 break;
1225 case 's':
1226 show_status ();
1227 break;
1228 case 'a':
1229 /* add new or modify existing lac configuration */
1231 int create_new_lac = 0;
1232 tunstr = strtok (&bufp[1], delims);
1233 if ((!tunstr) || (!strlen (tunstr)))
1235 write_res (resf,
1236 "%02i Configuration parse error: lac-name expected\n", 1);
1237 l2tp_log (LOG_CRIT, "%s: lac-name expected\n", __FUNCTION__);
1238 break;
1240 /* go to the end of tunnel name*/
1241 bufp = tunstr + strlen (tunstr) + 1;
1242 /* try to find lac with _tunstr_ name in laclist */
1243 lac = laclist;
1244 while (lac)
1246 if (!strcasecmp (tunstr, lac->entname))
1247 break;
1248 lac = lac->next;
1250 if (!lac)
1252 /* nothing found, create new lac */
1253 lac = new_lac ();
1254 if (!lac)
1256 write_res (resf,
1257 "%02i Could't create new lac: no memory\n", 2);
1258 l2tp_log (LOG_CRIT,
1259 "%s: Couldn't create new lac\n", __FUNCTION__);
1260 break;
1262 create_new_lac = 1;
1264 strncpy (lac->entname, tunstr, sizeof (lac->entname));
1266 if (parse_one_line_lac (bufp, lac))
1268 write_res (resf, "%02i Configuration parse error\n", 3);
1269 break;
1271 if (create_new_lac)
1273 lac->next = laclist;
1274 laclist = lac;
1276 if (lac->autodial)
1278 #ifdef DEBUG_MAGIC
1279 l2tp_log (LOG_DEBUG, "%s: Autodialing '%s'\n", __FUNCTION__,
1280 lac->entname[0] ? lac->entname : "(unnamed)");
1281 #endif
1282 lac->active = -1;
1283 switch_io = 1; /* If we're a LAC, autodials will be ICRQ's */
1284 magic_lac_dial (lac);
1285 /* FIXME: Should I check magic_lac_dial result somehow? */
1287 write_res (resf, "%02i OK\n", 0);
1289 break;
1290 case 'r':
1291 // find lac in laclist
1292 tunstr = strchr (bufp, ' ') + 1;
1293 lac = laclist;
1294 prev_lac = NULL;
1295 while (lac && strcasecmp (lac->entname, tunstr) != 0)
1297 prev_lac = lac;
1298 lac = lac->next;
1300 if (!lac)
1302 l2tp_log (LOG_DEBUG, "No such tunnel '%s'\n",
1303 tunstr);
1304 write_res (resf, "%02i No such tunnel '%s'\n", 1, tunstr);
1305 break;
1307 // disconnect lac
1308 lac->active = 0;
1309 lac->rtries = 0;
1310 if (lac->t)
1312 lac_disconnect (lac->t->ourtid);
1314 // removes lac from laclist
1315 if (prev_lac == NULL)
1316 laclist = lac->next;
1317 else
1318 prev_lac->next = lac->next;
1319 free(lac);
1320 lac = NULL;
1321 write_res (resf, "%02i OK\n", 0);
1322 break;
1323 default:
1324 l2tp_log (LOG_DEBUG, "Unknown command %c\n", bufp[0]);
1325 write_res (resf, "%02i Unknown command %c\n", 1, bufp[0]);
1328 if (resf)
1330 fclose (resf);
1334 /* Otherwise select goes nuts. Yeah, this just seems wrong */
1335 close (control_fd);
1336 open_controlfd();
1340 void usage(void) {
1341 printf("\nxl2tpd version: %s\n", SERVER_VERSION);
1342 printf("Usage: xl2tpd [-c <config file>] [-s <secret file>] [-p <pid file>]\n"
1343 " [-C <control file>] [-D]\n"
1344 " [-v, --version]\n");
1345 printf("\n");
1346 exit(1);
1349 void init_args(int argc, char *argv[])
1351 int i=0;
1353 gconfig.daemon=1;
1354 memset(gconfig.altauthfile,0,STRLEN);
1355 memset(gconfig.altconfigfile,0,STRLEN);
1356 memset(gconfig.authfile,0,STRLEN);
1357 memset(gconfig.configfile,0,STRLEN);
1358 memset(gconfig.pidfile,0,STRLEN);
1359 memset(gconfig.controlfile,0,STRLEN);
1360 strncpy(gconfig.altauthfile,ALT_DEFAULT_AUTH_FILE,
1361 sizeof(gconfig.altauthfile) - 1);
1362 strncpy(gconfig.altconfigfile,ALT_DEFAULT_CONFIG_FILE,
1363 sizeof(gconfig.altconfigfile) - 1);
1364 strncpy(gconfig.authfile,DEFAULT_AUTH_FILE,
1365 sizeof(gconfig.authfile) - 1);
1366 strncpy(gconfig.configfile,DEFAULT_CONFIG_FILE,
1367 sizeof(gconfig.configfile) - 1);
1368 strncpy(gconfig.pidfile,DEFAULT_PID_FILE,
1369 sizeof(gconfig.pidfile) - 1);
1370 strncpy(gconfig.controlfile,CONTROL_PIPE,
1371 sizeof(gconfig.controlfile) - 1);
1372 gconfig.ipsecsaref = 0;
1374 for (i = 1; i < argc; i++) {
1375 if ((! strncmp(argv[i],"--version",9))
1376 || (! strncmp(argv[i],"-v",2))) {
1377 printf("\nxl2tpd version: %s\n",SERVER_VERSION);
1378 exit(1);
1381 if(! strncmp(argv[i],"-c",2)) {
1382 if(++i == argc)
1383 usage();
1384 else
1385 strncpy(gconfig.configfile,argv[i],
1386 sizeof(gconfig.configfile) - 1);
1388 else if (! strncmp(argv[i],"-D",2)) {
1389 gconfig.daemon=0;
1391 else if (! strncmp(argv[i],"-s",2)) {
1392 if(++i == argc)
1393 usage();
1394 else
1395 strncpy(gconfig.authfile,argv[i],
1396 sizeof(gconfig.authfile) - 1);
1398 else if (! strncmp(argv[i],"-p",2)) {
1399 if(++i == argc)
1400 usage();
1401 else
1402 strncpy(gconfig.pidfile,argv[i],
1403 sizeof(gconfig.pidfile) - 1);
1405 else if (! strncmp(argv[i],"-C",2)) {
1406 if(++i == argc)
1407 usage();
1408 else
1409 strncpy(gconfig.controlfile,argv[i],
1410 sizeof(gconfig.controlfile) - 1);
1412 else {
1413 usage();
1419 void daemonize() {
1420 int pid=0;
1421 int i;
1423 #ifndef CONFIG_SNAPGEAR
1424 if((pid = fork()) < 0) {
1425 l2tp_log(LOG_INFO, "%s: Unable to fork ()\n",__FUNCTION__);
1426 close(server_socket);
1427 exit(1);
1429 else if (pid)
1430 exit(0);
1432 close(0);
1433 i = open("/dev/null", O_RDWR);
1434 if (i != 0) {
1435 l2tp_log(LOG_INFO, "Redirect of stdin to /dev/null failed\n");
1436 } else {
1437 if (dup2(0, 1) == -1)
1438 l2tp_log(LOG_INFO, "Redirect of stdout to /dev/null failed\n");
1439 if (dup2(0, 2) == -1)
1440 l2tp_log(LOG_INFO, "Redirect of stderr to /dev/null failed\n");
1442 #endif
1445 static void consider_pidfile() {
1446 int pid=0;
1447 int i,l;
1448 char buf[STRLEN];
1450 /* Read previous pid file. */
1451 i = open(gconfig.pidfile,O_RDONLY);
1452 if (i < 0) {
1453 /* l2tp_log(LOG_DEBUG, "%s: Unable to read pid file [%s]\n",
1454 __FUNCTION__, gconfig.pidfile);
1456 } else
1458 l=read(i,buf,sizeof(buf)-1);
1459 close (i);
1460 if (l >= 0)
1462 buf[l] = '\0';
1463 pid = atoi(buf);
1466 /* If the previous server process is still running,
1467 complain and exit immediately. */
1468 if (pid && pid != getpid () && kill (pid, 0) == 0)
1470 l2tp_log(LOG_INFO,
1471 "%s: There's already a xl2tpd server running.\n",
1472 __FUNCTION__);
1473 close(server_socket);
1474 exit(1);
1478 pid = setsid();
1480 unlink(gconfig.pidfile);
1481 if ((i = open (gconfig.pidfile, O_WRONLY | O_CREAT, 0640)) >= 0) {
1482 snprintf (buf, sizeof(buf), "%d\n", (int)getpid());
1483 if (-1 == write (i, buf, strlen(buf)))
1485 l2tp_log (LOG_CRIT, "%s: Unable to write to %s.\n",
1486 __FUNCTION__, gconfig.pidfile);
1487 close (i);
1488 exit(1);
1490 close (i);
1494 static void open_controlfd()
1496 control_fd = open (gconfig.controlfile, O_RDONLY | O_NONBLOCK, 0600);
1497 if (control_fd < 0)
1499 l2tp_log (LOG_CRIT, "%s: Unable to open %s for reading.\n",
1500 __FUNCTION__, gconfig.controlfile);
1501 exit (1);
1504 /* turn off O_NONBLOCK */
1505 if(fcntl(control_fd, F_SETFL, O_RDONLY)==-1) {
1506 l2tp_log(LOG_CRIT, "Can not turn off nonblocking mode for controlfd: %s\n",
1507 strerror(errno));
1508 exit(1);
1512 void init (int argc,char *argv[])
1514 struct lac *lac;
1515 struct in_addr listenaddr;
1516 struct utsname uts;
1518 init_args (argc,argv);
1519 srand( time(NULL) );
1520 rand_source = 0;
1521 init_addr ();
1522 if (init_config ())
1524 l2tp_log (LOG_CRIT, "%s: Unable to load config file\n", __FUNCTION__);
1525 exit (1);
1527 if (uname (&uts)<0)
1529 l2tp_log (LOG_CRIT, "%s : Unable to determine host system\n",
1530 __FUNCTION__);
1531 exit (1);
1533 init_tunnel_list (&tunnels);
1534 if (init_network ())
1535 exit (1);
1537 if (gconfig.daemon)
1538 daemonize ();
1540 consider_pidfile();
1542 signal (SIGTERM, &sigterm_handler);
1543 signal (SIGINT, &sigint_handler);
1544 signal (SIGCHLD, &sigchld_handler);
1545 signal (SIGUSR1, &sigusr1_handler);
1546 signal (SIGHUP, &sighup_handler);
1547 init_scheduler ();
1549 unlink(gconfig.controlfile);
1550 mkfifo (gconfig.controlfile, 0600);
1552 open_controlfd();
1554 l2tp_log (LOG_INFO, "xl2tpd version " SERVER_VERSION " started on %s PID:%d\n",
1555 hostname, getpid ());
1556 l2tp_log (LOG_INFO,
1557 "Written by Mark Spencer, Copyright (C) 1998, Adtran, Inc.\n");
1558 l2tp_log (LOG_INFO, "Forked by Scott Balmos and David Stipp, (C) 2001\n");
1559 l2tp_log (LOG_INFO, "Inherited by Jeff McAdams, (C) 2002\n");
1560 l2tp_log (LOG_INFO, "Forked again by Xelerance (www.xelerance.com) (C) 2006\n");
1561 listenaddr.s_addr = gconfig.listenaddr;
1562 l2tp_log (LOG_INFO, "Listening on IP address %s, port %d\n",
1563 inet_ntoa(listenaddr), gconfig.port);
1564 lac = laclist;
1565 while (lac)
1567 if (lac->autodial)
1569 #ifdef DEBUG_MAGIC
1570 l2tp_log (LOG_DEBUG, "%s: Autodialing '%s'\n", __FUNCTION__,
1571 lac->entname[0] ? lac->entname : "(unnamed)");
1572 #endif
1573 lac->active = -1;
1574 switch_io = 1; /* If we're a LAC, autodials will be ICRQ's */
1575 magic_lac_dial (lac);
1577 lac = lac->next;
1581 int main (int argc, char *argv[])
1583 init(argc,argv);
1584 dial_no_tmp = calloc (128, sizeof (char));
1585 network_thread ();
1586 return 0;
1589 /* Route manipulation */
1591 static int
1592 route_ctrl(int ctrl, struct rtentry *rt)
1594 int s;
1596 /* Open a raw socket to the kernel */
1597 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0 || ioctl(s, ctrl, rt) < 0)
1598 l2tp_log (LOG_ERR, "route_ctrl: %s", strerror(errno));
1599 else errno = 0;
1601 close(s);
1602 return errno;
1606 route_del(struct rtentry *rt)
1608 if (rt->rt_dev) {
1609 route_ctrl(SIOCDELRT, rt);
1610 free(rt->rt_dev);
1611 rt->rt_dev = NULL;
1613 return 0;
1617 route_add(const struct in_addr inetaddr, struct rtentry *rt)
1619 char buf[256], dev[64];
1620 int metric, flags;
1621 u_int32_t dest, mask;
1623 FILE *f = fopen("/proc/net/route", "r");
1624 if (f == NULL) {
1625 l2tp_log (LOG_ERR, "/proc/net/route: %s", strerror(errno));
1626 return -1;
1629 while (fgets(buf, sizeof(buf), f)) {
1630 if (sscanf(buf, "%63s %x %x %X %*s %*s %d %x", dev, &dest,
1631 &sin_addr(&rt->rt_gateway).s_addr, &flags, &metric, &mask) != 6)
1632 continue;
1633 if ((flags & RTF_UP) == (RTF_UP) && (inetaddr.s_addr & mask) == dest &&
1634 (dest || strncmp(dev, "ppp", 3)) /* avoid default via pppX to avoid on-demand loops*/) {
1635 rt->rt_metric = metric + 1;
1636 rt->rt_gateway.sa_family = AF_INET;
1637 break;
1641 fclose(f);
1643 /* check for no route */
1644 if (rt->rt_gateway.sa_family != AF_INET) {
1645 /* l2tp_log (LOG_ERR, "route_add: no route to host"); */
1646 return -1;
1649 /* check for existing route to this host,
1650 add if missing based on the existing routes */
1651 if (flags & RTF_HOST) {
1652 /* l2tp_log (LOG_ERR, "route_add: not adding existing route"); */
1653 return -1;
1656 sin_addr(&rt->rt_dst) = inetaddr;
1657 rt->rt_dst.sa_family = AF_INET;
1659 sin_addr(&rt->rt_genmask).s_addr = INADDR_BROADCAST;
1660 rt->rt_genmask.sa_family = AF_INET;
1662 rt->rt_flags = RTF_UP | RTF_HOST;
1663 if (flags & RTF_GATEWAY)
1664 rt->rt_flags |= RTF_GATEWAY;
1666 rt->rt_metric++;
1667 rt->rt_dev = strdup(dev);
1669 if (!rt->rt_dev) {
1670 l2tp_log (LOG_ERR, "route_add: no memory");
1671 return -1;
1674 if (!route_ctrl(SIOCADDRT, rt))
1675 return 0;
1677 free(rt->rt_dev);
1678 rt->rt_dev = NULL;
1680 return -1;