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            sprintf(command, "route add default gw %s", getGateway) ;
654            system(command);
655#ifdef DEBUG_SERV_IP_ROUTING
656            printf("%s: %s\n", __FUNCTION__, command);
657#endif
658        }
659        else if ( act == 2 )  /* remove default gateway and add host route */
660        {
661            unsigned int i_wanip, i_netmask;
662            system(del_host_cmd); /* remove last host route here */
663            system("route del default");
664#ifdef DEBUG_SERV_IP_ROUTING
665            printf("%s\n", del_host_cmd);
666            printf("route del default\n");
667#endif
668            if ((strcmp (getUserIp,"0.0.0.0") != 0) && (strcmp (getNetmask,"0.0.0.0") != 0))
669            {
670                i_wanip = inet_addr(getUserIp);
671                i_netmask = inet_addr(getNetmask);
672
673                if((i_wanip & i_netmask) != (inetaddr.s_addr & i_netmask))
674                {
675                    /* Foxconn added start pling 03/30/2012 */
676                    /* Change the way to add default gateway, in case the gateway is
677                    * in different subnet from the WAN IP. */
678                    sprintf(command, "route add -host %s dev %s", getGateway, wan_ifname);
679                    system(command);
680                    /* Foxconn added end pling 03/30/2012 */
681
682                    sprintf(command, "route add -host %s gw %s",
683                            inet_ntoa(inetaddr), getGateway);
684                    system(command);
685#ifdef DEBUG_SERV_IP_ROUTING
686                    printf("%s: %s\n", __FUNCTION__, command);
687#endif
688                }
689            }
690
691        }
692    }
693}
694#else
695void fxc_add_gw(int act, struct in_addr inetaddr) /*1: add, 2: del*/
696{
697    //struct sockaddr_pptpox sp_info; /*commented by MJ.*/
698    FILE *fp = NULL;
699    unsigned char buf[128];
700    unsigned char gateWay[IPV4_LEN];
701    unsigned char addrname[12];
702    unsigned int getIp[IPV4_LEN];
703    char gate_way[] = "gateway_addr";
704    char command[64];
705
706    del_host_cmd[0] = '\0';
707
708    if ((fp = fopen("/tmp/ppp/dhcpIp", "r")) != NULL)
709    {
710        /* commented by MJ.
711        // I can't find a place to use these variables.
712        memset(&sp_info, 0, sizeof(struct sockaddr_pptpox));
713
714        sp_info.sa_family = AF_PPPOX;
715        sp_info.sa_protocol = PX_PROTO_TP;
716        */
717        memset(gateWay, 0, IPV4_LEN);
718
719        while (fgets(buf, sizeof(buf), fp))
720        {
721            sscanf(buf, "%s %d.%d.%d.%d", &addrname[0],
722                &getIp[0], &getIp[1], &getIp[2], &getIp[3]);
723
724            if (memcmp(addrname, gate_way, sizeof(gate_way)) == 0)
725            {
726                if ( act == 1 )
727                {
728                    sprintf(command, "route add default gw %d.%d.%d.%d",
729                            getIp[0], getIp[1], getIp[2], getIp[3]);
730                    system(command);
731                }
732                else if ( act == 2 )  /* remove default gateway and add host route */
733                {
734                    system(del_host_cmd); /* remove last host route here */
735                    system("route del default");
736                    sprintf(command, "route add -host %s gw %d.%d.%d.%d",
737                    inet_ntoa(inetaddr), getIp[0], getIp[1], getIp[2], getIp[3]);
738                    system(command);
739
740                    sprintf(del_host_cmd, "route del %s gw %d.%d.%d.%d",
741                            inet_ntoa(inetaddr), getIp[0], getIp[1], getIp[2], getIp[3]);
742                }
743
744                fclose(fp);
745                return;
746            }
747        }
748        fclose(fp);
749    }
750}
751#endif
752
753/* Foxconn, add end by MJ., 01/29/2010*/
754
755struct tunnel *l2tp_call (char *host, int port, struct lac *lac,
756                          struct lns *lns)
757{
758    /*
759     * Establish a tunnel from us to host
760     * on port port
761     */
762    struct call *tmp = NULL;
763    struct hostent *hp;
764    unsigned int addr;
765    FILE *fp;
766    port = htons (port);
767
768    /* Foxconn, added by MJ. 01/29/2010 */
769    struct in_addr l2tp_serv_ip;
770
771    /* add routing for DNS server 01/29/2010*/
772    fxc_add_gw(1, l2tp_serv_ip);
773    /* Foxconn, added end.*/
774
775    hp = gethostbyname (host);
776
777    if (!hp)
778    {
779        log (LOG_WARN, "%s: gethostbyname() failed for %s.\n", __FUNCTION__,
780             host);
781        return NULL;
782    }
783    bcopy (hp->h_addr, &addr, hp->h_length);
784
785    /* Foxconn, add start by MJ., for l2tp. 01/28/2010 */
786
787    if (hp->h_addrtype == AF_INET){
788        memcpy(&l2tp_serv_ip.s_addr, hp->h_addr, sizeof(l2tp_serv_ip.s_addr));
789        if ( fp = fopen("/tmp/ppp/l2tpSrvIp", "w") )
790        {
791            fprintf(fp, "%s", inet_ntoa(l2tp_serv_ip));
792            fclose(fp);
793        }
794    }
795
796    /* Add routing for L2TP server */
797    fxc_add_gw(2, l2tp_serv_ip);
798    /* Foxconn, add end, by MJ., for l2tp. 01/28/2010 */
799
800
801    /* Force creation of a new tunnel
802       and set it's tid to 0 to cause
803       negotiation to occur */
804    /* XXX L2TP/IPSec: Set up SA to addr:port here?  NTB 20011010
805     */
806    tmp = get_call (0, 0, addr, port);
807    if (!tmp)
808    {
809        log (LOG_WARN, "%s: Unable to create tunnel to %s.\n", __FUNCTION__,
810             host);
811        return NULL;
812    }
813    tmp->container->tid = 0;
814    tmp->container->lac = lac;
815    tmp->container->lns = lns;
816    tmp->lac = lac;
817    tmp->lns = lns;
818    if (lac)
819        lac->t = tmp->container;
820    if (lns)
821        lns->t = tmp->container;
822    /*
823     * Since our state is 0, we will establish a tunnel now
824     */
825    log (LOG_LOG, "%s:Connecting to host %s, port %d\n", __FUNCTION__, host,
826         ntohs (port));
827    control_finish (tmp->container, tmp);
828    return tmp->container;
829}
830
831void magic_lac_tunnel (void *data)
832{
833    struct lac *lac;
834    lac = (struct lac *) data;
835    if (!lac)
836    {
837        log (LOG_WARN, "%s: magic_lac_tunnel: called on NULL lac!\n",
838             __FUNCTION__);
839        return;
840    }
841    if (lac->lns)
842    {
843        /* FIXME: I should try different LNS's if I get failures */
844        l2tp_call (lac->lns->hostname, lac->lns->port, lac, NULL);
845        return;
846    }
847    else if (deflac && deflac->lns)
848    {
849        l2tp_call (deflac->lns->hostname, deflac->lns->port, lac, NULL);
850        return;
851    }
852    else
853    {
854        log (LOG_WARN, "%s: Unable to find hostname to dial for '%s'\n",
855             __FUNCTION__, lac->entname);
856        return;
857    }
858}
859
860struct call *lac_call (int tid, struct lac *lac, struct lns *lns)
861{
862    struct tunnel *t = tunnels.head;
863    struct call *tmp;
864    while (t)
865    {
866        if (t->ourtid == tid)
867        {
868            tmp = new_call (t);
869            if (!tmp)
870            {
871                log (LOG_WARN, "%s: unable to create new call\n",
872                     __FUNCTION__);
873                return NULL;
874            }
875            tmp->next = t->call_head;
876            t->call_head = tmp;
877            t->count++;
878            tmp->cid = 0;
879            tmp->lac = lac;
880            tmp->lns = lns;
881            if (lac)
882                lac->c = tmp;
883            log (LOG_LOG, "%s: Calling on tunnel %d\n", __FUNCTION__, tid);
884            strcpy (tmp->dial_no, dial_no_tmp); /*  jz: copy dialnumber to tmp->dial_no  */
885            control_finish (t, tmp);
886            return tmp;
887        }
888        t = t->next;
889    };
890    log (LOG_DEBUG, "%s: No such tunnel %d to generate call.\n", __FUNCTION__,
891         tid);
892    return NULL;
893}
894
895void magic_lac_dial (void *data)
896{
897    struct lac *lac;
898    lac = (struct lac *) data;
899    if (!lac->active)
900    {
901        log (LOG_DEBUG, "%s: LAC %s not active", __FUNCTION__, lac->entname);
902        return;
903    }
904    lac->rsched = NULL;
905    lac->rtries++;
906    if (lac->rmax && (lac->rtries > lac->rmax))
907    {
908        log (LOG_LOG, "%s: maximum retries exceeded.\n", __FUNCTION__);
909        return;
910    }
911    if (!lac)
912    {
913        log (LOG_WARN, "%s : called on NULL lac!\n", __FUNCTION__);
914        return;
915    }
916    if (!lac->t)
917    {
918#ifdef DEGUG_MAGIC
919        log (LOG_DEBUG, "%s : tunnel not up!  Connecting!\n", __FUNCTION__);
920#endif
921        magic_lac_tunnel (lac);
922        return;
923    }
924    lac_call (lac->t->ourtid, lac, NULL);
925}
926
927void lac_hangup (int cid)
928{
929    struct tunnel *t = tunnels.head;
930    struct call *tmp;
931    while (t)
932    {
933        tmp = t->call_head;
934        while (tmp)
935        {
936            if (tmp->ourcid == cid)
937            {
938                log (LOG_LOG,
939                     "%s :Hanging up call %d, Local: %d, Remote: %d\n",
940                     __FUNCTION__, tmp->serno, tmp->ourcid, tmp->cid);
941                strcpy (tmp->errormsg, "Goodbye!");
942/*				tmp->needclose = -1; */
943                kill (tmp->pppd, SIGTERM);
944                return;
945            }
946            tmp = tmp->next;
947        }
948        t = t->next;
949    };
950    log (LOG_DEBUG, "%s : No such call %d to hang up.\n", __FUNCTION__, cid);
951    return;
952}
953
954void lac_disconnect (int tid)
955{
956    struct tunnel *t = tunnels.head;
957    while (t)
958    {
959        if (t->ourtid == tid)
960        {
961            log (LOG_LOG,
962                 "%s: Disconnecting from %s, Local: %d, Remote: %d\n",
963                 __FUNCTION__, IPADDY (t->peer.sin_addr), t->ourtid, t->tid);
964            t->self->needclose = -1;
965            strcpy (t->self->errormsg, "Goodbye!");
966            call_close (t->self);
967            return;
968        }
969        t = t->next;
970    };
971    log (LOG_DEBUG, "%s: No such tunnel %d to hang up.\n", __FUNCTION__, tid);
972    return;
973}
974
975struct tunnel *new_tunnel ()
976{
977    struct tunnel *tmp = malloc (sizeof (struct tunnel));
978    char entropy_buf[2] = "\0";
979    if (!tmp)
980        return NULL;
981    tmp->control_seq_num = 0;
982    tmp->control_rec_seq_num = 0;
983    tmp->cLr = 0;
984    tmp->call_head = NULL;
985    tmp->next = NULL;
986    tmp->debug = -1;
987    tmp->tid = -1;
988    tmp->hello = NULL;
989#ifndef TESTING
990/*	while(get_call((tmp->ourtid = rand() & 0xFFFF),0,0,0)); */
991#ifdef USE_KERNEL
992    if (kernel_support)
993        tmp->ourtid = ioctl (server_socket, L2TPIOCADDTUNNEL, 0);
994    else
995#endif
996/*        tmp->ourtid = rand () & 0xFFFF; */
997        /* get_entropy((char *)&tmp->ourtid, 2); */
998        get_entropy(entropy_buf, 2);
999        {
1000            int *temp;
1001            temp = (int *)entropy_buf;
1002            tmp->ourtid = *temp & 0xFFFF;
1003#ifdef DEBUG_ENTROPY
1004            log(LOG_DEBUG, "ourtid = %u, entropy_buf = %hx\n", tmp->ourtid, *temp);
1005#endif
1006        }
1007#else
1008    tmp->ourtid = 0x6227;
1009#endif
1010    tmp->nego = 0;
1011    tmp->count = 0;
1012    tmp->state = 0;             /* Nothing */
1013    tmp->peer.sin_family = AF_INET;
1014    tmp->peer.sin_port = 0;
1015    bzero (&(tmp->peer.sin_addr), sizeof (tmp->peer.sin_addr));
1016    tmp->sanity = -1;
1017    tmp->qtid = -1;
1018    tmp->ourfc = ASYNC_FRAMING | SYNC_FRAMING;
1019    tmp->ourbc = 0;
1020    tmp->ourtb = (((_u64) rand ()) << 32) | ((_u64) rand ());
1021    tmp->fc = -1;               /* These really need to be specified by the peer */
1022    tmp->bc = -1;               /* And we want to know if they forgot */
1023    tmp->hostname[0] = 0;
1024    tmp->vendor[0] = 0;
1025    tmp->secret[0] = 0;
1026    if (!(tmp->self = new_call (tmp)))
1027    {
1028        free (tmp);
1029        return NULL;
1030    };
1031    tmp->ourrws = DEFAULT_RWS_SIZE;
1032    tmp->self->ourfbit = FBIT;
1033    tmp->lac = NULL;
1034    tmp->lns = NULL;
1035    tmp->chal_us.state = 0;
1036    tmp->chal_us.secret[0] = 0;
1037    memset (tmp->chal_us.reply, 0, MD_SIG_SIZE);
1038    tmp->chal_them.state = 0;
1039    tmp->chal_them.secret[0] = 0;
1040    memset (tmp->chal_them.reply, 0, MD_SIG_SIZE);
1041    tmp->chal_them.vector = (unsigned char *) malloc (VECTOR_SIZE);
1042    tmp->chal_us.vector = NULL;
1043    tmp->hbit = 0;
1044    return tmp;
1045}
1046
1047void do_control (char *cmd)
1048{
1049    char buf[1024];
1050    char *host;
1051    char *tunstr;
1052    char *callstr;
1053
1054    char *sub_str;              /* jz: use by the strtok function */
1055    char *tmp_ptr;              /* jz: use by the strtok function */
1056    struct lac *lac;
1057    int call;
1058    int tunl;
1059    int cnt = -1;
1060    int first_run = 0;
1061
1062
1063    while (cnt)
1064    {
1065        /* Foxconn, add by MJ. for building L2TP tunnel in the begining. */
1066        if(cmd != NULL)
1067        {
1068            first_run = 1;
1069            strcpy(buf, cmd);
1070            cnt = strlen(buf);
1071            log (LOG_DEBUG, "%s -> L2TP connect immediately. \n", __FUNCTION__);
1072        }
1073        else
1074            cnt = read (control_fd, buf, sizeof (buf));
1075        /*add end, by MJ.*/
1076        if (cnt > 0)
1077        {
1078            if (buf[cnt - 1] == '\n')
1079                buf[--cnt] = 0;
1080#ifdef DEBUG_CONTROL
1081            log (LOG_DEBUG, "%s: Got message %s (%d bytes long)\n",
1082                 __FUNCTION__, buf, cnt);
1083#endif
1084            switch (buf[0])
1085            {
1086            case 't':
1087                host = strchr (buf, ' ') + 1;
1088#ifdef DEBUG_CONTROL
1089                log (LOG_DEBUG, "%s: Attempting to tunnel to %s\n",
1090                     __FUNCTION__, host);
1091#endif
1092                l2tp_call (host, UDP_LISTEN_PORT, NULL, NULL);
1093                break;
1094            case 'c':
1095
1096                switch_io = 1;  /* jz: Switch for Incoming - Outgoing Calls */
1097
1098                tunstr = strchr (buf, ' ') + 1;
1099                lac = laclist;
1100                while (lac)
1101                {
1102                    if (!strcasecmp (lac->entname, tunstr))
1103                    {
1104                        lac->active = -1;
1105                        lac->rtries = 0;
1106                        if (!lac->c)
1107                            magic_lac_dial (lac);
1108                        else
1109                            log (LOG_DEBUG,
1110                                 "%s: Session '%s' already active!\n",
1111                                 __FUNCTION__, lac->entname);
1112                        break;
1113                    }
1114                    lac = lac->next;
1115                }
1116                if (lac){
1117                    if (first_run) cnt = 0; /*Foxconn, by MJ., for leaving while*/
1118                    break;
1119                }
1120                tunl = atoi (tunstr);
1121                if (!tunl)
1122                {
1123                    log (LOG_DEBUG, "%s: No such tunnel '%s'\n", __FUNCTION__,
1124                         tunstr);
1125                    if (first_run) cnt = 0; /*Foxconn, by MJ., for leaving while*/
1126                    break;
1127                }
1128#ifdef DEBUG_CONTROL
1129                log (LOG_DEBUG, "%s: Attempting to call on tunnel %d\n",
1130                     __FUNCTION__, tunl);
1131#endif
1132                lac_call (tunl, NULL, NULL);
1133
1134                if (first_run) cnt = 0; /*Foxconn, by MJ., for leaving while*/
1135                break;
1136
1137            case 'o':          /* jz: option 'o' for doing a outgoing call */
1138
1139                switch_io = 0;  /* jz: Switch for incoming - outgoing Calls */
1140
1141                sub_str = strchr (buf, ' ') + 1;
1142
1143                tunstr = strtok (sub_str, " "); /* jz: using strtok function to get */
1144                tmp_ptr = strtok (NULL, " ");   /*     params out of the pipe       */
1145                strcpy (dial_no_tmp, tmp_ptr);
1146
1147                lac = laclist;
1148                while (lac)
1149                {
1150                    if (!strcasecmp (lac->entname, tunstr))
1151                    {
1152                        lac->active = -1;
1153                        lac->rtries = 0;
1154                        if (!lac->c)
1155                            magic_lac_dial (lac);
1156                        else
1157                            log (LOG_DEBUG,
1158                                 "%s: Session '%s' already active!\n",
1159                                 __FUNCTION__, lac->entname);
1160                        break;
1161                    }
1162                    lac = lac->next;
1163                }
1164                if (lac)
1165                    break;
1166                tunl = atoi (tunstr);
1167                if (!tunl)
1168                {
1169                    log (LOG_DEBUG, "%s: No such tunnel '%s'\n", __FUNCTION__,
1170                         tunstr);
1171                    break;
1172                }
1173#ifdef DEBUG_CONTROL
1174                log (LOG_DEBUG, "%s: Attempting to call on tunnel %d\n",
1175                     __FUNCTION__, tunl);
1176#endif
1177                lac_call (tunl, NULL, NULL);
1178                break;
1179
1180            case 'h':
1181                callstr = strchr (buf, ' ') + 1;
1182                call = atoi (callstr);
1183#ifdef DEBUG_CONTROL
1184                log (LOG_DEBUG, "%s: Attempting to call %d\n", __FUNCTION__,
1185                     call);
1186#endif
1187                lac_hangup (call);
1188                break;
1189            case 'd':
1190                tunstr = strchr (buf, ' ') + 1;
1191                lac = laclist;
1192                while (lac)
1193                {
1194                    if (!strcasecmp (lac->entname, tunstr))
1195                    {
1196                        lac->active = 0;
1197                        lac->rtries = 0;
1198                        if (lac->t)
1199                            lac_disconnect (lac->t->ourtid);
1200                        else
1201                            log (LOG_DEBUG, "%s: Session '%s' not up\n",
1202                                 __FUNCTION__, lac->entname);
1203                        break;
1204                    }
1205                    lac = lac->next;
1206                }
1207                if (lac)
1208                    break;
1209                tunl = atoi (tunstr);
1210                if (!tunl)
1211                {
1212                    log (LOG_DEBUG, "%s: No such tunnel '%s'\n", __FUNCTION__,
1213                         tunstr);
1214                    break;
1215                }
1216#ifdef DEBUG_CONTROL
1217                log (LOG_DEBUG, "%s: Attempting to disconnect tunnel %d\n",
1218                     __FUNCTION__, tunl);
1219#endif
1220                lac_disconnect (tunl);
1221                break;
1222            case 's':
1223                show_status (1);
1224                break;
1225            default:
1226                log (LOG_DEBUG, "%s: Unknown command %c\n", __FUNCTION__,
1227                     buf[0]);
1228            }
1229        }
1230    }
1231    /* Otherwise select goes nuts */
1232    close (control_fd);
1233    control_fd = open (CONTROL_PIPE, O_RDONLY | O_NONBLOCK, 0600);
1234}
1235
1236void usage(void) {
1237    printf("Usage: l2tpd -D -c [config file] -s [secret file] -p [pid file]\n");
1238    printf("\n");
1239    exit(1);
1240}
1241
1242void init_args(int argc, char *argv[]) {
1243    int i=0;
1244    gconfig.daemon=1;
1245    memset(gconfig.altauthfile,0,STRLEN);
1246    memset(gconfig.altconfigfile,0,STRLEN);
1247    memset(gconfig.authfile,0,STRLEN);
1248    memset(gconfig.configfile,0,STRLEN);
1249    memset(gconfig.pidfile,0,STRLEN);
1250    strncpy(gconfig.altauthfile,ALT_DEFAULT_AUTH_FILE,
1251            sizeof(gconfig.altauthfile) - 1);
1252    strncpy(gconfig.altconfigfile,ALT_DEFAULT_CONFIG_FILE,
1253            sizeof(gconfig.altconfigfile) - 1);
1254    strncpy(gconfig.authfile,DEFAULT_AUTH_FILE,
1255            sizeof(gconfig.authfile) - 1);
1256    strncpy(gconfig.configfile,DEFAULT_CONFIG_FILE,
1257            sizeof(gconfig.configfile) - 1);
1258    strncpy(gconfig.pidfile,DEFAULT_PID_FILE,
1259            sizeof(gconfig.pidfile) - 1);
1260    for (i = 1; i < argc; i++) {
1261        if(! strncmp(argv[i],"-c",2)) {
1262            if(++i == argc)
1263                usage();
1264            else
1265                strncpy(gconfig.configfile,argv[i],
1266                        sizeof(gconfig.configfile) - 1);
1267        }
1268        else if (! strncmp(argv[i],"-D",2)) {
1269            gconfig.daemon=0;
1270        }
1271        else if (! strncmp(argv[i],"-s",2)) {
1272            if(++i == argc)
1273                usage();
1274            else
1275                strncpy(gconfig.authfile,argv[i],
1276                        sizeof(gconfig.authfile) - 1);
1277        }
1278        else if (! strncmp(argv[i],"-p",2)) {
1279            if(++i == argc)
1280                usage();
1281            else
1282                strncpy(gconfig.pidfile,argv[i],
1283                        sizeof(gconfig.pidfile) - 1);
1284        }
1285        else {
1286            usage();
1287        }
1288    }
1289}
1290
1291
1292void daemonize() {
1293    int pid=0;
1294    int i,l;
1295    char buf[STRLEN];
1296    int pidfilewritten=0;
1297
1298    if((pid = fork()) < 0) {
1299        log(LOG_LOG, "%s: Unable to fork ()\n",__FUNCTION__);
1300        close(server_socket);
1301        exit(1);
1302    }
1303    else if (pid)
1304        exit(0);
1305
1306    /* close(0); */   /* This is a hack to "fix" problems with the
1307                         daemonization code...more work will be forthcoming
1308                         to do a proper fix for this */
1309    close(1);
1310    close(2);
1311
1312    /* Read previous pid file. */
1313    if ((i = open(gconfig.pidfile,O_RDONLY)) > 0) {
1314        l=read(i,buf,sizeof(buf)-1);
1315        if (i < 0) {
1316            log(LOG_LOG, "%s: Unable to read pid file [%s]\n",
1317                    __FUNCTION__, gconfig.pidfile);
1318        }
1319        buf[i] = '\0';
1320        pid = atoi(buf);
1321
1322        /* If the previous server process is not still running,
1323           write a new pid file immediately. */
1324        if (pid && (pid == getpid () || kill (pid, 0) < 0)) {
1325            unlink (gconfig.pidfile);
1326            if ((i = open (gconfig.pidfile, O_WRONLY | O_CREAT, 0640)) >= 0)
1327            {
1328                snprintf (buf, sizeof(buf), "%d\n", (int)getpid());
1329                write (i, buf, strlen(buf));
1330                close (i);
1331                pidfilewritten = 1;
1332            }
1333        }
1334        else
1335        {
1336            log(LOG_LOG, "%s: There's already a l2tpd server running.\n",
1337                    __FUNCTION__);
1338            close(server_socket);
1339            exit(1);
1340        }
1341    }
1342
1343    pid = setsid();
1344
1345    if(! pidfilewritten) {
1346        unlink(gconfig.pidfile);
1347        if ((i = open (gconfig.pidfile, O_WRONLY | O_CREAT, 0640)) >= 0) {
1348            snprintf (buf, strlen(buf), "%d\n", (int)getpid());
1349            write (i, buf, strlen(buf));
1350            close (i);
1351            pidfilewritten = 1;
1352        }
1353    }
1354}
1355
1356
1357
1358void init (int argc,char *argv[])
1359{
1360    struct lac *lac;
1361    init_args (argc,argv);
1362    rand_source = 0;
1363    init_addr ();
1364    if (init_config ())
1365    {
1366        log (LOG_CRIT, "%s: Unable to load config file\n", __FUNCTION__);
1367        exit (1);
1368    }
1369    if (uname (&uts))
1370    {
1371        log (LOG_CRIT, "%s : Unable to determine host system\n",
1372             __FUNCTION__);
1373        exit (1);
1374    }
1375    init_tunnel_list (&tunnels);
1376    if (init_network ())
1377        exit (1);
1378    if (gconfig.daemon)
1379	daemonize ();
1380    signal (SIGTERM, &death_handler);
1381    signal (SIGINT, &death_handler);
1382    signal (SIGCHLD, &child_handler);
1383    signal (SIGUSR1, &status_handler);
1384    signal (SIGHUP, &null_handler);
1385    init_scheduler ();
1386    mkfifo (CONTROL_PIPE, 0600);
1387    control_fd = open (CONTROL_PIPE, O_RDONLY | O_NONBLOCK, 0600);
1388    if (control_fd < 0)
1389    {
1390        log (LOG_CRIT, "%s: Unable to open " CONTROL_PIPE " for reading.",
1391             __FUNCTION__);
1392        exit (1);
1393    }
1394    log (LOG_LOG, "l2tpd version " SERVER_VERSION " started on %s PID:%d\n",
1395         hostname, getpid ());
1396    log (LOG_LOG,
1397         "Written by Mark Spencer, Copyright (C) 1998, Adtran, Inc.\n");
1398    log (LOG_LOG, "Forked by Scott Balmos and David Stipp, (C) 2001\n");
1399    log (LOG_LOG, "Inhereted by Jeff McAdams, (C) 2002\n");
1400    log (LOG_LOG, "%s version %s on a %s, port %d\n", uts.sysname,
1401         uts.release, uts.machine, gconfig.port);
1402    lac = laclist;
1403    while (lac)
1404    {
1405        if (lac->autodial)
1406        {
1407#ifdef DEBUG_MAGIC
1408            log (LOG_DEBUG, "%s: Autodialing '%s'\n", __FUNCTION__,
1409                 lac->entname[0] ? lac->entname : "(unnamed)");
1410#endif
1411            lac->active = -1;
1412            switch_io = 1;      /* If we're a LAC, autodials will be ICRQ's */
1413            magic_lac_dial (lac);
1414        }
1415        lac = lac->next;
1416    }
1417}
1418#define AUTO_CONNECT
1419int is_first_run = 0;
1420
1421int main (int argc, char *argv[])
1422{
1423    /* Foxconn added start pling 03/20/2012 */
1424    /* Add the default first */
1425    struct in_addr l2tp_serv_ip;
1426    fxc_add_gw(1, l2tp_serv_ip);
1427    /* Foxconn added end pling 03/20/2012 */
1428
1429    init(argc,argv);
1430    dial_no_tmp = calloc (128, sizeof (char));
1431    /* Foxconn, add by MJ. A global variable to mark the first execution */
1432#ifdef AUTO_CONNECT
1433    is_first_run = 1;
1434#endif
1435    network_thread ();
1436    return 0;
1437}
1438