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 * Handle a call as a separate thread
13 */
14
15#include <stdio.h>
16#include <fcntl.h>
17#include <sys/socket.h>
18#include <netinet/in.h>
19#include <arpa/inet.h>
20#include <sys/wait.h>
21#include <stdlib.h>
22#include <string.h>
23#include <unistd.h>
24#include <errno.h>
25#include <signal.h>
26#include <termios.h>
27#include "l2tp.h"
28#ifdef USE_KERNEL
29#include <sys/ioctl.h>
30#endif
31
32struct buffer *new_payload (struct sockaddr_in peer)
33{
34    struct buffer *tmp = new_buf (MAX_RECV_SIZE);
35    if (!tmp)
36        return NULL;
37    tmp->peer = peer;
38    tmp->start += sizeof (struct payload_hdr);
39    tmp->len = 0;
40    return tmp;
41}
42
43inline void recycle_payload (struct buffer *buf, struct sockaddr_in peer)
44{
45    buf->start = buf->rstart + sizeof (struct payload_hdr);
46    buf->len = 0;
47    buf->peer = peer;
48}
49
50void add_payload_hdr (struct tunnel *t, struct call *c, struct buffer *buf)
51{
52    struct payload_hdr *p;
53    buf->start -= sizeof (struct payload_hdr);
54    buf->len += sizeof (struct payload_hdr);
55    /* Account for no offset */
56    buf->start += 4;
57    buf->len -= 4;
58    if (!c->fbit && !c->ourfbit)
59    {
60        /* Forget about Ns and Nr fields then */
61        buf->start += 4;
62        buf->len -= 4;
63    }
64    if (!c->lbit)
65    {
66        /* Forget about specifying the length */
67        buf->start += 2;
68        buf->len -= 2;
69    }
70    p = (struct payload_hdr *) buf->start;
71/*	p->ver = htons(c->lbit | c->rbit | c->fbit | c->ourfbit | VER_L2TP); */
72    p->ver = htons (c->lbit | c->fbit | c->ourfbit | VER_L2TP);
73    if (c->lbit)
74    {
75        p->length = htons ((_u16) buf->len);
76    }
77    else
78    {
79        p = (struct payload_hdr *) (((char *) p) - 2);
80    }
81    p->tid = htons (t->tid);
82    p->cid = htons (c->cid);
83    if (c->fbit || c->ourfbit)
84    {
85        p->Ns = htons (c->data_seq_num);
86        p->Nr = htons (c->data_rec_seq_num);
87    }
88    c->data_seq_num++;
89/*	c->rbit=0; */
90}
91
92int read_packet (struct buffer *buf, int fd, int convert)
93{
94    unsigned char c;
95    unsigned char escape = 0;
96    unsigned char *p;
97    static unsigned char rbuf[MAX_RECV_SIZE];
98    static int pos = 0;
99    static int max = 0;
100    int res;
101    int errors = 0;
102    /* Read a packet, doing async->sync conversion if necessary */
103    p = buf->start;
104    while (1)
105    {
106        if (pos >= max)
107        {
108            /*Foxconn, by MJ., I use STDIN to replace the fd for reading.*/
109            max = read (STDIN_FILENO, rbuf, sizeof (rbuf));
110            //max = read (fd, rbuf, sizeof (rbuf));
111            //log (LOG_DEBUG, "read %d bytes from tty:%d\n", fd);
112
113            res = max;
114            pos = 0;
115        }
116        else
117        {
118            res = 1;
119        }
120        c = rbuf[pos++];
121        if (res < 1)
122        {
123            if (res == 0)
124            {
125                /*
126                   * Hmm..  Nothing to read.  It happens
127                 */
128                return 0;
129/*			} else if ((errno == EINTR ) || (errno == EAGAIN)) { */
130            }
131            else if ((errno == EIO) || (errno == EINTR) || (errno == EAGAIN))
132            {
133
134                /*
135                   * Oops, we were interrupted!
136                   * Or, we ran out of data too soon
137                   * anyway, we discared whatever it is we
138                   * have
139                 */
140                return 0;
141            }
142            errors++;
143            log (LOG_DEBUG, "%s: Error %d (%s)\n", __FUNCTION__, errno,
144                 strerror (errno));
145            if (errors > 10)
146            {
147                log (LOG_DEBUG,
148                     "%s: Too many errors.  Declaring call dead.\n",
149                     __FUNCTION__);
150                return -errno;
151            }
152            continue;
153        }
154        switch (c)
155        {
156        case PPP_FLAG:
157            if (escape)
158            {
159                log (LOG_DEBUG, "%s: got an escaped PPP_FLAG\n",
160                     __FUNCTION__);
161                return -EINVAL;
162            }
163            if (convert)
164            {
165                if (!buf->len)
166                    break;
167                /* Drop the FCS */
168                buf->len -= 2;
169            }
170            else
171            {
172                if (buf->len < buf->maxlen)
173                {
174                    *p = c;
175                    p++;
176                    buf->len++;
177                }
178            }
179            return buf->len;
180        case PPP_ESCAPE:
181            escape = PPP_TRANS;
182            if (convert)
183                break;
184        default:
185            if (convert)
186                c ^= escape;
187            escape = 0;
188            if (buf->len < buf->maxlen)
189            {
190                *p = c;
191                p++;
192                buf->len++;
193                break;
194            };
195            log (LOG_WARN, "%s: read overrun\n", __FUNCTION__);
196            return -EINVAL;
197        }
198    }
199    /* I should never get here */
200    log (LOG_WARN, "%s: You should not see this message.  If you do, please"
201		       "enter a bug report at http://sourceforge.net/projects/l2tpd", __FUNCTION__);
202    return -EINVAL;
203}
204
205void call_close (struct call *c)
206{
207    struct buffer *buf;
208    struct schedule_entry *se, *ose;
209    struct call *tmp, *tmp2;
210    if (!c || !c->container)
211    {
212        log (LOG_DEBUG, "%s: called on null call or containerless call\n",
213             __FUNCTION__);
214        return;
215    }
216    if (c == c->container->self)
217    {
218        /*
219         * We're actually closing the
220         * entire tunnel
221         */
222
223        /* First deschedule any remaining packet transmissions
224           for this tunnel.  That means Hello's and any reminaing
225           packets scheduled for transmission.  This is a very
226           nasty little piece of code here. */
227
228        se = events;
229        ose = NULL;
230        while (se)
231        {
232            if ((((struct buffer *) se->data)->tunnel == c->container)
233                || ((struct tunnel *) se->data == c->container))
234            {
235#ifdef DEBUG_CLOSE
236                log (LOG_DEBUG, "%s: Descheduling event\n", __FUNCTION__);
237#endif
238                if (ose)
239                {
240                    ose->next = se->next;
241                    if ((struct tunnel *) se->data != c->container)
242                        toss ((struct buffer *) (se->data));
243                    free (se);
244                    se = ose->next;
245                }
246                else
247                {
248                    events = se->next;
249                    if ((struct tunnel *) se->data != c->container)
250                        toss ((struct buffer *) (se->data));
251                    free (se);
252                    se = events;
253                }
254            }
255            else
256            {
257                ose = se;
258                se = se->next;
259            }
260        }
261
262        if (c->closing)
263        {
264            /* Really close this tunnel, as our
265               StopCCN has been ack'd */
266#ifdef DEBUG_CLOSE
267            log (LOG_DEBUG, "%s: Actually closing tunnel %d\n", __FUNCTION__,
268                 c->container->ourtid);
269#endif
270#ifdef USE_KERNEL
271            if (kernel_support)
272                ioctl (server_socket, L2TPIOCDELTUNNEL, c->container->ourtid);
273#endif
274            destroy_tunnel (c->container);
275            return;
276        }
277
278        /*
279           * We need to close, but need to provide reliable delivery
280           * of the final StopCCN. We record our state to know when
281           * we have actually received an ACK on our StopCCN
282         */
283        c->closeSs = c->container->control_seq_num;
284        buf = new_outgoing (c->container);
285        add_message_type_avp (buf, StopCCN);
286        if (c->container->hbit)
287        {
288            mk_challenge (c->container->chal_them.vector, VECTOR_SIZE);
289            add_randvect_avp (buf, c->container->chal_them.vector,
290                              VECTOR_SIZE);
291        }
292        add_tunnelid_avp (buf, c->container->ourtid);
293        if (c->result < 0)
294            c->result = RESULT_CLEAR;
295        if (c->error < 0)
296            c->error = 0;
297        add_result_code_avp (buf, c->result, c->error, c->errormsg,
298                             strlen (c->errormsg));
299        add_control_hdr (c->container, c, buf);
300        if (packet_dump)
301            do_packet_dump (buf);
302#ifdef DEBUG_CLOSE
303        log (LOG_DEBUG, "%s: enqueing close message for tunnel\n",
304             __FUNCTION__);
305#endif
306        control_xmit (buf);
307        /*
308           * We also need to stop all traffic on any calls contained
309           * within us.
310         */
311        tmp = c->container->call_head;
312        while (tmp)
313        {
314            tmp2 = tmp->next;
315            tmp->needclose = 0;
316            tmp->closing = -1;
317            call_close (tmp);
318            tmp = tmp2;
319        }
320        log (LOG_LOG,
321             "%s : Connection %d closed to %s, port %d (%s)\n", __FUNCTION__,
322             c->container->tid,
323             IPADDY (c->container->peer.sin_addr),
324             ntohs (c->container->peer.sin_port), c->errormsg);
325    }
326    else
327    {
328        /*
329           * Just close a call
330         */
331#ifdef USE_KERNEL
332        struct l2tp_call_opts co;
333#endif
334        if (c->zlb_xmit)
335            deschedule (c->zlb_xmit);
336/*		if (c->dethrottle) deschedule(c->dethrottle); */
337        if (c->closing)
338        {
339#ifdef DEBUG_CLOSE
340            log (LOG_DEBUG, "%s: Actually closing call %d\n", __FUNCTION__,
341                 c->ourcid);
342#endif
343            destroy_call (c);
344            return;
345        }
346#ifdef USE_KERNEL
347        if (kernel_support)
348        {
349            co.ourtid = c->container->ourtid;
350            co.ourcid = c->ourcid;
351            ioctl (server_socket, L2TPIOCGETCALLOPTS, &co);
352            co.flags = co.flags & ~L2TP_FLAG_CALL_UP;
353            ioctl (server_socket, L2TPIOCSETCALLOPTS, &co);
354        }
355#endif
356        c->closeSs = c->container->control_seq_num;
357        buf = new_outgoing (c->container);
358        add_message_type_avp (buf, CDN);
359        if (c->container->hbit)
360        {
361            mk_challenge (c->container->chal_them.vector, VECTOR_SIZE);
362            add_randvect_avp (buf, c->container->chal_them.vector,
363                              VECTOR_SIZE);
364        }
365        if (c->result < 0)
366            c->result = RESULT_CLEAR;
367        if (c->error < 0)
368            c->error = 0;
369        add_result_code_avp (buf, c->result, c->error, c->errormsg,
370                             strlen (c->errormsg));
371#ifdef TEST_HIDDEN
372        add_callid_avp (buf, c->ourcid, c->container);
373#else
374        add_callid_avp (buf, c->ourcid);
375#endif
376        add_control_hdr (c->container, c, buf);
377        if (packet_dump)
378            do_packet_dump (buf);
379#ifdef DEBUG_CLOSE
380        log (LOG_DEBUG, "%s: enqueuing close message for call %d\n",
381             __FUNCTION__, c->ourcid);
382#endif
383        control_xmit (buf);
384        log (LOG_LOG, "%s: Call %d to %s disconnected\n", __FUNCTION__,
385             c->ourcid, IPADDY (c->container->peer.sin_addr));
386    }
387    /*
388       * Note that we're in the process of closing now
389     */
390    c->closing = -1;
391}
392
393void destroy_call (struct call *c)
394{
395    /*
396     * Here, we unconditionally destroy a call.
397     */
398
399    struct call *p;
400    struct timeval tv;
401    pid_t pid;
402    /*
403     * Close the tty
404     */
405    if (c->fd > 0)
406        close (c->fd);
407/*	if (c->dethrottle) deschedule(c->dethrottle); */
408    if (c->zlb_xmit)
409        deschedule (c->zlb_xmit);
410
411#ifdef IP_ALLOCATION
412    if (c->addr)
413        unreserve_addr (c->addr);
414#endif
415
416    /*
417     * Kill off pppd and wait for it to
418     * return to us.  This should only be called
419     * in rare cases if pppd hasn't already died
420     * voluntarily
421     */
422    pid = c->pppd;
423    if (pid)
424    {
425        /* Set c->pppd to zero to prevent recursion with child_handler */
426        c->pppd = 0;
427        kill (pid, SIGTERM);
428        waitpid (pid, NULL, 0);
429    }
430    if (c->container)
431    {
432#ifdef USE_KERNEL
433        if (kernel_support)
434            ioctl (server_socket, L2TPIOCDELCALL,
435                   (c->container->ourtid << 16) | (c->ourcid));
436#endif
437        p = c->container->call_head;
438        /*
439         * Remove us from the call list, although
440         * we might not actually be there
441         */
442        if (p)
443        {
444            if (p == c)
445            {
446                c->container->call_head = c->next;
447                c->container->count--;
448            }
449            else
450            {
451                while (p->next && (p->next != c))
452                    p = p->next;
453                if (p->next)
454                {
455                    p->next = c->next;
456                    c->container->count--;
457                }
458            }
459        }
460    }
461    if (c->lac)
462    {
463        c->lac->c = NULL;
464        if (c->lac->redial && (c->lac->rtimeout > 0) && !c->lac->rsched &&
465            c->lac->active)
466        {
467#ifdef DEBUG_MAGIC
468            log (LOG_LOG, "%s: Will redial in %d seconds\n", __FUNCTION__,
469                 c->lac->rtimeout);
470#endif
471            tv.tv_sec = c->lac->rtimeout;
472            tv.tv_usec = 0;
473            c->lac->rsched = schedule (tv, magic_lac_dial, c->lac);
474        }
475    }
476
477    free (c);
478
479}
480
481
482struct call *new_call (struct tunnel *parent)
483{
484    char entropy_buf[2] = "\0";
485    struct call *tmp = malloc (sizeof (struct call));
486    if (!tmp)
487        return NULL;
488    tmp->tx_pkts = 0;
489    tmp->rx_pkts = 0;
490    tmp->tx_bytes = 0;
491    tmp->rx_bytes = 0;
492    tmp->zlb_xmit = NULL;
493/*	tmp->throttle = 0; */
494/*	tmp->dethrottle=NULL; */
495    tmp->prx = 0;
496/*	tmp->rbit = 0; */
497    tmp->msgtype = 0;
498/*	tmp->timeout = 0; */
499    tmp->data_seq_num = 0;
500    tmp->data_rec_seq_num = 0;
501    tmp->pLr = -1;
502    tmp->nego = 0;
503    tmp->debug = 0;
504    tmp->seq_reqd = 0;
505    tmp->state = 0;             /* Nothing so far */
506    if (parent->self)
507    {
508#ifndef TESTING
509#ifdef USE_KERNEL
510        if (kernel_support)
511            tmp->ourcid =
512                ioctl (server_socket, L2TPIOCADDCALL, parent->ourtid << 16);
513        else
514#endif
515/*	while(get_call(parent->ourtid, (tmp->ourcid = (rand() && 0xFFFF)),0,0)); */
516            /* FIXME: What about possibility of multiple random #'s??? */
517            /* tmp->ourcid = (rand () & 0xFFFF); */
518            get_entropy(entropy_buf, 2);
519        {
520            int *temp;
521            temp = (int *)entropy_buf;
522            tmp->ourcid = *temp & 0xFFFF;
523#ifdef DEBUG_ENTROPY
524            log(LOG_DEBUG, "ourcid = %u, entropy_buf = %hx\n", tmp->ourcid, *temp);
525#endif
526        }
527#else
528        tmp->ourcid = 0x6227;
529#endif
530    }
531    tmp->dialed[0] = 0;
532    tmp->dialing[0] = 0;
533    tmp->subaddy[0] = 0;
534    tmp->physchan = -1;
535    tmp->serno = 0;
536    tmp->bearer = -1;
537    tmp->cid = -1;
538    tmp->qcid = -1;
539    tmp->container = parent;
540/*	tmp->rws = -1; */
541    tmp->fd = -1;
542    tmp->oldptyconf = malloc (sizeof (struct termios));
543    tmp->pnu = 0;
544    tmp->cnu = 0;
545    tmp->needclose = 0;
546    tmp->closing = 0;
547    tmp->die = 0;
548    tmp->pppd = 0;
549    tmp->error = -1;
550    tmp->result = -1;
551    tmp->errormsg[0] = 0;
552    tmp->fbit = 0;
553    tmp->cid = 0;
554    tmp->lbit = 0;
555    /* Inherit LAC and LNS from parent */
556    tmp->lns = parent->lns;
557    tmp->lac = parent->lac;
558    tmp->addr = 0;
559/*	tmp->ourrws = DEFAULT_RWS_SIZE;	 */
560/*	if (tmp->ourrws >= 0)
561		tmp->ourfbit = FBIT;
562	else */
563    tmp->ourfbit = 0;           /* initialize to 0 since we don't actually use this
564                                   value at this point anywhere in the code (I don't
565                                   think)  We might just be able to remove it completely */
566    tmp->dial_no[0] = '\0';     /* jz: dialing number for outgoing call */
567    return tmp;
568}
569
570struct call *get_tunnel (int tunnel, unsigned int addr, int port)
571{
572    struct tunnel *st;
573    if (tunnel)
574    {
575        st = tunnels.head;
576        while (st)
577        {
578            if (st->ourtid == tunnel)
579            {
580                return st->self;
581            }
582            st = st->next;
583        }
584    }
585    return NULL;
586}
587struct call *get_call (int tunnel, int call, unsigned int addr, int port)
588{
589    /*
590     * Figure out which call struct should handle this.
591     * If we have tunnel and call ID's then they are unique.
592     * Otherwise, if the tunnel is 0, look for an existing connection
593     * or create a new tunnel.
594     */
595    struct tunnel *st;
596    struct call *sc;
597    if (tunnel)
598    {
599        st = tunnels.head;
600        while (st)
601        {
602            if (st->ourtid == tunnel)
603            {
604                if (call)
605                {
606                    sc = st->call_head;
607                    while (sc)
608                    {
609                        if (sc->ourcid == call)
610                            return sc;
611                        sc = sc->next;
612                    }
613                    log (LOG_DEBUG, "%s: can't find call %d in tunnel %d\n",
614                         __FUNCTION__, call, tunnel);
615                    return NULL;
616                }
617                else
618                {
619                    return st->self;
620                }
621            }
622            st = st->next;
623        }
624        log (LOG_DEBUG, "%s:can't find tunnel %d\n", __FUNCTION__, tunnel);
625        return NULL;
626    }
627    else
628    {
629#ifdef USE_KERNEL
630        struct l2tp_tunnel_opts to;
631#endif
632        /* You can't specify a call number if you haven't specified
633           a tunnel silly! */
634
635        if (call)
636        {
637            log (LOG_WARN,
638                 "%s: call ID specified, but no tunnel ID specified.  tossing.\n",
639                 __FUNCTION__);
640            return NULL;
641        }
642        /*
643         * Well, nothing appropriate...  Let's add a new tunnel, if
644         * we are not at capacity.
645         */
646        if (debug_tunnel)
647        {
648            log (LOG_DEBUG,
649                 "%s: allocating new tunnel for host %s, port %d.\n",
650                 __FUNCTION__, IPADDY (addr), ntohs (port));
651        }
652        if (!(st = new_tunnel ()))
653        {
654            log (LOG_WARN,
655                 "%s: unable to allocate new tunnel for host %s, port %d.\n",
656                 __FUNCTION__, IPADDY (addr), ntohs (port));
657            return NULL;
658        };
659        st->peer.sin_family = AF_INET;
660        st->peer.sin_port = port;
661        bcopy (&addr, &st->peer.sin_addr, sizeof (addr));
662#ifdef USE_KERNEL
663        if (kernel_support)
664        {
665            /* Update kernel as to peer's location */
666            to.ourtid = st->ourtid;
667            ioctl (server_socket, L2TPIOCGETTUNOPTS, &to);
668            bcopy (&st->peer, &to.peer, sizeof (st->peer));
669            to.addrlen = sizeof (st->peer);
670            ioctl (server_socket, L2TPIOCSETTUNOPTS, &to);
671        }
672#endif
673        /* foxconn wklin added start, 08/04/2010 @l2tp throughput */
674        /* this is to make "connected == 1" in usb_sendmsg(), so the dst entry can
675        * be cached in struct sock.
676        */
677        if (connect (server_socket, (struct sockaddr *)&st->peer, sizeof (st->peer))) {
678            log (LOG_WARN,
679                 "%s: unable to connect to host %s, port %d.\n",
680                 __FUNCTION__, IPADDY (addr), ntohs (port));
681        }
682        /* foxconn wklin added end, 08/04/2010 */
683        st->next = tunnels.head;
684        tunnels.head = st;
685        tunnels.count++;
686        return st->self;
687    }
688}
689