1/*
2 * Layer Two Tunnelling Protocol Daemon
3 * Copyright (C) 1998 Adtran, Inc.
4 * Copyright (C) 2002 Jeff McAdams
5 *
6 * Mark Spencer
7 *
8 * This software is distributed under the terms
9 * of the GPL, which you should have received
10 * along with this source.
11 *
12 * Main Daemon source.
13 *
14 */
15
16#include <stdlib.h>
17#include <sys/utsname.h>
18#include <sys/stat.h>
19#include <sys/wait.h>
20#include <stdio.h>
21#include <errno.h>
22#include <unistd.h>
23#if (__GLIBC__ < 2)
24# if defined(FREEBSD)
25#  include <sys/signal.h>
26# elif defined(LINUX)
27#  include <bsd/signal.h>
28# elif defined(SOLARIS)
29#  include <signal.h>
30# endif
31#else
32# include <signal.h>
33#endif
34#include <netdb.h>
35#include <string.h>
36#include <fcntl.h>
37#include <netinet/in.h>
38#include <arpa/inet.h>
39#ifdef USE_KERNEL
40#include <sys/ioctl.h>
41#endif
42#include "l2tp.h"
43
44#ifdef PPPOX_L2TP
45#include "pppol2tp.h"
46#endif
47
48
49struct tunnel_list tunnels;
50int max_tunnels = DEF_MAX_TUNNELS;
51struct utsname uts;
52int ppd = 1;                    /* Packet processing delay */
53int control_fd;                 /* descriptor of control area */
54char *args;
55
56char *dial_no_tmp;              /* jz: Dialnumber for Outgoing Call */
57int switch_io = 0;              /* jz: Switch for Incoming or Outgoing Call */
58
59void init_tunnel_list (struct tunnel_list *t)
60{
61    t->head = NULL;
62    t->count = 0;
63    t->calls = 0;
64}
65
66void show_status (int fd)
67{
68    struct schedule_entry *se;
69    struct tunnel *t;
70    struct call *c;
71    struct lns *tlns;
72    struct lac *tlac;
73    struct host *h;
74    int s = 0;
75    int fd2 = dup (fd);
76    FILE *f = fdopen (fd2, "a");
77    if (!f)
78    {
79        log (LOG_WARN, "show_status: fdopen() failed on fd %d\n", fd);
80        return;
81    }
82    fprintf (f, "====== l2tpd statistics ========\n");
83    fprintf (f, " Scheduler entries:\n");
84    se = events;
85    while (se)
86    {
87        s++;
88        t = (struct tunnel *) se->data;
89        tlac = (struct lac *) se->data;
90        c = (struct call *) se->data;
91        if (se->func == &hello)
92        {
93            fprintf (f, "%d: HELLO to %d\n", s, t->tid);
94        }
95        else if (se->func == &magic_lac_dial)
96        {
97            fprintf (f, "%d: Magic dial on %s\n", s, tlac->entname);
98        }
99        else if (se->func == &send_zlb)
100        {
101            fprintf (f, "%d: Send payload ZLB on call %d:%d\n", s,
102                     c->container->tid, c->cid);
103        }
104        else if (se->func == &dethrottle)
105        {
106            fprintf (f, "%d: Dethrottle call %d:%d\n", s, c->container->tid,
107                     c->cid);
108        }
109        else
110            fprintf (f, "%d: Unknown event\n", s);
111        se = se->next;
112    };
113    fprintf (f, "Total Events scheduled: %d\n", s);
114    fprintf (f, "Number of tunnels open: %d\n", tunnels.count);
115    fprintf (f, "Highest file descriptor: %d\n", fd2);
116    t = tunnels.head;
117    while (t)
118    {
119        fprintf (f, "Tunnel %s, ID = %d (local), %d (remote) to %s:%d\n"
120                 "   control_seq_num = %d, control_rec_seq_num = %d,\n"
121                 "   cLr = %d\n",
122                 (t->lac ? t->lac->entname : (t->lns ? t->lns->entname : "")),
123                 t->ourtid, t->tid, IPADDY (t->peer.sin_addr),
124                 ntohs (t->peer.sin_port), t->control_seq_num,
125                 t->control_rec_seq_num, t->cLr);
126        c = t->call_head;
127        while (c)
128        {
129            fprintf (f,
130                     "Call %s, ID = %d (local), %d (remote), serno = %u,\n"
131                     "      data_seq_num = %d, data_rec_seq_num = %d,\n"
132                     "      pLr = %d, tx = %u bytes (%u), rx= %u bytes (%u)\n",
133                     (c->lac ? c->lac->
134                      entname : (c->lns ? c->lns->entname : "")), c->ourcid,
135                     c->cid, c->serno, c->data_seq_num, c->data_rec_seq_num,
136                     c->pLr, c->tx_bytes, c->tx_pkts, c->rx_bytes, c->rx_pkts);
137            c = c->next;
138        }
139        t = t->next;
140    }
141    fprintf (f, "==========Config File===========\n");
142    tlns = lnslist;
143    while (tlns)
144    {
145        fprintf (f, "LNS entry %s\n",
146                 tlns->entname[0] ? tlns->entname : "(unnamed)");
147        tlns = tlns->next;
148    };
149    tlac = laclist;
150    while (tlac)
151    {
152        fprintf (f, "LAC entry %s, LNS is/are:",
153                 tlac->entname[0] ? tlac->entname : "(unnamed)");
154        h = tlac->lns;
155        if (h)
156        {
157            while (h)
158            {
159                fprintf (f, " %s", h->hostname);
160                h = h->next;
161            }
162        }
163        else
164            fprintf (f, " [none]");
165        fprintf (f, "\n");
166        tlac = tlac->next;
167    };
168    fprintf (f, "================================\n");
169    fclose (f);
170    close (fd2);
171}
172
173void null_handler(int sig)
174{
175       /* FIXME
176        * A sighup is received when a call is terminated, unknown origine ..
177        * I catch it and ll looks good, but ..
178	*/
179}
180
181void status_handler (int sig)
182{
183    show_status (1);
184}
185
186void child_handler (int signal)
187{
188    /*
189     * Oops, somebody we launched was killed.
190     * It's time to reap them and close that call.
191     * But first, we have to find out what PID died.
192     * unfortunately, pppd will
193     */
194    struct tunnel *t;
195    struct call *c;
196    pid_t pid;
197    int status;
198    t = tunnels.head;
199    pid = waitpid (-1, &status, WNOHANG);
200    if (pid < 1)
201    {
202        /*
203         * Oh well, nobody there.  Maybe we reaped it
204         * somewhere else already
205         */
206        return;
207    }
208    while (t)
209    {
210        c = t->call_head;
211        while (c)
212        {
213            if (c->pppd == pid)
214            {
215                log (LOG_DEBUG, "%s : pppd died for call %d\n", __FUNCTION__,
216                     c->cid);
217                c->needclose = -1;
218                /*
219                 * OK...pppd died, we can go ahead and close the pty for
220                 * it
221                 */
222                close (c->fd);
223                return;
224            }
225            c = c->next;
226        }
227        t = t->next;
228    }
229}
230
231void death_handler (int signal)
232{
233    /*
234       * If we get here, somebody terminated us with a kill or a control-c.
235       * we call call_close on each tunnel twice to get a StopCCN out
236       * for each one (we can't pause to make sure it's received.
237       * Then we close the connections
238     */
239    struct tunnel *st, *st2;
240    int sec;
241    log (LOG_CRIT, "%s: Fatal signal %d received\n", __FUNCTION__, signal);
242    st = tunnels.head;
243    while (st)
244    {
245        st2 = st->next;
246        strcpy (st->self->errormsg, "Server closing");
247        sec = st->self->closing;
248        if (st->lac)
249            st->lac->redial = 0;
250        /* Foxconn added start pling 08/31/2010 */
251        /* Disconnect the call (send CDN) tear down tunnel (StopCCN) */
252        call_close(st->call_head);
253        /* Foxconn added end pling 08/31/2010 */
254        call_close (st->self);
255        if (!sec)
256        {
257            st->self->closing = -1;
258            call_close (st->self);
259        }
260        st = st2;
261    }
262
263    /* erase pid file */
264	unlink (gconfig.pidfile);
265
266#ifdef PPPOX_L2TP
267    extern int pox_fd;
268    extern int ppp_fd;
269
270    if(ppp_fd >= 0){
271        if (ioctl(ppp_fd, PPPIOCDETACH) < 0)
272            log (LOG_DEBUG, "detach ioctl(PPPIOCDETACH) failed");
273    }
274
275    if(pox_fd){
276        close(pox_fd);
277    }
278
279#endif
280
281    exit (1);
282}
283
284int start_pppd (struct call *c, struct ppp_opts *opts)
285{
286    char a, b;
287    char tty[80];
288    char *stropt[80];
289    struct ppp_opts *p;
290#ifdef USE_KERNEL
291    struct l2tp_call_opts co;
292#endif
293    int pos = 1;
294    int fd2;
295#ifdef DEBUG_PPPD
296    int x;
297#endif
298    struct termios ptyconf;
299    char *str;
300    p = opts;
301    stropt[0] = strdup (PPPD);
302    while (p)
303    {
304        stropt[pos] = (char *) malloc (strlen (p->option) + 1);
305        strncpy (stropt[pos], p->option, strlen (p->option) + 1);
306        pos++;
307        p = p->next;
308    }
309    stropt[pos] = NULL;
310    if (c->pppd > 0)
311    {
312        log (LOG_WARN, "%s: PPP already started on call!\n", __FUNCTION__);
313        return -EINVAL;
314    }
315    if (c->fd > -1)
316    {
317        log (LOG_WARN, "%s: file descriptor already assigned!\n",
318             __FUNCTION__);
319        return -EINVAL;
320    }
321#ifdef USE_KERNEL
322    if (kernel_support)
323    {
324        co.ourtid = c->container->ourtid;
325        co.ourcid = c->ourcid;
326        ioctl (server_socket, L2TPIOCGETCALLOPTS, &co);
327        stropt[pos++] = strdup ("channel");
328        stropt[pos] = (char *) malloc (10);
329        snprintf (stropt[pos], 10, "%d", co.id);
330        pos++;
331        stropt[pos] = NULL;
332    }
333    else
334    {
335#endif
336        int flags;
337
338        c->fd = STDOUT_FILENO;
339
340        flags = fcntl(c->fd, F_GETFL);
341        flags |= O_NONBLOCK;
342        fcntl(c->fd, F_SETFL, flags);
343
344        //dup2(STDOUT_FILENO, c->fd);
345        //dup2(STDIN_FILENO,  c->fd);
346
347        /*
348        if ((c->fd = getPtyMaster (&a, &b)) < 0)
349        {
350            log (LOG_WARN, "%s: unable to allocate pty, abandoning!\n",
351                 __FUNCTION__);
352            return -EINVAL;
353        }
354        */
355        // set fd opened above to not echo so we don't see read our own packets
356        //   back of the file descriptor that we just wrote them to
357        tcgetattr (c->fd, &ptyconf);
358        *(c->oldptyconf) = ptyconf;
359        ptyconf.c_cflag &= ~(ICANON | ECHO);
360        tcsetattr (c->fd, TCSANOW, &ptyconf);
361        /*
362        snprintf (tty, sizeof (tty), "/dev/tty%c%c", a, b);
363
364	    //snprintf (tty, sizeof (tty), "/tmp/ttyp0");
365	    log (LOG_DEBUG, "try to open %s\n", tty);
366
367        fd2 = open (tty, O_RDWR);
368        */
369#ifdef USE_KERNEL
370    }
371#endif
372    str = stropt[0];
373#ifdef DEBUG_PPPD
374    /*log (LOG_DEBUG, "%s: I'm running:  ", __FUNCTION__);
375    for (x = 0; stropt[x]; x++)
376    {
377        log (LOG_DEBUG, "\"%s\" ", stropt[x]);
378    };
379    log (LOG_DEBUG, "\n");*/
380#endif
381    c->pppd = 88888;
382    /*
383    c->pppd = fork ();
384
385    if (c->pppd < 0) //fork failed
386    {
387        log (LOG_WARN, "%s: unable to fork(), abandoning!\n", __FUNCTION__);
388        return -EINVAL;
389    }
390    else if (!c->pppd) //pid==0, child process;
391    {
392        struct call *sc;
393        struct tunnel *st;
394
395        //close (0);
396        //close (1);
397        //close (2);
398#ifdef USE_KERNEL
399        if (!kernel_support && (fd2 < 0))
400#else
401        if (fd2 < 0)
402#endif
403        {
404            log (LOG_WARN, "%s: Unable to open %s to launch pppd!\n",
405                 __FUNCTION__, tty);
406            exit (1);
407        }
408        dup2 (fd2, 0);
409        dup2 (fd2, 1);
410
411
412        // close all the calls pty fds
413        st = tunnels.head;
414        while (st)
415        {
416            sc = st->call_head;
417            while (sc)
418            {
419                close (sc->fd);
420                sc = sc->next;
421            }
422            st = st->next;
423        }
424
425        // close the UDP socket fd
426        close (server_socket);
427
428        // close the control pipe fd
429        close (control_fd);
430
431	    printf ("===================\n");
432	    printf ("%s\n", PPPD);
433	    for (x = 0; stropt[x]; x++)
434    	{
435        	printf ("\"%s\" ", stropt[x]);
436    	};
437        execv (PPPD, stropt);
438	    printf ("===================\n");
439
440        printf("%s: Exec of %s failed!\n", __FUNCTION__, PPPD);
441        exit (1);
442    };
443    close (fd2);
444    */
445    pos = 0;
446    while (stropt[pos])
447    {
448        free (stropt[pos]);
449        pos++;
450    };
451    return 0;
452}
453
454void destroy_tunnel (struct tunnel *t)
455{
456    /*
457     * Immediately destroy a tunnel (and all its calls)
458     * and free its resources.  This may be called
459     * by the tunnel itself,so it needs to be
460     * "suicide safe"
461     */
462
463    struct call *c, *me;
464    struct tunnel *p;
465    struct timeval tv;
466    if (!t)
467        return;
468
469    /*
470     * Save ourselves until the very
471     * end, since we might be calling this ourselves.
472     * We must divorce ourself from the tunnel
473     * structure, however, to avoid recursion
474     * because of the logic of the destroy_call
475     */
476    me = t->self;
477
478    /*
479     * Destroy all the member calls
480     */
481    c = t->call_head;
482    while (c)
483    {
484        destroy_call (c);
485        c = c->next;
486    };
487    /*
488     * Remove ourselves from the list of tunnels
489     */
490
491    if (tunnels.head == t)
492    {
493        tunnels.head = t->next;
494        tunnels.count--;
495    }
496    else
497    {
498        p = tunnels.head;
499        if (p)
500        {
501            while (p->next && (p->next != t))
502                p = p->next;
503            if (p->next)
504            {
505                p->next = t->next;
506                tunnels.count--;
507            }
508            else
509            {
510                log (LOG_WARN,
511                     "%s: unable to locate tunnel in tunnel list\n",
512                     __FUNCTION__);
513            }
514        }
515        else
516        {
517            log (LOG_WARN, "%s: tunnel list is empty!\n", __FUNCTION__);
518        }
519    }
520    if (t->lac)
521    {
522        t->lac->t = NULL;
523        if (t->lac->redial && (t->lac->rtimeout > 0) && !t->lac->rsched &&
524            t->lac->active)
525        {
526            log (LOG_LOG, "%s: Will redial in %d seconds\n", __FUNCTION__,
527                 t->lac->rtimeout);
528            tv.tv_sec = t->lac->rtimeout;
529            tv.tv_usec = 0;
530            t->lac->rsched = schedule (tv, magic_lac_dial, t->lac);
531        }
532    }
533    /* XXX L2TP/IPSec: remove relevant SAs here?  NTB 20011010
534     * XXX But what if another tunnel is using same SA?
535     */
536    if (t->lns)
537        t->lns->t = NULL;
538    free (t);
539    free (me);
540}
541
542
543/* Foxconn, add start by MJ., copied from pptp.c 01/29/2010 */
544/* If L2TP server isn't on WAN side.
545 * We need to set a routing for Server's IP to pass ethernet
546 * act1: add, 2: del
547 * inetadd: IP of L2TP server
548 */
549static char del_host_cmd[64]="";
550
551#undef DEBUG_SERV_IP_ROUTING
552#define IPV4_LEN        4
553
554#ifdef STATIC_PPPOE
555void fxc_add_gw(int act, struct in_addr inetaddr) /*1: add, 2: del*/
556{
557    //struct sockaddr_pptpox sp_info;
558    FILE *fp = NULL;
559    unsigned char buf[128];
560    //unsigned char gateWay[IPV4_LEN];
561    unsigned char name[32];     // foxconn modified pling 07/26/2010, 12->32
562    char value[18];
563    char getGateway[18]= "";
564    char getUserIp[18]= "";
565    char getNetmask[18]= "";
566    char gate_way[] = "gateway_addr";
567    char user_ipaddr[] = "user_ip_addr";
568    char netmask_addr[] = "netmask_addr";
569    char user_nvram[] = "l2tp_user_ip";
570    char gw_nvram[] = "l2tp_gateway_ip";
571    char netmask_nvram[] = "l2tp_user_netmask";
572    char command[64];
573
574    del_host_cmd[0] = '\0';
575
576    if ((fp = fopen("/tmp/ppp/dhcpIp", "r")) != NULL)
577    {/* If server IP, resolved from udhcpc. */
578        while (fgets(buf, sizeof(buf), fp))
579        {
580            name[0] = '\0';
581            value[0] = '\0';
582            sscanf(buf, "%s %s", &name[0],&value[0]);
583
584            if (strcmp(name, user_ipaddr) == 0)
585            {
586                strcpy(getUserIp,value);
587            }
588            else if (strcmp(name, gate_way) == 0)
589            {
590                strcpy(getGateway,value);
591            }
592            else if (strcmp(name, netmask_addr) == 0)
593            {
594                strcpy(getNetmask,value);
595            }
596        }
597        fclose(fp);
598    }
599    else if ((fp = fopen("/tmp/ppp/l2tpIp", "r")) != NULL)
600    {/* If server IP, gotten from the user setting */
601        while (fgets(buf, sizeof(buf), fp))
602        {
603            name[0] = '\0';
604            value[0] = '\0';
605            sscanf(buf, "%s %s", &name[0],&value[0]);
606
607            if (strcmp(name, user_nvram) == 0)
608            {
609                strcpy(getUserIp,value);
610            }
611            else if (strcmp(name, gw_nvram) == 0)
612            {
613                strcpy(getGateway,value);
614            }
615            else if (strcmp(name, netmask_nvram) == 0)
616            {
617                strcpy(getNetmask,value);
618            }
619        }
620        fclose(fp);
621    }
622#ifdef DEBUG_SERV_IP_ROUTING
623    printf("%s user IP: %s\n", __FUNCTION__, getUserIp);
624    printf("%s gateway IP:%s\n", __FUNCTION__, getGateway);
625    printf("%s netmask:%s\n", __FUNCTION__, getNetmask);
626#endif
627
628
629    if (getUserIp[0] != '\0')
630    {
631        /* Foxconn added start pling 03/30/2012 */
632        /* get the wan interface name properly */
633        char wan_ifname[32] = "vlan2";
634        char dns_srv1[32];
635        char dns_srv2[32];
636        fp = fopen("/tmp/ppp/l2tpIp", "r");
637        if (fp)
638        {
639            fgets(buf, sizeof(buf), fp);
640            fclose(fp);
641            strcpy(wan_ifname, buf);
642        }
643        /* Foxconn added end pling 03/30/2012 */
644
645        if ( act == 1 )
646        {
647            /* Foxconn added start pling 03/30/2012 */
648            /* Change the way to add default gateway, in case the gateway is
649            * in different subnet from the WAN IP. */
650            sprintf(command, "route add -host %s dev %s", getGateway, wan_ifname);
651            system(command);
652            /* Foxconn added end pling 03/30/2012 */
653
654            /* Foxconn removed start by Bob, 12/23/2013,
655            the default route should be removed when act==2, but for unknown reason,
656            the default route is not deleted in end user's environmnet, so we just add host route here.
657            It's unnecessary to add default route. */
658            /*
659            sprintf(command, "route add default gw %s", getGateway) ;
660            system(command);
661            */
662            /* Foxconn removed end by Bob, 12/23/2013 */
663
664#ifdef DEBUG_SERV_IP_ROUTING
665            printf("%s: %s\n", __FUNCTION__, command);
666#endif
667        }
668        else if ( act == 2 )  /* remove default gateway and add host route */
669        {
670            unsigned int i_wanip, i_netmask;
671            system(del_host_cmd); /* remove last host route here */
672            system("route del default");
673#ifdef DEBUG_SERV_IP_ROUTING
674            printf("%s\n", del_host_cmd);
675            printf("route del default\n");
676#endif
677            if ((strcmp (getUserIp,"0.0.0.0") != 0) && (strcmp (getNetmask,"0.0.0.0") != 0))
678            {
679                i_wanip = inet_addr(getUserIp);
680                i_netmask = inet_addr(getNetmask);
681
682                if((i_wanip & i_netmask) != (inetaddr.s_addr & i_netmask))
683                {
684                    /* Foxconn added start pling 03/30/2012 */
685                    /* Change the way to add default gateway, in case the gateway is
686                    * in different subnet from the WAN IP. */
687                    sprintf(command, "route add -host %s dev %s", getGateway, wan_ifname);
688                    system(command);
689                    /* Foxconn added end pling 03/30/2012 */
690
691                    sprintf(command, "route add -host %s gw %s",
692                            inet_ntoa(inetaddr), getGateway);
693                    system(command);
694#ifdef DEBUG_SERV_IP_ROUTING
695                    printf("%s: %s\n", __FUNCTION__, command);
696#endif
697                }
698            }
699
700        }
701    }
702}
703#else
704void fxc_add_gw(int act, struct in_addr inetaddr) /*1: add, 2: del*/
705{
706    //struct sockaddr_pptpox sp_info; /*commented by MJ.*/
707    FILE *fp = NULL;
708    unsigned char buf[128];
709    unsigned char gateWay[IPV4_LEN];
710    unsigned char addrname[12];
711    unsigned int getIp[IPV4_LEN];
712    char gate_way[] = "gateway_addr";
713    char command[64];
714
715    del_host_cmd[0] = '\0';
716
717    if ((fp = fopen("/tmp/ppp/dhcpIp", "r")) != NULL)
718    {
719        /* commented by MJ.
720        // I can't find a place to use these variables.
721        memset(&sp_info, 0, sizeof(struct sockaddr_pptpox));
722
723        sp_info.sa_family = AF_PPPOX;
724        sp_info.sa_protocol = PX_PROTO_TP;
725        */
726        memset(gateWay, 0, IPV4_LEN);
727
728        while (fgets(buf, sizeof(buf), fp))
729        {
730            sscanf(buf, "%s %d.%d.%d.%d", &addrname[0],
731                &getIp[0], &getIp[1], &getIp[2], &getIp[3]);
732
733            if (memcmp(addrname, gate_way, sizeof(gate_way)) == 0)
734            {
735                if ( act == 1 )
736                {
737                    sprintf(command, "route add default gw %d.%d.%d.%d",
738                            getIp[0], getIp[1], getIp[2], getIp[3]);
739                    system(command);
740                }
741                else if ( act == 2 )  /* remove default gateway and add host route */
742                {
743                    system(del_host_cmd); /* remove last host route here */
744                    system("route del default");
745                    sprintf(command, "route add -host %s gw %d.%d.%d.%d",
746                    inet_ntoa(inetaddr), getIp[0], getIp[1], getIp[2], getIp[3]);
747                    system(command);
748
749                    sprintf(del_host_cmd, "route del %s gw %d.%d.%d.%d",
750                            inet_ntoa(inetaddr), getIp[0], getIp[1], getIp[2], getIp[3]);
751                }
752
753                fclose(fp);
754                return;
755            }
756        }
757        fclose(fp);
758    }
759}
760#endif
761
762/* Foxconn, add end by MJ., 01/29/2010*/
763
764struct tunnel *l2tp_call (char *host, int port, struct lac *lac,
765                          struct lns *lns)
766{
767    /*
768     * Establish a tunnel from us to host
769     * on port port
770     */
771    struct call *tmp = NULL;
772    struct hostent *hp;
773    unsigned int addr;
774    FILE *fp;
775    port = htons (port);
776
777    /* Foxconn, added by MJ. 01/29/2010 */
778    struct in_addr l2tp_serv_ip;
779
780    /* add routing for DNS server 01/29/2010*/
781    fxc_add_gw(1, l2tp_serv_ip);
782    /* Foxconn, added end.*/
783
784    hp = gethostbyname (host);
785
786    if (!hp)
787    {
788        log (LOG_WARN, "%s: gethostbyname() failed for %s.\n", __FUNCTION__,
789             host);
790        return NULL;
791    }
792    bcopy (hp->h_addr, &addr, hp->h_length);
793
794    /* Foxconn, add start by MJ., for l2tp. 01/28/2010 */
795
796    if (hp->h_addrtype == AF_INET){
797        memcpy(&l2tp_serv_ip.s_addr, hp->h_addr, sizeof(l2tp_serv_ip.s_addr));
798        if ( fp = fopen("/tmp/ppp/l2tpSrvIp", "w") )
799        {
800            fprintf(fp, "%s", inet_ntoa(l2tp_serv_ip));
801            fclose(fp);
802        }
803    }
804
805    /* Add routing for L2TP server */
806    fxc_add_gw(2, l2tp_serv_ip);
807    /* Foxconn, add end, by MJ., for l2tp. 01/28/2010 */
808
809
810    /* Force creation of a new tunnel
811       and set it's tid to 0 to cause
812       negotiation to occur */
813    /* XXX L2TP/IPSec: Set up SA to addr:port here?  NTB 20011010
814     */
815    tmp = get_call (0, 0, addr, port);
816    if (!tmp)
817    {
818        log (LOG_WARN, "%s: Unable to create tunnel to %s.\n", __FUNCTION__,
819             host);
820        return NULL;
821    }
822    tmp->container->tid = 0;
823    tmp->container->lac = lac;
824    tmp->container->lns = lns;
825    tmp->lac = lac;
826    tmp->lns = lns;
827    if (lac)
828        lac->t = tmp->container;
829    if (lns)
830        lns->t = tmp->container;
831    /*
832     * Since our state is 0, we will establish a tunnel now
833     */
834    log (LOG_LOG, "%s:Connecting to host %s, port %d\n", __FUNCTION__, host,
835         ntohs (port));
836    control_finish (tmp->container, tmp);
837    return tmp->container;
838}
839
840void magic_lac_tunnel (void *data)
841{
842    struct lac *lac;
843    lac = (struct lac *) data;
844    if (!lac)
845    {
846        log (LOG_WARN, "%s: magic_lac_tunnel: called on NULL lac!\n",
847             __FUNCTION__);
848        return;
849    }
850    if (lac->lns)
851    {
852        /* FIXME: I should try different LNS's if I get failures */
853        l2tp_call (lac->lns->hostname, lac->lns->port, lac, NULL);
854        return;
855    }
856    else if (deflac && deflac->lns)
857    {
858        l2tp_call (deflac->lns->hostname, deflac->lns->port, lac, NULL);
859        return;
860    }
861    else
862    {
863        log (LOG_WARN, "%s: Unable to find hostname to dial for '%s'\n",
864             __FUNCTION__, lac->entname);
865        return;
866    }
867}
868
869struct call *lac_call (int tid, struct lac *lac, struct lns *lns)
870{
871    struct tunnel *t = tunnels.head;
872    struct call *tmp;
873    while (t)
874    {
875        if (t->ourtid == tid)
876        {
877            tmp = new_call (t);
878            if (!tmp)
879            {
880                log (LOG_WARN, "%s: unable to create new call\n",
881                     __FUNCTION__);
882                return NULL;
883            }
884            tmp->next = t->call_head;
885            t->call_head = tmp;
886            t->count++;
887            tmp->cid = 0;
888            tmp->lac = lac;
889            tmp->lns = lns;
890            if (lac)
891                lac->c = tmp;
892            log (LOG_LOG, "%s: Calling on tunnel %d\n", __FUNCTION__, tid);
893            strcpy (tmp->dial_no, dial_no_tmp); /*  jz: copy dialnumber to tmp->dial_no  */
894            control_finish (t, tmp);
895            return tmp;
896        }
897        t = t->next;
898    };
899    log (LOG_DEBUG, "%s: No such tunnel %d to generate call.\n", __FUNCTION__,
900         tid);
901    return NULL;
902}
903
904void magic_lac_dial (void *data)
905{
906    struct lac *lac;
907    lac = (struct lac *) data;
908    if (!lac->active)
909    {
910        log (LOG_DEBUG, "%s: LAC %s not active", __FUNCTION__, lac->entname);
911        return;
912    }
913    lac->rsched = NULL;
914    lac->rtries++;
915    if (lac->rmax && (lac->rtries > lac->rmax))
916    {
917        log (LOG_LOG, "%s: maximum retries exceeded.\n", __FUNCTION__);
918        return;
919    }
920    if (!lac)
921    {
922        log (LOG_WARN, "%s : called on NULL lac!\n", __FUNCTION__);
923        return;
924    }
925    if (!lac->t)
926    {
927#ifdef DEGUG_MAGIC
928        log (LOG_DEBUG, "%s : tunnel not up!  Connecting!\n", __FUNCTION__);
929#endif
930        magic_lac_tunnel (lac);
931        return;
932    }
933    lac_call (lac->t->ourtid, lac, NULL);
934}
935
936void lac_hangup (int cid)
937{
938    struct tunnel *t = tunnels.head;
939    struct call *tmp;
940    while (t)
941    {
942        tmp = t->call_head;
943        while (tmp)
944        {
945            if (tmp->ourcid == cid)
946            {
947                log (LOG_LOG,
948                     "%s :Hanging up call %d, Local: %d, Remote: %d\n",
949                     __FUNCTION__, tmp->serno, tmp->ourcid, tmp->cid);
950                strcpy (tmp->errormsg, "Goodbye!");
951/*				tmp->needclose = -1; */
952                kill (tmp->pppd, SIGTERM);
953                return;
954            }
955            tmp = tmp->next;
956        }
957        t = t->next;
958    };
959    log (LOG_DEBUG, "%s : No such call %d to hang up.\n", __FUNCTION__, cid);
960    return;
961}
962
963void lac_disconnect (int tid)
964{
965    struct tunnel *t = tunnels.head;
966    while (t)
967    {
968        if (t->ourtid == tid)
969        {
970            log (LOG_LOG,
971                 "%s: Disconnecting from %s, Local: %d, Remote: %d\n",
972                 __FUNCTION__, IPADDY (t->peer.sin_addr), t->ourtid, t->tid);
973            t->self->needclose = -1;
974            strcpy (t->self->errormsg, "Goodbye!");
975            call_close (t->self);
976            return;
977        }
978        t = t->next;
979    };
980    log (LOG_DEBUG, "%s: No such tunnel %d to hang up.\n", __FUNCTION__, tid);
981    return;
982}
983
984struct tunnel *new_tunnel ()
985{
986    struct tunnel *tmp = malloc (sizeof (struct tunnel));
987    char entropy_buf[2] = "\0";
988    if (!tmp)
989        return NULL;
990    tmp->control_seq_num = 0;
991    tmp->control_rec_seq_num = 0;
992    tmp->cLr = 0;
993    tmp->call_head = NULL;
994    tmp->next = NULL;
995    tmp->debug = -1;
996    tmp->tid = -1;
997    tmp->hello = NULL;
998#ifndef TESTING
999/*	while(get_call((tmp->ourtid = rand() & 0xFFFF),0,0,0)); */
1000#ifdef USE_KERNEL
1001    if (kernel_support)
1002        tmp->ourtid = ioctl (server_socket, L2TPIOCADDTUNNEL, 0);
1003    else
1004#endif
1005/*        tmp->ourtid = rand () & 0xFFFF; */
1006        /* get_entropy((char *)&tmp->ourtid, 2); */
1007        get_entropy(entropy_buf, 2);
1008        {
1009            int *temp;
1010            temp = (int *)entropy_buf;
1011            tmp->ourtid = *temp & 0xFFFF;
1012#ifdef DEBUG_ENTROPY
1013            log(LOG_DEBUG, "ourtid = %u, entropy_buf = %hx\n", tmp->ourtid, *temp);
1014#endif
1015        }
1016#else
1017    tmp->ourtid = 0x6227;
1018#endif
1019    tmp->nego = 0;
1020    tmp->count = 0;
1021    tmp->state = 0;             /* Nothing */
1022    tmp->peer.sin_family = AF_INET;
1023    tmp->peer.sin_port = 0;
1024    bzero (&(tmp->peer.sin_addr), sizeof (tmp->peer.sin_addr));
1025    tmp->sanity = -1;
1026    tmp->qtid = -1;
1027    tmp->ourfc = ASYNC_FRAMING | SYNC_FRAMING;
1028    tmp->ourbc = 0;
1029    tmp->ourtb = (((_u64) rand ()) << 32) | ((_u64) rand ());
1030    tmp->fc = -1;               /* These really need to be specified by the peer */
1031    tmp->bc = -1;               /* And we want to know if they forgot */
1032    tmp->hostname[0] = 0;
1033    tmp->vendor[0] = 0;
1034    tmp->secret[0] = 0;
1035    if (!(tmp->self = new_call (tmp)))
1036    {
1037        free (tmp);
1038        return NULL;
1039    };
1040    tmp->ourrws = DEFAULT_RWS_SIZE;
1041    tmp->self->ourfbit = FBIT;
1042    tmp->lac = NULL;
1043    tmp->lns = NULL;
1044    tmp->chal_us.state = 0;
1045    tmp->chal_us.secret[0] = 0;
1046    memset (tmp->chal_us.reply, 0, MD_SIG_SIZE);
1047    tmp->chal_them.state = 0;
1048    tmp->chal_them.secret[0] = 0;
1049    memset (tmp->chal_them.reply, 0, MD_SIG_SIZE);
1050    tmp->chal_them.vector = (unsigned char *) malloc (VECTOR_SIZE);
1051    tmp->chal_us.vector = NULL;
1052    tmp->hbit = 0;
1053    return tmp;
1054}
1055
1056void do_control (char *cmd)
1057{
1058    char buf[1024];
1059    char *host;
1060    char *tunstr;
1061    char *callstr;
1062
1063    char *sub_str;              /* jz: use by the strtok function */
1064    char *tmp_ptr;              /* jz: use by the strtok function */
1065    struct lac *lac;
1066    int call;
1067    int tunl;
1068    int cnt = -1;
1069    int first_run = 0;
1070
1071
1072    while (cnt)
1073    {
1074        /* Foxconn, add by MJ. for building L2TP tunnel in the begining. */
1075        if(cmd != NULL)
1076        {
1077            first_run = 1;
1078            strcpy(buf, cmd);
1079            cnt = strlen(buf);
1080            log (LOG_DEBUG, "%s -> L2TP connect immediately. \n", __FUNCTION__);
1081        }
1082        else
1083            cnt = read (control_fd, buf, sizeof (buf));
1084        /*add end, by MJ.*/
1085        if (cnt > 0)
1086        {
1087            if (buf[cnt - 1] == '\n')
1088                buf[--cnt] = 0;
1089#ifdef DEBUG_CONTROL
1090            log (LOG_DEBUG, "%s: Got message %s (%d bytes long)\n",
1091                 __FUNCTION__, buf, cnt);
1092#endif
1093            switch (buf[0])
1094            {
1095            case 't':
1096                host = strchr (buf, ' ') + 1;
1097#ifdef DEBUG_CONTROL
1098                log (LOG_DEBUG, "%s: Attempting to tunnel to %s\n",
1099                     __FUNCTION__, host);
1100#endif
1101                l2tp_call (host, UDP_LISTEN_PORT, NULL, NULL);
1102                break;
1103            case 'c':
1104
1105                switch_io = 1;  /* jz: Switch for Incoming - Outgoing Calls */
1106
1107                tunstr = strchr (buf, ' ') + 1;
1108                lac = laclist;
1109                while (lac)
1110                {
1111                    if (!strcasecmp (lac->entname, tunstr))
1112                    {
1113                        lac->active = -1;
1114                        lac->rtries = 0;
1115                        if (!lac->c)
1116                            magic_lac_dial (lac);
1117                        else
1118                            log (LOG_DEBUG,
1119                                 "%s: Session '%s' already active!\n",
1120                                 __FUNCTION__, lac->entname);
1121                        break;
1122                    }
1123                    lac = lac->next;
1124                }
1125                if (lac){
1126                    if (first_run) cnt = 0; /*Foxconn, by MJ., for leaving while*/
1127                    break;
1128                }
1129                tunl = atoi (tunstr);
1130                if (!tunl)
1131                {
1132                    log (LOG_DEBUG, "%s: No such tunnel '%s'\n", __FUNCTION__,
1133                         tunstr);
1134                    if (first_run) cnt = 0; /*Foxconn, by MJ., for leaving while*/
1135                    break;
1136                }
1137#ifdef DEBUG_CONTROL
1138                log (LOG_DEBUG, "%s: Attempting to call on tunnel %d\n",
1139                     __FUNCTION__, tunl);
1140#endif
1141                lac_call (tunl, NULL, NULL);
1142
1143                if (first_run) cnt = 0; /*Foxconn, by MJ., for leaving while*/
1144                break;
1145
1146            case 'o':          /* jz: option 'o' for doing a outgoing call */
1147
1148                switch_io = 0;  /* jz: Switch for incoming - outgoing Calls */
1149
1150                sub_str = strchr (buf, ' ') + 1;
1151
1152                tunstr = strtok (sub_str, " "); /* jz: using strtok function to get */
1153                tmp_ptr = strtok (NULL, " ");   /*     params out of the pipe       */
1154                strcpy (dial_no_tmp, tmp_ptr);
1155
1156                lac = laclist;
1157                while (lac)
1158                {
1159                    if (!strcasecmp (lac->entname, tunstr))
1160                    {
1161                        lac->active = -1;
1162                        lac->rtries = 0;
1163                        if (!lac->c)
1164                            magic_lac_dial (lac);
1165                        else
1166                            log (LOG_DEBUG,
1167                                 "%s: Session '%s' already active!\n",
1168                                 __FUNCTION__, lac->entname);
1169                        break;
1170                    }
1171                    lac = lac->next;
1172                }
1173                if (lac)
1174                    break;
1175                tunl = atoi (tunstr);
1176                if (!tunl)
1177                {
1178                    log (LOG_DEBUG, "%s: No such tunnel '%s'\n", __FUNCTION__,
1179                         tunstr);
1180                    break;
1181                }
1182#ifdef DEBUG_CONTROL
1183                log (LOG_DEBUG, "%s: Attempting to call on tunnel %d\n",
1184                     __FUNCTION__, tunl);
1185#endif
1186                lac_call (tunl, NULL, NULL);
1187                break;
1188
1189            case 'h':
1190                callstr = strchr (buf, ' ') + 1;
1191                call = atoi (callstr);
1192#ifdef DEBUG_CONTROL
1193                log (LOG_DEBUG, "%s: Attempting to call %d\n", __FUNCTION__,
1194                     call);
1195#endif
1196                lac_hangup (call);
1197                break;
1198            case 'd':
1199                tunstr = strchr (buf, ' ') + 1;
1200                lac = laclist;
1201                while (lac)
1202                {
1203                    if (!strcasecmp (lac->entname, tunstr))
1204                    {
1205                        lac->active = 0;
1206                        lac->rtries = 0;
1207                        if (lac->t)
1208                            lac_disconnect (lac->t->ourtid);
1209                        else
1210                            log (LOG_DEBUG, "%s: Session '%s' not up\n",
1211                                 __FUNCTION__, lac->entname);
1212                        break;
1213                    }
1214                    lac = lac->next;
1215                }
1216                if (lac)
1217                    break;
1218                tunl = atoi (tunstr);
1219                if (!tunl)
1220                {
1221                    log (LOG_DEBUG, "%s: No such tunnel '%s'\n", __FUNCTION__,
1222                         tunstr);
1223                    break;
1224                }
1225#ifdef DEBUG_CONTROL
1226                log (LOG_DEBUG, "%s: Attempting to disconnect tunnel %d\n",
1227                     __FUNCTION__, tunl);
1228#endif
1229                lac_disconnect (tunl);
1230                break;
1231            case 's':
1232                show_status (1);
1233                break;
1234            default:
1235                log (LOG_DEBUG, "%s: Unknown command %c\n", __FUNCTION__,
1236                     buf[0]);
1237            }
1238        }
1239    }
1240    /* Otherwise select goes nuts */
1241    close (control_fd);
1242    control_fd = open (CONTROL_PIPE, O_RDONLY | O_NONBLOCK, 0600);
1243}
1244
1245void usage(void) {
1246    printf("Usage: l2tpd -D -c [config file] -s [secret file] -p [pid file]\n");
1247    printf("\n");
1248    exit(1);
1249}
1250
1251void init_args(int argc, char *argv[]) {
1252    int i=0;
1253    gconfig.daemon=1;
1254    memset(gconfig.altauthfile,0,STRLEN);
1255    memset(gconfig.altconfigfile,0,STRLEN);
1256    memset(gconfig.authfile,0,STRLEN);
1257    memset(gconfig.configfile,0,STRLEN);
1258    memset(gconfig.pidfile,0,STRLEN);
1259    strncpy(gconfig.altauthfile,ALT_DEFAULT_AUTH_FILE,
1260            sizeof(gconfig.altauthfile) - 1);
1261    strncpy(gconfig.altconfigfile,ALT_DEFAULT_CONFIG_FILE,
1262            sizeof(gconfig.altconfigfile) - 1);
1263    strncpy(gconfig.authfile,DEFAULT_AUTH_FILE,
1264            sizeof(gconfig.authfile) - 1);
1265    strncpy(gconfig.configfile,DEFAULT_CONFIG_FILE,
1266            sizeof(gconfig.configfile) - 1);
1267    strncpy(gconfig.pidfile,DEFAULT_PID_FILE,
1268            sizeof(gconfig.pidfile) - 1);
1269    for (i = 1; i < argc; i++) {
1270        if(! strncmp(argv[i],"-c",2)) {
1271            if(++i == argc)
1272                usage();
1273            else
1274                strncpy(gconfig.configfile,argv[i],
1275                        sizeof(gconfig.configfile) - 1);
1276        }
1277        else if (! strncmp(argv[i],"-D",2)) {
1278            gconfig.daemon=0;
1279        }
1280        else if (! strncmp(argv[i],"-s",2)) {
1281            if(++i == argc)
1282                usage();
1283            else
1284                strncpy(gconfig.authfile,argv[i],
1285                        sizeof(gconfig.authfile) - 1);
1286        }
1287        else if (! strncmp(argv[i],"-p",2)) {
1288            if(++i == argc)
1289                usage();
1290            else
1291                strncpy(gconfig.pidfile,argv[i],
1292                        sizeof(gconfig.pidfile) - 1);
1293        }
1294        else {
1295            usage();
1296        }
1297    }
1298}
1299
1300
1301void daemonize() {
1302    int pid=0;
1303    int i,l;
1304    char buf[STRLEN];
1305    int pidfilewritten=0;
1306
1307    if((pid = fork()) < 0) {
1308        log(LOG_LOG, "%s: Unable to fork ()\n",__FUNCTION__);
1309        close(server_socket);
1310        exit(1);
1311    }
1312    else if (pid)
1313        exit(0);
1314
1315    /* close(0); */   /* This is a hack to "fix" problems with the
1316                         daemonization code...more work will be forthcoming
1317                         to do a proper fix for this */
1318    close(1);
1319    close(2);
1320
1321    /* Read previous pid file. */
1322    if ((i = open(gconfig.pidfile,O_RDONLY)) > 0) {
1323        l=read(i,buf,sizeof(buf)-1);
1324        if (i < 0) {
1325            log(LOG_LOG, "%s: Unable to read pid file [%s]\n",
1326                    __FUNCTION__, gconfig.pidfile);
1327        }
1328        buf[i] = '\0';
1329        pid = atoi(buf);
1330
1331        /* If the previous server process is not still running,
1332           write a new pid file immediately. */
1333        if (pid && (pid == getpid () || kill (pid, 0) < 0)) {
1334            unlink (gconfig.pidfile);
1335            if ((i = open (gconfig.pidfile, O_WRONLY | O_CREAT, 0640)) >= 0)
1336            {
1337                snprintf (buf, sizeof(buf), "%d\n", (int)getpid());
1338                write (i, buf, strlen(buf));
1339                close (i);
1340                pidfilewritten = 1;
1341            }
1342        }
1343        else
1344        {
1345            log(LOG_LOG, "%s: There's already a l2tpd server running.\n",
1346                    __FUNCTION__);
1347            close(server_socket);
1348            exit(1);
1349        }
1350    }
1351
1352    pid = setsid();
1353
1354    if(! pidfilewritten) {
1355        unlink(gconfig.pidfile);
1356        if ((i = open (gconfig.pidfile, O_WRONLY | O_CREAT, 0640)) >= 0) {
1357            snprintf (buf, strlen(buf), "%d\n", (int)getpid());
1358            write (i, buf, strlen(buf));
1359            close (i);
1360            pidfilewritten = 1;
1361        }
1362    }
1363}
1364
1365
1366
1367void init (int argc,char *argv[])
1368{
1369    struct lac *lac;
1370    init_args (argc,argv);
1371    rand_source = 0;
1372    init_addr ();
1373    if (init_config ())
1374    {
1375        log (LOG_CRIT, "%s: Unable to load config file\n", __FUNCTION__);
1376        exit (1);
1377    }
1378    if (uname (&uts))
1379    {
1380        log (LOG_CRIT, "%s : Unable to determine host system\n",
1381             __FUNCTION__);
1382        exit (1);
1383    }
1384    init_tunnel_list (&tunnels);
1385    if (init_network ())
1386        exit (1);
1387    if (gconfig.daemon)
1388	daemonize ();
1389    signal (SIGTERM, &death_handler);
1390    signal (SIGINT, &death_handler);
1391    signal (SIGCHLD, &child_handler);
1392    signal (SIGUSR1, &status_handler);
1393    signal (SIGHUP, &null_handler);
1394    init_scheduler ();
1395    mkfifo (CONTROL_PIPE, 0600);
1396    control_fd = open (CONTROL_PIPE, O_RDONLY | O_NONBLOCK, 0600);
1397    if (control_fd < 0)
1398    {
1399        log (LOG_CRIT, "%s: Unable to open " CONTROL_PIPE " for reading.",
1400             __FUNCTION__);
1401        exit (1);
1402    }
1403    log (LOG_LOG, "l2tpd version " SERVER_VERSION " started on %s PID:%d\n",
1404         hostname, getpid ());
1405    log (LOG_LOG,
1406         "Written by Mark Spencer, Copyright (C) 1998, Adtran, Inc.\n");
1407    log (LOG_LOG, "Forked by Scott Balmos and David Stipp, (C) 2001\n");
1408    log (LOG_LOG, "Inhereted by Jeff McAdams, (C) 2002\n");
1409    log (LOG_LOG, "%s version %s on a %s, port %d\n", uts.sysname,
1410         uts.release, uts.machine, gconfig.port);
1411    lac = laclist;
1412    while (lac)
1413    {
1414        if (lac->autodial)
1415        {
1416#ifdef DEBUG_MAGIC
1417            log (LOG_DEBUG, "%s: Autodialing '%s'\n", __FUNCTION__,
1418                 lac->entname[0] ? lac->entname : "(unnamed)");
1419#endif
1420            lac->active = -1;
1421            switch_io = 1;      /* If we're a LAC, autodials will be ICRQ's */
1422            magic_lac_dial (lac);
1423        }
1424        lac = lac->next;
1425    }
1426}
1427#define AUTO_CONNECT
1428int is_first_run = 0;
1429
1430int main (int argc, char *argv[])
1431{
1432    /* Foxconn added start pling 03/20/2012 */
1433    /* Add the default first */
1434    struct in_addr l2tp_serv_ip;
1435    fxc_add_gw(1, l2tp_serv_ip);
1436    /* Foxconn added end pling 03/20/2012 */
1437
1438    init(argc,argv);
1439    dial_no_tmp = calloc (128, sizeof (char));
1440    /* Foxconn, add by MJ. A global variable to mark the first execution */
1441#ifdef AUTO_CONNECT
1442    is_first_run = 1;
1443#endif
1444    network_thread ();
1445    return 0;
1446}
1447