minidlna support now Samsung TV C550/C650 (thx amir909)
[tomato.git] / release / src / router / xl2tpd / xl2tpd.c
blob398673fe7c125a80b1454b13969d25aef266f99d
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
22 #include <stdlib.h>
23 #include <sys/types.h>
24 #include <sys/utsname.h>
25 #include <sys/stat.h>
26 #include <sys/wait.h>
27 #include <stdio.h>
28 #include <errno.h>
29 #include <unistd.h>
30 #include <time.h>
31 #if (__GLIBC__ < 2)
32 # if defined(FREEBSD) || defined(OPENBSD)
33 # include <sys/signal.h>
34 # elif defined(LINUX)
35 # include <bsd/signal.h>
36 # elif defined(SOLARIS)
37 # include <signal.h>
38 # endif
39 #else
40 # include <signal.h>
41 #endif
42 #ifndef LINUX
43 # include <sys/socket.h>
44 #endif
45 #include <netdb.h>
46 #include <string.h>
47 #include <strings.h>
48 #include <fcntl.h>
49 #include <netinet/in.h>
50 #include <arpa/inet.h>
51 #include <net/route.h>
52 #include <features.h>
53 #include <resolv.h>
54 #include <sys/ioctl.h>
55 #include "l2tp.h"
57 struct tunnel_list tunnels;
58 int rand_source;
59 int ppd = 1; /* Packet processing delay */
60 int control_fd; /* descriptor of control area */
61 char *args;
63 char *dial_no_tmp; /* jz: Dialnumber for Outgoing Call */
64 int switch_io = 0; /* jz: Switch for Incoming or Outgoing Call */
66 static void open_controlfd(void);
68 volatile sig_atomic_t sigterm_received;
69 volatile sig_atomic_t sigint_received;
70 volatile sig_atomic_t sigchld_received;
71 volatile sig_atomic_t sigusr1_received;;
72 volatile sig_atomic_t sighup_received;
74 void init_tunnel_list (struct tunnel_list *t)
76 t->head = NULL;
77 t->count = 0;
78 t->calls = 0;
81 /* Now sends to syslog instead - MvO */
82 void show_status (void)
84 struct schedule_entry *se;
85 struct tunnel *t;
86 struct call *c;
87 struct lns *tlns;
88 struct lac *tlac;
89 struct host *h;
90 unsigned long cnt = 0;
92 int s = 0;
93 l2tp_log (LOG_WARNING, "====== xl2tpd statistics ========\n");
94 l2tp_log (LOG_WARNING, " Scheduler entries:\n");
95 se = events;
96 while (se)
98 s++;
99 t = (struct tunnel *) se->data;
100 tlac = (struct lac *) se->data;
101 c = (struct call *) se->data;
102 if (se->func == &hello)
104 l2tp_log (LOG_WARNING, "%d: HELLO to %d\n", s, t->tid);
106 else if (se->func == &magic_lac_dial)
108 l2tp_log (LOG_WARNING, "%d: Magic dial on %s\n", s, tlac->entname);
110 else if (se->func == &send_zlb)
112 l2tp_log (LOG_WARNING, "%d: Send payload ZLB on call %d:%d\n", s,
113 c->container->tid, c->cid);
115 else if (se->func == &dethrottle)
117 l2tp_log (LOG_WARNING, "%d: Dethrottle call %d:%d\n", s, c->container->tid,
118 c->cid);
120 else
121 l2tp_log (LOG_WARNING, "%d: Unknown event\n", s);
122 se = se->next;
124 l2tp_log (LOG_WARNING, "Total Events scheduled: %d\n", s);
125 l2tp_log (LOG_WARNING, "Number of tunnels open: %d\n", tunnels.count);
126 t = tunnels.head;
127 while (t)
129 l2tp_log (LOG_WARNING, "Tunnel %s, ID = %d (local), %d (remote) to %s:%d,"
130 " control_seq_num = %d, control_rec_seq_num = %d,"
131 " cLr = %d, call count = %d ref=%u/refhim=%u",
132 (t->lac ? t->lac->entname : (t->lns ? t->lns->entname : "")),
133 t->ourtid, t->tid, IPADDY (t->peer.sin_addr),
134 ntohs (t->peer.sin_port), t->control_seq_num,
135 t->control_rec_seq_num, t->cLr, t->count,
136 t->refme, t->refhim);
137 c = t->call_head;
138 while (c)
140 cnt++;
141 l2tp_log (LOG_WARNING,
142 "Call %s # %lu, ID = %d (local), %d (remote), serno = %u,"
143 " data_seq_num = %d, data_rec_seq_num = %d,"
144 " pLr = %d, tx = %u bytes (%u), rx= %u bytes (%u)",
145 (c->lac ? c->lac->
146 entname : (c->lns ? c->lns->entname : "")),
147 cnt, c->ourcid,
148 c->cid, c->serno, c->data_seq_num, c->data_rec_seq_num,
149 c->pLr, c->tx_bytes, c->tx_pkts, c->rx_bytes, c->rx_pkts);
150 c = c->next;
152 t = t->next;
154 l2tp_log (LOG_WARNING, "==========Config File===========\n");
155 tlns = lnslist;
156 while (tlns)
158 l2tp_log (LOG_WARNING, "LNS entry %s\n",
159 tlns->entname[0] ? tlns->entname : "(unnamed)");
160 tlns = tlns->next;
162 tlac = laclist;
163 while (tlac)
165 l2tp_log (LOG_WARNING, "LAC entry %s, LNS is/are:",
166 tlac->entname[0] ? tlac->entname : "(unnamed)");
167 h = tlac->lns;
168 if (h)
170 while (h)
172 l2tp_log (LOG_WARNING, " %s", h->hostname);
173 h = h->next;
176 else
177 l2tp_log (LOG_WARNING, " [none]");
178 tlac = tlac->next;
180 l2tp_log (LOG_WARNING, "================================\n");
183 void null_handler(int sig)
185 /* FIXME
186 * A sighup is received when a call is terminated, unknown origine ..
187 * I catch it and ll looks good, but ..
191 void status_handler (int sig)
193 show_status ();
196 void child_handler (int signal)
199 * Oops, somebody we launched was killed.
200 * It's time to reap them and close that call.
201 * But first, we have to find out what PID died.
202 * unfortunately, pppd will
204 struct tunnel *t;
205 struct call *c;
206 pid_t pid;
207 int status;
208 /* Keep looping until all are cleared */
209 for(;;)
211 pid = waitpid (-1, &status, WNOHANG);
212 if (pid < 1)
215 * Oh well, nobody there. Maybe we reaped it
216 * somewhere else already
218 return;
220 /* find the call that "owned" the pppd which just died */
221 t = tunnels.head;
222 while (t)
224 c = t->call_head;
225 t = t->next;
226 while (c)
228 if (c->pppd == pid)
230 if ( WIFEXITED( status ) )
232 l2tp_log (LOG_DEBUG, "%s : pppd exited for call %d with code %d\n", __FUNCTION__,
233 c->cid, WEXITSTATUS( status ) );
235 else if( WIFSIGNALED( status ) )
237 l2tp_log (LOG_DEBUG, "%s : pppd terminated for call %d by signal %d\n", __FUNCTION__,
238 c->cid, WTERMSIG( status ) );
240 else
242 l2tp_log (LOG_DEBUG, "%s : pppd exited for call %d for unknown reason\n", __FUNCTION__,
243 c->cid );
245 c->needclose = -1;
247 * OK...pppd died, we can go ahead and close the pty for
248 * it
250 #ifdef USE_KERNEL
251 if (!kernel_support)
252 #endif
253 close (c->fd);
254 c->fd = -1;
256 * terminate tunnel and call loops, returning to the
257 * for(;;) loop (and possibly get the next pid)
259 t = NULL;
260 break;
262 c = c->next;
268 void death_handler (int signal)
271 * If we get here, somebody terminated us with a kill or a control-c.
272 * we call call_close on each tunnel twice to get a StopCCN out
273 * for each one (we can't pause to make sure it's received.
274 * Then we close the connections
276 struct tunnel *st, *st2;
277 int sec;
278 l2tp_log (LOG_CRIT, "%s: Fatal signal %d received\n", __FUNCTION__, signal);
279 if (signal != SIGTERM) {
280 st = tunnels.head;
281 while (st)
283 st2 = st->next;
284 strcpy (st->self->errormsg, "Server closing");
285 sec = st->self->closing;
286 if (st->lac)
287 st->lac->redial = 0;
288 call_close (st->self);
289 if (!sec)
291 st->self->closing = -1;
292 call_close (st->self);
294 st = st2;
298 /* erase pid and control files */
299 unlink (gconfig.pidfile);
300 unlink (gconfig.controlfile);
302 exit (1);
305 void sigterm_handler(int sig)
307 sigterm_received = 1;
310 void sigint_handler(int sig)
312 sigint_received = 1;
315 void sigchld_handler(int sig)
317 sigchld_received = 1;
320 void sigusr1_handler(int sig)
322 sigusr1_received = 1;
325 void sighup_handler(int sig)
327 sighup_received = 1;
330 void process_signal(void)
332 if (sigterm_received) { sigterm_received = 0; death_handler(SIGTERM); }
333 if (sigint_received) { sigint_received = 0; death_handler(SIGINT); }
334 if (sigchld_received) { sigchld_received = 0; child_handler(SIGCHLD); }
335 if (sigusr1_received) { sigusr1_received = 0; status_handler(SIGUSR1); }
336 if (sighup_received) { sighup_received = 0; null_handler(SIGHUP); }
339 int start_pppd (struct call *c, struct ppp_opts *opts)
341 /* char a, b; */
342 char tty[512];
343 char *stropt[80];
344 struct ppp_opts *p;
345 #ifdef USE_KERNEL
346 struct sockaddr_pppol2tp sax;
347 int flags;
348 #endif
349 int pos = 1;
350 int fd2;
351 #ifdef DEBUG_PPPD
352 int x;
353 #endif
354 struct termios ptyconf;
355 struct call *sc;
356 struct tunnel *st;
358 p = opts;
359 stropt[0] = strdup (PPPD);
360 while (p)
362 stropt[pos] = (char *) malloc (strlen (p->option) + 1);
363 strncpy (stropt[pos], p->option, strlen (p->option) + 1);
364 pos++;
365 p = p->next;
367 stropt[pos] = NULL;
368 if (c->pppd > 0)
370 l2tp_log(LOG_WARNING, "%s: PPP already started on call!\n", __FUNCTION__);
371 return -EINVAL;
373 if (c->fd > -1)
375 l2tp_log (LOG_WARNING, "%s: file descriptor already assigned!\n",
376 __FUNCTION__);
377 return -EINVAL;
380 #ifdef USE_KERNEL
381 if (kernel_support)
383 fd2 = socket(AF_PPPOX, SOCK_DGRAM, PX_PROTO_OL2TP);
384 if (fd2 < 0) {
385 l2tp_log (LOG_WARNING, "%s: Unable to allocate PPPoL2TP socket.\n",
386 __FUNCTION__);
387 return -EINVAL;
389 flags = fcntl(fd2, F_GETFL);
390 if (flags == -1 || fcntl(fd2, F_SETFL, flags | O_NONBLOCK) == -1) {
391 l2tp_log (LOG_WARNING, "%s: Unable to set PPPoL2TP socket nonblock.\n",
392 __FUNCTION__);
393 return -EINVAL;
395 sax.sa_family = AF_PPPOX;
396 sax.sa_protocol = PX_PROTO_OL2TP;
397 sax.pppol2tp.pid = 0;
398 sax.pppol2tp.fd = server_socket;
399 sax.pppol2tp.addr.sin_addr.s_addr = c->container->peer.sin_addr.s_addr;
400 sax.pppol2tp.addr.sin_port = c->container->peer.sin_port;
401 sax.pppol2tp.addr.sin_family = AF_INET;
402 sax.pppol2tp.s_tunnel = c->container->ourtid;
403 sax.pppol2tp.s_session = c->ourcid;
404 sax.pppol2tp.d_tunnel = c->container->tid;
405 sax.pppol2tp.d_session = c->cid;
406 if (connect(fd2, (struct sockaddr *)&sax, sizeof(sax)) < 0) {
407 l2tp_log (LOG_WARNING, "%s: Unable to connect PPPoL2TP socket.\n",
408 __FUNCTION__);
409 return -EINVAL;
411 stropt[pos++] = strdup ("plugin");
412 stropt[pos++] = strdup ("pppol2tp.so");
413 stropt[pos++] = strdup ("pppol2tp");
414 stropt[pos] = (char *) malloc (10);
415 snprintf (stropt[pos], 10, "%d", fd2);
416 pos++;
417 stropt[pos] = NULL;
419 else
420 #endif
422 if ((c->fd = getPtyMaster (tty, sizeof(tty))) < 0)
424 l2tp_log (LOG_WARNING, "%s: unable to allocate pty, abandoning!\n",
425 __FUNCTION__);
426 return -EINVAL;
429 /* set fd opened above to not echo so we don't see read our own packets
430 back of the file descriptor that we just wrote them to */
431 tcgetattr (c->fd, &ptyconf);
432 *(c->oldptyconf) = ptyconf;
433 ptyconf.c_cflag &= ~(ICANON | ECHO);
434 ptyconf.c_lflag &= ~ECHO;
435 tcsetattr (c->fd, TCSANOW, &ptyconf);
436 if(fcntl(c->fd, F_SETFL, O_NONBLOCK)!=0) {
437 l2tp_log(LOG_WARNING, "failed to set nonblock: %s\n", strerror(errno));
438 return -EINVAL;
441 fd2 = open (tty, O_RDWR);
442 if (fd2 < 0) {
443 l2tp_log (LOG_WARNING, "unable to open tty %s, cannot start pppd", tty);
444 return -EINVAL;
446 stropt[pos++] = strdup(tty);
447 stropt[pos] = NULL;
450 #ifdef DEBUG_PPPD
451 l2tp_log (LOG_DEBUG, "%s: I'm running: \n", __FUNCTION__);
452 for (x = 0; stropt[x]; x++)
454 l2tp_log (LOG_DEBUG, "\"%s\" \n", stropt[x]);
456 #endif
457 #ifdef __uClinux__
458 c->pppd = vfork ();
459 #else
460 c->pppd = fork ();
461 #endif
463 if (c->pppd < 0)
465 /* parent */
466 l2tp_log(LOG_WARNING,"%s: unable to fork(), abandoning!\n", __FUNCTION__);
467 return -EINVAL;
469 else if (!c->pppd)
471 /* child */
473 close (0); /* redundant; the dup2() below would do that, too */
474 close (1); /* ditto */
475 /* close (2); No, we want to keep the connection to /dev/null. */
476 #ifdef USE_KERNEL
477 if (!kernel_support)
478 #endif
481 /* connect the pty to stdin and stdout */
482 dup2 (fd2, 0);
483 dup2 (fd2, 1);
484 close(fd2);
486 /* close all the calls pty fds */
487 st = tunnels.head;
488 while (st)
490 sc = st->call_head;
491 while (sc)
493 close (sc->fd);
494 sc = sc->next;
496 st = st->next;
500 /* close the UDP socket fd */
501 close (server_socket);
503 /* close the control pipe fd */
504 close (control_fd);
506 if( c->dialing[0] )
508 setenv( "CALLER_ID", c->dialing, 1 );
510 execv (PPPD, stropt);
511 l2tp_log (LOG_WARNING, "%s: Exec of %s failed!\n", __FUNCTION__, PPPD);
512 _exit (1);
514 close (fd2);
515 pos = 0;
516 while (stropt[pos])
518 free (stropt[pos]);
519 pos++;
521 return 0;
524 void destroy_tunnel (struct tunnel *t)
527 * Immediately destroy a tunnel (and all its calls)
528 * and free its resources. This may be called
529 * by the tunnel itself,so it needs to be
530 * "suicide safe"
533 struct call *c, *me;
534 struct tunnel *p;
535 struct timeval tv;
536 if (!t)
537 return;
540 * Save ourselves until the very
541 * end, since we might be calling this ourselves.
542 * We must divorce ourself from the tunnel
543 * structure, however, to avoid recursion
544 * because of the logic of the destroy_call
546 me = t->self;
549 * Destroy all the member calls
551 c = t->call_head;
552 while (c)
554 destroy_call (c);
555 c = c->next;
558 * Remove ourselves from the list of tunnels
561 if (tunnels.head == t)
563 tunnels.head = t->next;
564 tunnels.count--;
566 else
568 p = tunnels.head;
569 if (p)
571 while (p->next && (p->next != t))
572 p = p->next;
573 if (p->next)
575 p->next = t->next;
576 tunnels.count--;
578 else
580 l2tp_log (LOG_WARNING,
581 "%s: unable to locate tunnel in tunnel list\n",
582 __FUNCTION__);
585 else
587 l2tp_log (LOG_WARNING, "%s: tunnel list is empty!\n", __FUNCTION__);
590 if (t->lac)
592 t->lac->t = NULL;
593 if (t->lac->redial && (t->lac->rtimeout > 0) && !t->lac->rsched &&
594 t->lac->active)
596 l2tp_log (LOG_INFO, "Will redial in %d seconds\n",
597 t->lac->rtimeout);
598 tv.tv_sec = t->lac->rtimeout;
599 tv.tv_usec = 0;
600 t->lac->rsched = schedule (tv, magic_lac_dial, t->lac);
603 /* XXX L2TP/IPSec: remove relevant SAs here? NTB 20011010
604 * XXX But what if another tunnel is using same SA?
606 if (t->lns)
607 t->lns->t = NULL;
608 if (t->chal_us.challenge)
609 free (t->chal_us.challenge);
610 if (t->chal_them.challenge)
611 free (t->chal_them.challenge);
612 /* we need no free(t->chal_us.vector) here because we malloc() and free()
613 the memory pointed to by t->chal_us.vector at some other place */
614 if (t->chal_them.vector)
615 free (t->chal_them.vector);
616 route_del(&t->rt);
617 free (t);
618 free (me);
621 struct tunnel *l2tp_call (char *host, int port, struct lac *lac,
622 struct lns *lns)
625 * Establish a tunnel from us to host
626 * on port port
628 struct call *tmp = NULL;
629 struct hostent *hp;
630 unsigned int addr;
632 #if !defined(__UCLIBC__) \
633 || (__UCLIBC_MAJOR__ == 0 \
634 && (__UCLIBC_MINOR__ < 9 || (__UCLIBC_MINOR__ == 9 && __UCLIBC_SUBLEVEL__ < 31)))
635 /* force ns refresh from resolv.conf with uClibc pre-0.9.31 */
636 res_init();
637 #endif
639 port = htons (port);
640 hp = gethostbyname (host);
641 if (!hp)
643 l2tp_log (LOG_WARNING, "Host name lookup failed for %s.\n",
644 host);
645 return NULL;
647 bcopy (hp->h_addr, &addr, hp->h_length);
648 /* Force creation of a new tunnel
649 and set it's tid to 0 to cause
650 negotiation to occur */
652 * to do IPsec properly here, we need to set a socket policy,
653 * and/or communicate with pluto.
655 tmp = get_call (0, 0, addr, port, IPSEC_SAREF_NULL, IPSEC_SAREF_NULL);
656 if (!tmp)
658 l2tp_log (LOG_WARNING, "%s: Unable to create tunnel to %s.\n", __FUNCTION__,
659 host);
660 return NULL;
662 tmp->container->tid = 0;
663 tmp->container->lac = lac;
664 tmp->container->lns = lns;
665 tmp->lac = lac;
666 tmp->lns = lns;
667 if (lac)
668 lac->t = tmp->container;
669 if (lns)
670 lns->t = tmp->container;
672 * Since our state is 0, we will establish a tunnel now
674 l2tp_log (LOG_NOTICE, "Connecting to host %s, port %d\n", host,
675 ntohs (port));
676 control_finish (tmp->container, tmp);
677 return tmp->container;
680 void magic_lac_tunnel (void *data)
682 struct lac *lac;
683 lac = (struct lac *) data;
684 if (!lac)
686 l2tp_log (LOG_WARNING, "%s: magic_lac_tunnel: called on NULL lac!\n",
687 __FUNCTION__);
688 return;
690 if (lac->lns)
692 /* FIXME: I should try different LNS's if I get failures */
693 l2tp_call (lac->lns->hostname, lac->lns->port, lac, NULL);
694 return;
696 else if (deflac && deflac->lns)
698 l2tp_call (deflac->lns->hostname, deflac->lns->port, lac, NULL);
699 return;
701 else
703 l2tp_log (LOG_WARNING, "%s: Unable to find hostname to dial for '%s'\n",
704 __FUNCTION__, lac->entname);
705 return;
709 struct call *lac_call (int tid, struct lac *lac, struct lns *lns)
711 struct tunnel *t = tunnels.head;
712 struct call *tmp;
713 while (t)
715 if (t->ourtid == tid)
717 tmp = new_call (t);
718 if (!tmp)
720 l2tp_log (LOG_WARNING, "%s: unable to create new call\n",
721 __FUNCTION__);
722 return NULL;
724 tmp->next = t->call_head;
725 t->call_head = tmp;
726 t->count++;
727 tmp->cid = 0;
728 tmp->lac = lac;
729 tmp->lns = lns;
730 if (lac)
731 lac->c = tmp;
732 l2tp_log (LOG_NOTICE, "Calling on tunnel %d\n", tid);
733 strcpy (tmp->dial_no, dial_no_tmp); /* jz: copy dialnumber to tmp->dial_no */
734 control_finish (t, tmp);
735 return tmp;
737 t = t->next;
739 l2tp_log (LOG_DEBUG, "%s: No such tunnel %d to generate call.\n", __FUNCTION__,
740 tid);
741 return NULL;
744 void magic_lac_dial (void *data)
746 struct lac *lac;
747 lac = (struct lac *) data;
748 if (!lac->active)
750 l2tp_log (LOG_DEBUG, "%s: LAC %s not active", __FUNCTION__, lac->entname);
751 return;
753 lac->rsched = NULL;
754 lac->rtries++;
755 if (lac->rmax && (lac->rtries > lac->rmax))
757 l2tp_log (LOG_INFO, "%s: maximum retries exceeded.\n", __FUNCTION__);
758 return;
760 if (!lac)
762 l2tp_log (LOG_WARNING, "%s : called on NULL lac!\n", __FUNCTION__);
763 return;
765 if (!lac->t)
767 #ifdef DEGUG_MAGIC
768 l2tp_log (LOG_DEBUG, "%s : tunnel not up! Connecting!\n", __FUNCTION__);
769 #endif
770 magic_lac_tunnel (lac);
771 return;
773 lac_call (lac->t->ourtid, lac, NULL);
776 void lac_hangup (int cid)
778 struct tunnel *t = tunnels.head;
779 struct call *tmp;
780 while (t)
782 tmp = t->call_head;
783 while (tmp)
785 if (tmp->ourcid == cid)
787 l2tp_log (LOG_INFO,
788 "%s :Hanging up call %d, Local: %d, Remote: %d\n",
789 __FUNCTION__, tmp->serno, tmp->ourcid, tmp->cid);
790 strcpy (tmp->errormsg, "Goodbye!");
791 /* tmp->needclose = -1; */
792 kill (tmp->pppd, SIGTERM);
793 return;
795 tmp = tmp->next;
797 t = t->next;
799 l2tp_log (LOG_DEBUG, "%s : No such call %d to hang up.\n", __FUNCTION__, cid);
800 return;
803 void lac_disconnect (int tid)
805 struct tunnel *t = tunnels.head;
806 while (t)
808 if (t->ourtid == tid)
810 l2tp_log (LOG_INFO,
811 "Disconnecting from %s, Local: %d, Remote: %d\n",
812 IPADDY (t->peer.sin_addr), t->ourtid, t->tid);
813 t->self->needclose = -1;
814 strcpy (t->self->errormsg, "Goodbye!");
815 call_close (t->self);
816 return;
818 t = t->next;
820 l2tp_log (LOG_DEBUG, "No such tunnel %d to hang up.\n", tid);
821 return;
824 struct tunnel *new_tunnel ()
826 struct tunnel *tmp = malloc (sizeof (struct tunnel));
827 unsigned char entropy_buf[2] = "\0";
828 if (!tmp)
829 return NULL;
830 tmp->control_seq_num = 0;
831 tmp->control_rec_seq_num = 0;
832 tmp->cLr = 0;
833 tmp->call_head = NULL;
834 tmp->next = NULL;
835 tmp->debug = -1;
836 tmp->tid = -1;
837 tmp->hello = NULL;
838 #ifndef TESTING
839 /* while(get_call((tmp->ourtid = rand() & 0xFFFF),0,0,0)); */
840 /* tmp->ourtid = rand () & 0xFFFF; */
841 /* get_entropy((char *)&tmp->ourtid, 2); */
842 get_entropy(entropy_buf, 2);
844 unsigned short *temp;
845 temp = (unsigned short *)entropy_buf;
846 tmp->ourtid = *temp & 0xFFFF;
847 #ifdef DEBUG_ENTROPY
848 l2tp_log(LOG_DEBUG, "ourtid = %u, entropy_buf = %hx\n", tmp->ourtid, *temp);
849 #endif
852 #else
853 tmp->ourtid = 0x6227;
854 #endif
855 tmp->nego = 0;
856 tmp->count = 0;
857 tmp->state = 0; /* Nothing */
858 tmp->peer.sin_family = AF_INET;
859 tmp->peer.sin_port = 0;
860 bzero (&(tmp->peer.sin_addr), sizeof (tmp->peer.sin_addr));
861 #ifdef SANITY
862 tmp->sanity = -1;
863 #endif
864 tmp->qtid = -1;
865 tmp->ourfc = ASYNC_FRAMING | SYNC_FRAMING;
866 tmp->ourbc = 0;
867 tmp->ourtb = (((_u64) rand ()) << 32) | ((_u64) rand ());
868 tmp->fc = -1; /* These really need to be specified by the peer */
869 tmp->bc = -1; /* And we want to know if they forgot */
870 tmp->hostname[0] = 0;
871 tmp->vendor[0] = 0;
872 tmp->secret[0] = 0;
873 if (!(tmp->self = new_call (tmp)))
875 free (tmp);
876 return NULL;
878 tmp->ourrws = DEFAULT_RWS_SIZE;
879 tmp->self->ourfbit = FBIT;
880 tmp->rxspeed = DEFAULT_RX_BPS;
881 tmp->txspeed = DEFAULT_TX_BPS;
882 tmp->lac = NULL;
883 tmp->lns = NULL;
884 tmp->chal_us.state = 0;
885 tmp->chal_us.secret[0] = 0;
886 memset (tmp->chal_us.reply, 0, MD_SIG_SIZE);
887 tmp->chal_us.challenge = NULL;
888 tmp->chal_us.chal_len = 0;
889 tmp->chal_them.state = 0;
890 tmp->chal_them.secret[0] = 0;
891 memset (tmp->chal_them.reply, 0, MD_SIG_SIZE);
892 tmp->chal_them.challenge = NULL;
893 tmp->chal_them.chal_len = 0;
894 tmp->chal_them.vector = (unsigned char *) malloc (VECTOR_SIZE);
895 tmp->chal_us.vector = NULL;
896 tmp->hbit = 0;
897 return tmp;
900 void do_control ()
902 char buf[1024];
903 char *host;
904 char *tunstr;
905 char *callstr;
907 char *authname = NULL;
908 char *password = NULL;
909 char delims[] = " ";
910 char *sub_str; /* jz: use by the strtok function */
911 char *tmp_ptr; /* jz: use by the strtok function */
912 struct lac *lac;
913 int call;
914 int tunl;
915 int cnt = -1;
916 int done = 0;
918 bzero(buf, sizeof(buf));
919 buf[0]='\0';
921 while (!done)
923 cnt = read (control_fd, buf, sizeof (buf));
924 if (cnt <= 0)
926 if(cnt < 0 && errno != EINTR) {
927 perror("controlfd");
929 done=1;
930 break;
933 if (buf[cnt - 1] == '\n')
934 buf[--cnt] = 0;
935 #ifdef DEBUG_CONTROL
936 l2tp_log (LOG_DEBUG, "%s: Got message %s (%d bytes long)\n",
937 __FUNCTION__, buf, cnt);
938 #endif
939 switch (buf[0])
941 case 't':
942 host = strchr (buf, ' ') + 1;
943 #ifdef DEBUG_CONTROL
944 l2tp_log (LOG_DEBUG, "%s: Attempting to tunnel to %s\n",
945 __FUNCTION__, host);
946 #endif
947 l2tp_call (host, UDP_LISTEN_PORT, NULL, NULL);
948 break;
949 case 'c':
950 switch_io = 1; /* jz: Switch for Incoming - Outgoing Calls */
952 tunstr = strtok (&buf[1], delims);
954 /* Are these passed on the command line? */
955 authname = strtok (NULL, delims);
956 password = strtok (NULL, delims);
958 lac = laclist;
959 while (lac && strcasecmp (lac->entname, tunstr)!=0)
961 lac = lac->next;
964 if(lac) {
965 lac->active = -1;
966 lac->rtries = 0;
967 if (authname != NULL)
968 strncpy (lac->authname, authname, STRLEN);
969 if (password != NULL)
970 strncpy (lac->password, password, STRLEN);
971 if (!lac->c)
972 magic_lac_dial (lac);
973 else {
974 l2tp_log (LOG_DEBUG,
975 "Session '%s' already active!\n", lac->entname);
977 break;
980 /* did not find a tunnel by name, look by number */
981 tunl = atoi (tunstr);
982 if (!tunl)
984 l2tp_log (LOG_DEBUG, "No such tunnel '%s'\n", tunstr);
985 break;
987 #ifdef DEBUG_CONTROL
988 l2tp_log (LOG_DEBUG, "%s: Attempting to call on tunnel %d\n",
989 __FUNCTION__, tunl);
990 #endif
991 lac_call (tunl, NULL, NULL);
992 break;
994 case 'o': /* jz: option 'o' for doing a outgoing call */
995 switch_io = 0; /* jz: Switch for incoming - outgoing Calls */
997 sub_str = strchr (buf, ' ') + 1;
998 tunstr = strtok (sub_str, " "); /* jz: using strtok function to get */
999 tmp_ptr = strtok (NULL, " "); /* params out of the pipe */
1000 strcpy (dial_no_tmp, tmp_ptr);
1002 lac = laclist;
1003 while (lac && strcasecmp (lac->entname, tunstr)!=0)
1005 lac = lac->next;
1008 if(lac) {
1009 lac->active = -1;
1010 lac->rtries = 0;
1011 if (!lac->c)
1012 magic_lac_dial (lac);
1013 else
1014 l2tp_log (LOG_DEBUG, "Session '%s' already active!\n",
1015 lac->entname);
1016 break;
1019 /* did not find a tunnel by name, look by number */
1020 tunl = atoi (tunstr);
1021 if (!tunl)
1023 l2tp_log (LOG_DEBUG, "No such tunnel '%s'\n", tunstr);
1024 break;
1026 #ifdef DEBUG_CONTROL
1027 l2tp_log (LOG_DEBUG, "%s: Attempting to call on tunnel %d\n",
1028 __FUNCTION__, tunl);
1029 #endif
1030 lac_call (tunl, NULL, NULL);
1031 break;
1033 case 'h':
1034 callstr = strchr (buf, ' ') + 1;
1035 call = atoi (callstr);
1036 #ifdef DEBUG_CONTROL
1037 l2tp_log (LOG_DEBUG, "%s: Attempting to hangup call %d\n", __FUNCTION__,
1038 call);
1039 #endif
1040 lac_hangup (call);
1041 break;
1043 case 'd':
1044 tunstr = strchr (buf, ' ') + 1;
1045 lac = laclist;
1046 while (lac)
1048 if (!strcasecmp (lac->entname, tunstr))
1050 lac->active = 0;
1051 lac->rtries = 0;
1052 if (lac->t)
1053 lac_disconnect (lac->t->ourtid);
1054 else
1055 l2tp_log (LOG_DEBUG, "Session '%s' not up\n",
1056 lac->entname);
1057 break;
1059 lac = lac->next;
1061 if (lac)
1062 break;
1063 tunl = atoi (tunstr);
1064 if (!tunl)
1066 l2tp_log (LOG_DEBUG, "No such tunnel '%s'\n",
1067 tunstr);
1068 break;
1070 #ifdef DEBUG_CONTROL
1071 l2tp_log (LOG_DEBUG, "%s: Attempting to disconnect tunnel %d\n",
1072 __FUNCTION__, tunl);
1073 #endif
1074 lac_disconnect (tunl);
1075 break;
1076 case 's':
1077 show_status ();
1078 break;
1079 default:
1080 l2tp_log (LOG_DEBUG, "Unknown command %c\n", buf[0]);
1084 /* Otherwise select goes nuts. Yeah, this just seems wrong */
1085 close (control_fd);
1086 open_controlfd();
1090 void usage(void) {
1091 printf("\nxl2tpd version: %s\n",SERVER_VERSION);
1092 printf("Usage: xl2tpd [-c <config file>] [-s <secret file>] [-p <pid file>] \n [-C <control file>] [-D]\n");
1093 printf("\n");
1094 exit(1);
1097 void init_args(int argc, char *argv[])
1099 int i=0;
1101 gconfig.daemon=1;
1102 memset(gconfig.altauthfile,0,STRLEN);
1103 memset(gconfig.altconfigfile,0,STRLEN);
1104 memset(gconfig.authfile,0,STRLEN);
1105 memset(gconfig.configfile,0,STRLEN);
1106 memset(gconfig.pidfile,0,STRLEN);
1107 memset(gconfig.controlfile,0,STRLEN);
1108 strncpy(gconfig.altauthfile,ALT_DEFAULT_AUTH_FILE,
1109 sizeof(gconfig.altauthfile) - 1);
1110 strncpy(gconfig.altconfigfile,ALT_DEFAULT_CONFIG_FILE,
1111 sizeof(gconfig.altconfigfile) - 1);
1112 strncpy(gconfig.authfile,DEFAULT_AUTH_FILE,
1113 sizeof(gconfig.authfile) - 1);
1114 strncpy(gconfig.configfile,DEFAULT_CONFIG_FILE,
1115 sizeof(gconfig.configfile) - 1);
1116 strncpy(gconfig.pidfile,DEFAULT_PID_FILE,
1117 sizeof(gconfig.pidfile) - 1);
1118 strncpy(gconfig.controlfile,CONTROL_PIPE,
1119 sizeof(gconfig.controlfile) - 1);
1120 gconfig.ipsecsaref = 0;
1122 for (i = 1; i < argc; i++) {
1123 if (! strncmp(argv[i],"--version",9)) {
1124 printf("\nxl2tpd version: %s\n",SERVER_VERSION);
1125 exit(1);
1128 if(! strncmp(argv[i],"-c",2)) {
1129 if(++i == argc)
1130 usage();
1131 else
1132 strncpy(gconfig.configfile,argv[i],
1133 sizeof(gconfig.configfile) - 1);
1135 else if (! strncmp(argv[i],"-D",2)) {
1136 gconfig.daemon=0;
1138 else if (! strncmp(argv[i],"-s",2)) {
1139 if(++i == argc)
1140 usage();
1141 else
1142 strncpy(gconfig.authfile,argv[i],
1143 sizeof(gconfig.authfile) - 1);
1145 else if (! strncmp(argv[i],"-p",2)) {
1146 if(++i == argc)
1147 usage();
1148 else
1149 strncpy(gconfig.pidfile,argv[i],
1150 sizeof(gconfig.pidfile) - 1);
1152 else if (! strncmp(argv[i],"-C",2)) {
1153 if(++i == argc)
1154 usage();
1155 else
1156 strncpy(gconfig.controlfile,argv[i],
1157 sizeof(gconfig.controlfile) - 1);
1159 else {
1160 usage();
1166 void daemonize() {
1167 int pid=0;
1168 int i;
1170 #ifndef CONFIG_SNAPGEAR
1171 if((pid = fork()) < 0) {
1172 l2tp_log(LOG_INFO, "%s: Unable to fork ()\n",__FUNCTION__);
1173 close(server_socket);
1174 exit(1);
1176 else if (pid)
1177 exit(0);
1179 close(0);
1180 i = open("/dev/null", O_RDWR);
1181 if (i != 0) {
1182 l2tp_log(LOG_INFO, "Redirect of stdin to /dev/null failed\n");
1183 } else {
1184 if (dup2(0, 1) == -1)
1185 l2tp_log(LOG_INFO, "Redirect of stdout to /dev/null failed\n");
1186 if (dup2(0, 2) == -1)
1187 l2tp_log(LOG_INFO, "Redirect of stderr to /dev/null failed\n");
1189 #endif
1192 void consider_pidfile() {
1193 int pid=0;
1194 int i,l;
1195 char buf[STRLEN];
1197 /* Read previous pid file. */
1198 i = open(gconfig.pidfile,O_RDONLY);
1199 if (i < 0) {
1200 /* l2tp_log(LOG_DEBUG, "%s: Unable to read pid file [%s]\n",
1201 __FUNCTION__, gconfig.pidfile);
1203 } else
1205 l=read(i,buf,sizeof(buf)-1);
1206 close (i);
1207 if (l >= 0)
1209 buf[l] = '\0';
1210 pid = atoi(buf);
1213 /* If the previous server process is still running,
1214 complain and exit immediately. */
1215 if (pid && pid != getpid () && kill (pid, 0) == 0)
1217 l2tp_log(LOG_INFO,
1218 "%s: There's already a xl2tpd server running.\n",
1219 __FUNCTION__);
1220 close(server_socket);
1221 exit(1);
1225 pid = setsid();
1227 unlink(gconfig.pidfile);
1228 if ((i = open (gconfig.pidfile, O_WRONLY | O_CREAT, 0640)) >= 0) {
1229 snprintf (buf, sizeof(buf), "%d\n", (int)getpid());
1230 write (i, buf, strlen(buf));
1231 close (i);
1235 static void open_controlfd()
1237 control_fd = open (gconfig.controlfile, O_RDONLY | O_NONBLOCK, 0600);
1238 if (control_fd < 0)
1240 l2tp_log (LOG_CRIT, "%s: Unable to open %s for reading.\n",
1241 __FUNCTION__, gconfig.controlfile);
1242 exit (1);
1245 /* turn off O_NONBLOCK */
1246 if(fcntl(control_fd, F_SETFL, O_RDONLY)==-1) {
1247 l2tp_log(LOG_CRIT, "Can not turn off nonblocking mode for controlfd: %s\n",
1248 strerror(errno));
1249 exit(1);
1253 void init (int argc,char *argv[])
1255 struct lac *lac;
1256 struct in_addr listenaddr;
1257 struct utsname uts;
1259 init_args (argc,argv);
1260 srand( time(NULL) );
1261 rand_source = 0;
1262 init_addr ();
1263 if (init_config ())
1265 l2tp_log (LOG_CRIT, "%s: Unable to load config file\n", __FUNCTION__);
1266 exit (1);
1268 if (uname (&uts)<0)
1270 l2tp_log (LOG_CRIT, "%s : Unable to determine host system\n",
1271 __FUNCTION__);
1272 exit (1);
1274 init_tunnel_list (&tunnels);
1275 if (init_network ())
1276 exit (1);
1278 if (gconfig.daemon)
1279 daemonize ();
1281 consider_pidfile();
1283 signal (SIGTERM, &sigterm_handler);
1284 signal (SIGINT, &sigint_handler);
1285 signal (SIGCHLD, &sigchld_handler);
1286 signal (SIGUSR1, &sigusr1_handler);
1287 signal (SIGHUP, &sighup_handler);
1288 init_scheduler ();
1290 unlink(gconfig.controlfile);
1291 mkfifo (gconfig.controlfile, 0600);
1293 open_controlfd();
1295 l2tp_log (LOG_INFO, "xl2tpd version " SERVER_VERSION " started on %s PID:%d\n",
1296 hostname, getpid ());
1297 l2tp_log (LOG_INFO,
1298 "Written by Mark Spencer, Copyright (C) 1998, Adtran, Inc.\n");
1299 l2tp_log (LOG_INFO, "Forked by Scott Balmos and David Stipp, (C) 2001\n");
1300 l2tp_log (LOG_INFO, "Inherited by Jeff McAdams, (C) 2002\n");
1301 l2tp_log (LOG_INFO, "Forked again by Xelerance (www.xelerance.com) (C) 2006\n");
1302 listenaddr.s_addr = gconfig.listenaddr;
1303 l2tp_log (LOG_INFO, "Listening on IP address %s, port %d\n",
1304 inet_ntoa(listenaddr), gconfig.port);
1305 lac = laclist;
1306 while (lac)
1308 if (lac->autodial)
1310 #ifdef DEBUG_MAGIC
1311 l2tp_log (LOG_DEBUG, "%s: Autodialing '%s'\n", __FUNCTION__,
1312 lac->entname[0] ? lac->entname : "(unnamed)");
1313 #endif
1314 lac->active = -1;
1315 switch_io = 1; /* If we're a LAC, autodials will be ICRQ's */
1316 magic_lac_dial (lac);
1318 lac = lac->next;
1322 int main (int argc, char *argv[])
1324 init(argc,argv);
1325 dial_no_tmp = calloc (128, sizeof (char));
1326 network_thread ();
1327 return 0;
1330 /* Route manipulation */
1332 static int
1333 route_ctrl(int ctrl, struct rtentry *rt)
1335 int s;
1337 /* Open a raw socket to the kernel */
1338 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0 || ioctl(s, ctrl, rt) < 0)
1339 l2tp_log (LOG_ERR, "route_ctrl: %s", strerror(errno));
1340 else errno = 0;
1342 close(s);
1343 return errno;
1347 route_del(struct rtentry *rt)
1349 if (rt->rt_dev) {
1350 route_ctrl(SIOCDELRT, rt);
1351 free(rt->rt_dev);
1352 rt->rt_dev = NULL;
1354 return 0;
1358 route_add(const struct in_addr inetaddr, struct rtentry *rt)
1360 char buf[256], dev[64];
1361 int metric, flags;
1362 u_int32_t dest, mask;
1364 FILE *f = fopen("/proc/net/route", "r");
1365 if (f == NULL) {
1366 l2tp_log (LOG_ERR, "/proc/net/route: %s", strerror(errno));
1367 return -1;
1370 while (fgets(buf, sizeof(buf), f)) {
1371 if (sscanf(buf, "%63s %x %x %X %*s %*s %d %x", dev, &dest,
1372 &sin_addr(&rt->rt_gateway).s_addr, &flags, &metric, &mask) != 6)
1373 continue;
1374 if ((flags & RTF_UP) == (RTF_UP) && (inetaddr.s_addr & mask) == dest &&
1375 (dest || strncmp(dev, "ppp", 3)) /* avoid default via pppX to avoid on-demand loops*/) {
1376 rt->rt_metric = metric + 1;
1377 rt->rt_gateway.sa_family = AF_INET;
1378 break;
1382 fclose(f);
1384 /* check for no route */
1385 if (rt->rt_gateway.sa_family != AF_INET) {
1386 /* l2tp_log (LOG_ERR, "route_add: no route to host"); */
1387 return -1;
1390 /* check for existing route to this host,
1391 add if missing based on the existing routes */
1392 if (flags & RTF_HOST) {
1393 /* l2tp_log (LOG_ERR, "route_add: not adding existing route"); */
1394 return -1;
1397 sin_addr(&rt->rt_dst) = inetaddr;
1398 rt->rt_dst.sa_family = AF_INET;
1400 sin_addr(&rt->rt_genmask).s_addr = INADDR_BROADCAST;
1401 rt->rt_genmask.sa_family = AF_INET;
1403 rt->rt_flags = RTF_UP | RTF_HOST;
1404 if (flags & RTF_GATEWAY)
1405 rt->rt_flags |= RTF_GATEWAY;
1407 rt->rt_metric++;
1408 rt->rt_dev = strdup(dev);
1410 if (!rt->rt_dev) {
1411 l2tp_log (LOG_ERR, "route_add: no memory");
1412 return -1;
1415 if (!route_ctrl(SIOCADDRT, rt))
1416 return 0;
1418 free(rt->rt_dev);
1419 rt->rt_dev = NULL;
1421 return -1;