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 * Control Packet Handling
13 *
14 */
15
16#include <errno.h>
17#include <string.h>
18#include <stdio.h>
19#include <netinet/in.h>
20#include <arpa/inet.h>
21#include <unistd.h>
22#include <stdlib.h>
23#include "l2tp.h"
24#include <signal.h>
25#ifdef USE_KERNEL
26#include <sys/ioctl.h>
27#endif
28
29#ifdef PPPOX_L2TP
30//#include <linux/ppp_defs.h>
31#include "pppol2tp.h"
32//#include <linux/if_ether.h>    // For ETH_ALEN
33//#include <net/if.h>    //IFNAMSIZ
34
35//#include <linux/if_ppp.h>
36//#include <linux/if_pppol2tp.h>
37//#include <linux/if_pppox.h>
38//#include <linux/if_ppp.h>
39//#include <net/if.h>    //IFNAMSIZ
40//#include <linux/if_ether.h>    // For ETH_ALEN
41#include <linux/types.h>
42#include <linux/ppp_defs.h>
43#include <fcntl.h>
44#include <sys/file.h>
45#include <sys/ioctl.h>
46#endif
47
48struct sockaddr_pppol2tp sax;
49int pox_fd = -1;
50int ppp_fd = -1;
51//int ret;//session_fd;
52
53
54
55_u16 ppp_crc16_table[256] = {
56    0x0000, 0x1189, 0x2312, 0x329b, 0x4624, 0x57ad, 0x6536, 0x74bf,
57    0x8c48, 0x9dc1, 0xaf5a, 0xbed3, 0xca6c, 0xdbe5, 0xe97e, 0xf8f7,
58    0x1081, 0x0108, 0x3393, 0x221a, 0x56a5, 0x472c, 0x75b7, 0x643e,
59    0x9cc9, 0x8d40, 0xbfdb, 0xae52, 0xdaed, 0xcb64, 0xf9ff, 0xe876,
60    0x2102, 0x308b, 0x0210, 0x1399, 0x6726, 0x76af, 0x4434, 0x55bd,
61    0xad4a, 0xbcc3, 0x8e58, 0x9fd1, 0xeb6e, 0xfae7, 0xc87c, 0xd9f5,
62    0x3183, 0x200a, 0x1291, 0x0318, 0x77a7, 0x662e, 0x54b5, 0x453c,
63    0xbdcb, 0xac42, 0x9ed9, 0x8f50, 0xfbef, 0xea66, 0xd8fd, 0xc974,
64    0x4204, 0x538d, 0x6116, 0x709f, 0x0420, 0x15a9, 0x2732, 0x36bb,
65    0xce4c, 0xdfc5, 0xed5e, 0xfcd7, 0x8868, 0x99e1, 0xab7a, 0xbaf3,
66    0x5285, 0x430c, 0x7197, 0x601e, 0x14a1, 0x0528, 0x37b3, 0x263a,
67    0xdecd, 0xcf44, 0xfddf, 0xec56, 0x98e9, 0x8960, 0xbbfb, 0xaa72,
68    0x6306, 0x728f, 0x4014, 0x519d, 0x2522, 0x34ab, 0x0630, 0x17b9,
69    0xef4e, 0xfec7, 0xcc5c, 0xddd5, 0xa96a, 0xb8e3, 0x8a78, 0x9bf1,
70    0x7387, 0x620e, 0x5095, 0x411c, 0x35a3, 0x242a, 0x16b1, 0x0738,
71    0xffcf, 0xee46, 0xdcdd, 0xcd54, 0xb9eb, 0xa862, 0x9af9, 0x8b70,
72    0x8408, 0x9581, 0xa71a, 0xb693, 0xc22c, 0xd3a5, 0xe13e, 0xf0b7,
73    0x0840, 0x19c9, 0x2b52, 0x3adb, 0x4e64, 0x5fed, 0x6d76, 0x7cff,
74    0x9489, 0x8500, 0xb79b, 0xa612, 0xd2ad, 0xc324, 0xf1bf, 0xe036,
75    0x18c1, 0x0948, 0x3bd3, 0x2a5a, 0x5ee5, 0x4f6c, 0x7df7, 0x6c7e,
76    0xa50a, 0xb483, 0x8618, 0x9791, 0xe32e, 0xf2a7, 0xc03c, 0xd1b5,
77    0x2942, 0x38cb, 0x0a50, 0x1bd9, 0x6f66, 0x7eef, 0x4c74, 0x5dfd,
78    0xb58b, 0xa402, 0x9699, 0x8710, 0xf3af, 0xe226, 0xd0bd, 0xc134,
79    0x39c3, 0x284a, 0x1ad1, 0x0b58, 0x7fe7, 0x6e6e, 0x5cf5, 0x4d7c,
80    0xc60c, 0xd785, 0xe51e, 0xf497, 0x8028, 0x91a1, 0xa33a, 0xb2b3,
81    0x4a44, 0x5bcd, 0x6956, 0x78df, 0x0c60, 0x1de9, 0x2f72, 0x3efb,
82    0xd68d, 0xc704, 0xf59f, 0xe416, 0x90a9, 0x8120, 0xb3bb, 0xa232,
83    0x5ac5, 0x4b4c, 0x79d7, 0x685e, 0x1ce1, 0x0d68, 0x3ff3, 0x2e7a,
84    0xe70e, 0xf687, 0xc41c, 0xd595, 0xa12a, 0xb0a3, 0x8238, 0x93b1,
85    0x6b46, 0x7acf, 0x4854, 0x59dd, 0x2d62, 0x3ceb, 0x0e70, 0x1ff9,
86    0xf78f, 0xe606, 0xd49d, 0xc514, 0xb1ab, 0xa022, 0x92b9, 0x8330,
87    0x7bc7, 0x6a4e, 0x58d5, 0x495c, 0x3de3, 0x2c6a, 0x1ef1, 0x0f78
88};
89
90int global_serno = 1;
91
92struct buffer *new_outgoing (struct tunnel *t)
93{
94    /*
95     * Make a new outgoing control packet
96     */
97    struct buffer *tmp = new_buf (MAX_RECV_SIZE);
98    if (!tmp)
99        return NULL;
100    tmp->peer = t->peer;
101    tmp->start += sizeof (struct control_hdr);
102    tmp->len = 0;
103    tmp->retries = 0;
104    tmp->tunnel = t;
105    return tmp;
106}
107
108inline void recycle_outgoing (struct buffer *buf, struct sockaddr_in peer)
109{
110    /*
111     * This should only be used for ZLB's!
112     */
113    buf->start = buf->rstart + sizeof (struct control_hdr);
114    buf->peer = peer;
115    buf->len = 0;
116    buf->retries = -1;
117    buf->tunnel = NULL;
118}
119void add_fcs (struct buffer *buf)
120{
121    _u16 fcs = PPP_INITFCS;
122    unsigned char *c = buf->start;
123    int x;
124    for (x = 0; x < buf->len; x++)
125    {
126        fcs = PPP_FCS (fcs, *c);
127        c++;
128    }
129    fcs = fcs ^ 0xFFFF;
130    *c = fcs & 0xFF;
131    c++;
132    *c = (fcs >> 8) & 0xFF;
133    buf->len += 2;
134}
135
136void add_control_hdr (struct tunnel *t, struct call *c, struct buffer *buf)
137{
138    struct control_hdr *h;
139    buf->start -= sizeof (struct control_hdr);
140    buf->len += sizeof (struct control_hdr);
141    h = (struct control_hdr *) buf->start;
142    h->ver = htons (TBIT | LBIT | FBIT | VER_L2TP);
143    h->length = htons ((_u16) buf->len);
144    h->tid = htons (t->tid);
145    h->cid = htons (c->cid);
146    h->Ns = htons (t->control_seq_num);
147    h->Nr = htons (t->control_rec_seq_num);
148    t->control_seq_num++;
149
150}
151
152void hello (void *tun)
153{
154    struct buffer *buf;
155    struct tunnel *t;
156    struct timeval tv;
157    tv.tv_sec = HELLO_DELAY;
158    tv.tv_usec = 0;
159    t = (struct tunnel *) tun;
160    buf = new_outgoing (t);
161    add_message_type_avp (buf, Hello);
162    add_control_hdr (t, t->self, buf);
163    if (packet_dump)
164        do_packet_dump (buf);
165#ifdef DEBUG_HELLO
166    log (LOG_DEBUG, "%s: sending Hello on %d\n", __FUNCTION__, t->ourtid);
167#endif
168    control_xmit (buf);
169    /*
170     * Schedule another Hello in a little bit.
171     */
172#ifdef DEBUG_HELLO
173    log (LOG_DEBUG, "%s: scheduling another Hello on %d\n", __FUNCTION__,
174         t->ourtid);
175#endif
176    t->hello = schedule (tv, hello, (void *) t);
177}
178
179void control_zlb (struct buffer *buf, struct tunnel *t, struct call *c)
180{
181    recycle_outgoing (buf, t->peer);
182    add_control_hdr (t, c, buf);
183    t->control_seq_num--;
184#ifdef DEBUG_ZLB
185    log (LOG_DEBUG, "%s: sending control ZLB on tunnel %d\n", __FUNCTION__,
186         t->tid);
187#endif
188    udp_xmit (buf);
189}
190
191int control_finish (struct tunnel *t, struct call *c)
192{
193    /*
194     * After all AVP's have been handled, do anything else
195     * which needs to be done, like prepare response
196     * packets to go back.  This is essentially the
197     * implementation of the state machine of section 7.2.1
198     *
199     * If we set c->needclose, the call (or tunnel) will
200     * be closed upon return.
201     */
202    struct buffer *buf;
203    struct call *p, *z;
204    struct tunnel *y;
205    struct timeval tv;
206    struct ppp_opts *po;
207#ifdef USE_KERNEL
208    struct l2tp_call_opts co;
209#endif
210    char ip1[STRLEN];
211    char ip2[STRLEN];
212    char dummy_buf[128] = "/var/l2tp/"; /* jz: needed to read /etc/ppp/var.options - just kick it if you dont like */
213    if (c->msgtype < 0)
214    {
215        log (LOG_DEBUG, "%s: Whoa...  non-ZLB with no message type!\n",
216             __FUNCTION__);
217        return -EINVAL;
218    }
219    if (debug_state)
220        log (LOG_DEBUG,
221             "%s: message type is %s(%d).  Tunnel is %d, call is %d.\n",
222             __FUNCTION__, msgtypes[c->msgtype], c->msgtype, t->tid, c->cid);
223    switch (c->msgtype)
224    {
225    case 0:
226        /*
227         * We need to initiate a connection.
228         */
229        if (t->self == c)
230        {
231            if (t->lns)
232            {
233                t->ourrws = t->lns->tun_rws;
234                t->hbit = t->lns->hbit;
235            }
236            else if (t->lac)
237            {
238                t->ourrws = t->lac->tun_rws;
239                t->hbit = t->lac->hbit;
240            }
241            /* This is an attempt to bring up the tunnel */
242            t->state = SCCRQ;
243            buf = new_outgoing (t);
244            add_message_type_avp (buf, SCCRQ);
245            if (t->hbit)
246            {
247                mk_challenge (t->chal_them.vector, VECTOR_SIZE);
248                add_randvect_avp (buf, t->chal_them.vector, VECTOR_SIZE);
249            }
250            add_protocol_avp (buf);
251            add_frame_caps_avp (buf, t->ourfc);
252            add_bearer_caps_avp (buf, t->ourbc);
253            /* FIXME:  Tie breaker */
254            add_firmware_avp (buf);
255            add_hostname_avp (buf);
256            add_vendor_avp (buf);
257            add_tunnelid_avp (buf, t->ourtid);
258            if (t->ourrws >= 0)
259                add_avp_rws (buf, t->ourrws);
260            if ((t->lac && t->lac->challenge)
261                || (t->lns && t->lns->challenge))
262            {
263                mk_challenge (t->chal_them.challenge, MD_SIG_SIZE);
264                add_challenge_avp (buf, t->chal_them.challenge, MD_SIG_SIZE);
265                t->chal_them.state = STATE_CHALLENGED;
266                /* We generate the challenge and make a note that we plan to
267                   challenge the peer, but we can't predict the response yet
268                   because we don't know their hostname AVP */
269            }
270            add_control_hdr (t, c, buf);
271            c->cnu = 0;
272            if (packet_dump)
273                do_packet_dump (buf);
274            if (debug_state)
275                log (LOG_DEBUG, "%s: control_finish: sending SCCRQ\n",
276                     __FUNCTION__);
277            control_xmit (buf);
278        }
279        else
280        {
281            if (switch_io)
282            {
283                c->state = ICRQ;
284                if (c->lns)
285                {
286                    c->lbit = c->lns->lbit ? LBIT : 0;
287/*					c->ourrws = c->lns->call_rws;
288					if (c->ourrws > -1) c->ourfbit = FBIT; else c->ourfbit = 0; */
289                }
290                else if (c->lac)
291                {
292                    c->lbit = c->lac->lbit ? LBIT : 0;
293/*					c->ourrws = c->lac->call_rws;
294					if (c->ourrws > -1) c->ourfbit = FBIT; else c->ourfbit = 0; */
295                }
296                buf = new_outgoing (t);
297                add_message_type_avp (buf, ICRQ);
298                if (t->hbit)
299                {
300                    mk_challenge (t->chal_them.vector, VECTOR_SIZE);
301                    add_randvect_avp (buf, t->chal_them.vector, VECTOR_SIZE);
302                }
303#ifdef TEST_HIDDEN
304                add_callid_avp (buf, c->ourcid, t);
305#else
306                add_callid_avp (buf, c->ourcid);
307#endif
308                add_serno_avp (buf, global_serno);
309                c->serno = global_serno;
310                global_serno++;
311                add_bearer_avp (buf, 0);
312                add_control_hdr (t, c, buf);
313                c->cnu = 0;
314                if (packet_dump)
315                    do_packet_dump (buf);
316                if (debug_state)
317                    log (LOG_DEBUG, "%s: sending ICRQ\n", __FUNCTION__);
318                control_xmit (buf);
319            }
320            else
321            {                   /* jz: sending a OCRQ */
322                c->state = OCRQ;
323                if (c->lns)
324                {
325                    c->lbit = c->lns->lbit ? LBIT : 0;
326/*                                      c->ourrws = c->lns->call_rws;
327                                        if (c->ourrws > -1) c->ourfbit = FBIT; else c->ourfbit = 0; */
328                }
329                else if (c->lac)
330                {
331/*                                      c->ourrws = c->lac->call_rws;
332                                        if (c->ourrws > -1) c->ourfbit = FBIT; else c->ourfbit = 0; */
333                }
334
335                if (t->fc & SYNC_FRAMING)
336                    c->frame = SYNC_FRAMING;
337                else
338                    c->frame = ASYNC_FRAMING;
339                buf = new_outgoing (t);
340                add_message_type_avp (buf, OCRQ);
341#ifdef TEST_HIDDEN
342                add_callid_avp (buf, c->ourcid, t);
343#else
344                add_callid_avp (buf, c->ourcid);
345#endif
346                add_serno_avp (buf, global_serno);
347                c->serno = global_serno;
348                global_serno++;
349                add_minbps_avp (buf, DEFAULT_MIN_BPS);
350                add_maxbps_avp (buf, DEFAULT_MAX_BPS);
351                add_bearer_avp (buf, 0);
352                add_frame_avp (buf, c->frame);
353                add_number_avp (buf, c->dial_no);
354                add_control_hdr (t, c, buf);
355                c->cnu = 0;
356                if (packet_dump)
357                    do_packet_dump (buf);
358                control_xmit (buf);
359            }
360        }
361        break;
362    case SCCRQ:
363        /*
364         * We've received a request, now let's
365         * formulate a response.
366         */
367        if (t->tid <= 0)
368        {
369            if (DEBUG)
370                log (LOG_DEBUG,
371                     "%s: Peer did not specify assigned tunnel ID.  Closing.\n",
372                     __FUNCTION__);
373            set_error (c, VENDOR_ERROR, "Specify your assigned tunnel ID");
374            c->needclose = -1;
375            return -EINVAL;
376        }
377        if (!(t->lns = get_lns (t)))
378        {
379            if (DEBUG)
380                log (LOG_DEBUG,
381                     "%s: Denied connection to unauthorized peer %s\n",
382                     __FUNCTION__, IPADDY (t->peer.sin_addr));
383            set_error (c, VENDOR_ERROR, "No Authorization");
384            c->needclose = -1;
385            return -EINVAL;
386        }
387        t->ourrws = t->lns->tun_rws;
388        t->hbit = t->lns->hbit;
389        if (t->fc < 0)
390        {
391            if (DEBUG)
392                log (LOG_DEBUG,
393                     "%s: Peer did not specify framing capability.  Closing.\n",
394                     __FUNCTION__);
395            set_error (c, VENDOR_ERROR, "Specify framing capability");
396            c->needclose = -1;
397            return -EINVAL;
398        }
399        /* FIXME: Do we need to be sure they specified a version number?
400         *   Theoretically, yes, but we don't have anything in the code
401         *   to actually *do* anything with it, so...why check at this point?
402         * We shouldn't be requiring a bearer capabilities avp to be present in
403         * SCCRQ and SCCRP as they aren't required
404         if (t->bc < 0 ) {
405         if (DEBUG) log(LOG_DEBUG,
406         "%s: Peer did not specify bearer capability.  Closing.\n",__FUNCTION__);
407         set_error(c, VENDOR_ERROR, "Specify bearer capability");
408         c->needclose = -1;
409         return -EINVAL;
410         }  */
411        if (!strlen (t->hostname))
412        {
413            if (DEBUG)
414                log (LOG_DEBUG,
415                     "%s: Peer did not specify hostname.  Closing.\n",
416                     __FUNCTION__);
417            set_error (c, VENDOR_ERROR, "Specify your hostname");
418            c->needclose = -1;
419            return -EINVAL;
420        }
421        y = tunnels.head;
422        while (y)
423        {
424            if ((y->tid == t->tid) &&
425                (y->peer.sin_addr.s_addr == t->peer.sin_addr.s_addr) &&
426                (y != t))
427            {
428                /* This can happen if we get a duplicate
429                   StartCCN or if they don't get our ack packet */
430                /*
431                 * But it is legitimate for two different remote systems
432                 * to use the same tid
433                 */
434                log (LOG_DEBUG,
435                     "%s: Peer requested tunnel %d twice, ignoring second one.\n",
436                     __FUNCTION__, t->tid);
437                c->needclose = 0;
438                c->closing = -1;
439                return 0;
440            }
441            y = y->next;
442        }
443        t->state = SCCRP;
444        buf = new_outgoing (t);
445        add_message_type_avp (buf, SCCRP);
446        if (t->hbit)
447        {
448            mk_challenge (t->chal_them.vector, VECTOR_SIZE);
449            add_randvect_avp (buf, t->chal_them.vector, VECTOR_SIZE);
450        }
451        add_protocol_avp (buf);
452        add_frame_caps_avp (buf, t->ourfc);
453        add_bearer_caps_avp (buf, t->ourbc);
454        add_firmware_avp (buf);
455        add_hostname_avp (buf);
456        add_vendor_avp (buf);
457        add_tunnelid_avp (buf, t->ourtid);
458        if (t->ourrws >= 0)
459            add_avp_rws (buf, t->ourrws);
460        if (t->chal_us.state)
461        {
462            t->chal_us.ss = SCCRP;
463            handle_challenge (t, &t->chal_us);
464            add_chalresp_avp (buf, t->chal_us.response, MD_SIG_SIZE);
465        }
466        if (t->lns->challenge)
467        {
468            t->chal_them.challenge = malloc(MD_SIG_SIZE);
469            if (!(t->chal_them.challenge))
470            {
471                log (LOG_WARN, "%s: malloc failed\n", __FUNCTION__);
472                set_error (c, VENDOR_ERROR, "malloc failed");
473                toss (buf);
474                return -EINVAL;
475            }
476            mk_challenge (t->chal_them.challenge, MD_SIG_SIZE);
477            t->chal_them.ss = SCCCN;
478            if (handle_challenge (t, &t->chal_them))
479            {
480                /* We already know what to expect back */
481                log (LOG_WARN, "%s: No secret for '%s'\n", __FUNCTION__,
482                     t->hostname);
483                set_error (c, VENDOR_ERROR, "No secret on our side");
484                toss (buf);
485                return -EINVAL;
486            };
487            add_challenge_avp (buf, t->chal_them.challenge, MD_SIG_SIZE);
488        }
489        add_control_hdr (t, c, buf);
490        if (packet_dump)
491            do_packet_dump (buf);
492        c->cnu = 0;
493        if (debug_state)
494            log (LOG_DEBUG, "%s: sending SCCRP\n", __FUNCTION__);
495        control_xmit (buf);
496        break;
497    case SCCRP:
498        /*
499         * We have a reply.  If everything is okay, send
500         * a connected message
501         */
502        if (t->fc < 0)
503        {
504            if (DEBUG)
505                log (LOG_DEBUG,
506                     "%s: Peer did not specify framing capability.  Closing.\n",
507                     __FUNCTION__);
508            set_error (c, VENDOR_ERROR, "Specify framing capability");
509            c->needclose = -1;
510            return -EINVAL;
511        }
512        /* FIXME: Do we need to be sure they specified a version number?
513         *   Theoretically, yes, but we don't have anything in the code
514         *   to actually *do* anything with it, so...why check at this point?
515         * We shouldn't be requiring a bearer capabilities avp to be present in
516         * SCCRQ and SCCRP as they aren't required
517         if (t->bc < 0 ) {
518         if (DEBUG) log(LOG_DEBUG,
519         "%s: Peer did not specify bearer capability.  Closing.\n",__FUNCTION__);
520         set_error(c, VENDOR_ERROR, "Specify bearer capability");
521         c->needclose = -1;
522         return -EINVAL;
523         } */
524        if (!strlen (t->hostname))
525        {
526            if (DEBUG)
527                log (LOG_DEBUG,
528                     "%s: Peer did not specify hostname.  Closing.\n",
529                     __FUNCTION__);
530            set_error (c, VENDOR_ERROR, "Specify your hostname");
531            c->needclose = -1;
532            return -EINVAL;
533        }
534        if (t->tid <= 0)
535        {
536            if (DEBUG)
537                log (LOG_DEBUG,
538                     "%s: Peer did not specify assigned tunnel ID.  Closing.\n",
539                     __FUNCTION__);
540            set_error (c, VENDOR_ERROR, "Specify your assigned tunnel ID");
541            c->needclose = -1;
542            return -EINVAL;
543        }
544        if (t->chal_them.state)
545        {
546            t->chal_them.ss = SCCRP;
547            if (handle_challenge (t, &t->chal_them))
548            {
549                set_error (c, VENDOR_ERROR, "No secret key on our side");
550                log (LOG_WARN, "%s: No secret key for authenticating '%s'\n",
551                     __FUNCTION__, t->hostname);
552                c->needclose = -1;
553                return -EINVAL;
554            }
555            if (memcmp
556                (t->chal_them.reply, t->chal_them.response, MD_SIG_SIZE))
557            {
558                set_error (c, VENDOR_ERROR,
559                           "Invalid challenge authentication");
560                log (LOG_DEBUG, "%s: Invalid authentication for host '%s'\n",
561                     __FUNCTION__, t->hostname);
562                c->needclose = -1;
563                return -EINVAL;
564            }
565        }
566        if (t->chal_us.state)
567        {
568            t->chal_us.ss = SCCCN;
569            if (handle_challenge (t, &t->chal_us))
570            {
571                log (LOG_WARN, "%s: No secret for authenticating to '%s'\n",
572                     __FUNCTION__, t->hostname);
573                set_error (c, VENDOR_ERROR, "No secret key on our end");
574                c->needclose = -1;
575                return -EINVAL;
576            };
577        }
578#ifdef USE_KERNEL
579        if (kernel_support)
580        {
581            struct l2tp_tunnel_opts to;
582            to.ourtid = t->ourtid;
583            ioctl (server_socket, L2TPIOCGETTUNOPTS, &to);
584            to.tid = t->tid;
585            ioctl (server_socket, L2TPIOCSETTUNOPTS, &to);
586        }
587#endif
588        t->state = SCCCN;
589        buf = new_outgoing (t);
590        add_message_type_avp (buf, SCCCN);
591        if (t->hbit)
592        {
593            mk_challenge (t->chal_them.vector, VECTOR_SIZE);
594            add_randvect_avp (buf, t->chal_them.vector, VECTOR_SIZE);
595        }
596        if (t->chal_us.state)
597            add_chalresp_avp (buf, t->chal_us.response, MD_SIG_SIZE);
598        add_control_hdr (t, c, buf);
599        if (packet_dump)
600            do_packet_dump (buf);
601        c->cnu = 0;
602        if (debug_state)
603            log (LOG_DEBUG, "%s: sending SCCCN\n", __FUNCTION__);
604        control_xmit (buf);
605        /* Schedule a HELLO */
606        tv.tv_sec = HELLO_DELAY;
607        tv.tv_usec = 0;
608#ifdef DEBUG_HELLO
609        log (LOG_DEBUG, "%s: scheduling initial HELLO on %d\n", __FUNCTION__,
610             t->ourtid);
611#endif
612        t->hello = schedule (tv, hello, (void *) t);
613        log (LOG_LOG,
614             "%s: Connection established to %s, %d.  Local: %d, Remote: %d.\n",
615             __FUNCTION__, IPADDY (t->peer.sin_addr),
616             ntohs (t->peer.sin_port), t->ourtid, t->tid);
617        if (t->lac)
618        {
619            /* This is part of a LAC, so we want to go ahead
620               and start an ICRQ now */
621            magic_lac_dial (t->lac);
622        }
623        break;
624    case SCCCN:
625        if (t->chal_them.state)
626        {
627            if (memcmp
628                (t->chal_them.reply, t->chal_them.response, MD_SIG_SIZE))
629            {
630                set_error (c, VENDOR_ERROR,
631                           "Invalid challenge authentication");
632                log (LOG_DEBUG, "%s: Invalid authentication for host '%s'\n",
633                     __FUNCTION__, t->hostname);
634                c->needclose = -1;
635                return -EINVAL;
636            }
637        }
638#ifdef USE_KERNEL
639        if (kernel_support)
640        {
641            struct l2tp_tunnel_opts to;
642            to.ourtid = t->ourtid;
643            ioctl (server_socket, L2TPIOCGETTUNOPTS, &to);
644            to.tid = t->tid;
645            ioctl (server_socket, L2TPIOCSETTUNOPTS, &to);
646        }
647#endif
648        t->state = SCCCN;
649        log (LOG_LOG,
650             "%s: Connection established to %s, %d.  Local: %d, Remote: %d.  LNS session is '%s'\n",
651             __FUNCTION__, IPADDY (t->peer.sin_addr),
652             ntohs (t->peer.sin_port), t->ourtid, t->tid, t->lns->entname);
653        /* Schedule a HELLO */
654        tv.tv_sec = HELLO_DELAY;
655        tv.tv_usec = 0;
656#ifdef DEBUG_HELLO
657        log (LOG_DEBUG, "%s: scheduling initial HELLO on %d\n", __FUNCTION__,
658             t->ourtid);
659#endif
660        t->hello = schedule (tv, hello, (void *) t);
661        break;
662    case StopCCN:
663        if (t->qtid < 0)
664        {
665            if (DEBUG)
666                log (LOG_DEBUG,
667                     "%s: Peer tried to disconnect without specifying tunnel ID\n",
668                     __FUNCTION__);
669            return -EINVAL;
670        }
671        if ((t->qtid != t->tid) && (t->tid > 0))
672        {
673            if (DEBUG)
674                log (LOG_DEBUG,
675                     "%s: Peer tried to disconnect with invalid TID (%d != %d)\n",
676                     __FUNCTION__, t->qtid, t->tid);
677            return -EINVAL;
678        }
679        /* In case they're disconnecting immediately after SCCN */
680        if (!t->tid)
681            t->tid = t->qtid;
682        if (t->self->result < 0)
683        {
684            if (DEBUG)
685                log (LOG_DEBUG,
686                     "%s: Peer tried to disconnect without specifying result code.\n",
687                     __FUNCTION__);
688            return -EINVAL;
689        }
690        log (LOG_LOG,
691             "%s: Connection closed to %s, port %d (%s), Local: %d, Remote: %d\n",
692             __FUNCTION__, IPADDY (t->peer.sin_addr),
693             ntohs (t->peer.sin_port), t->self->errormsg, t->ourtid, t->tid);
694        c->needclose = 0;
695        c->closing = -1;
696
697        /* Foxconn, add by MJ. for kill itself after call closed. 01/20/2010*/
698        death_handler(SIGTERM);
699        break;
700
701    case ICRQ:
702        p = t->call_head;
703        if (!p->lns)
704        {
705            set_error (p, ERROR_INVALID, "This tunnel cannot accept calls\n");
706            call_close (p);
707            return -EINVAL;
708        }
709        p->lbit = p->lns->lbit ? LBIT : 0;
710/*		p->ourrws = p->lns->call_rws;
711		if (p->ourrws > -1) p->ourfbit = FBIT; else p->ourfbit = 0; */
712        if (p->cid < 0)
713        {
714            if (DEBUG)
715                log (LOG_DEBUG,
716                     "%s: Peer tried to initiate call without call ID\n",
717                     __FUNCTION__);
718            /* Here it doesn't make sense to use the needclose flag because
719               the call p did not receive any packets */
720            call_close (p);
721            return -EINVAL;
722        }
723        z = p->next;
724        while (z)
725        {
726            if (z->cid == p->cid)
727            {
728                /* This can happen if we get a duplicate
729                   ICRQ or if they don't get our ack packet */
730                log (LOG_DEBUG,
731                     "%s: Peer requested call %d twice, ignoring second one.\n",
732                     __FUNCTION__, p->cid);
733                p->needclose = 0;
734                p->closing = -1;
735                return 0;
736            }
737            z = z->next;
738        }
739        p = t->call_head;
740        /* FIXME:  by commenting this out, we're not checking whether the serial
741         * number avp is included in the ICRQ at all which its required to be.
742         * Since the serial number is only used for human debugging aid, this
743         * isn't a big deal, but it would be nice to have *some* sort of check
744         * for it and perhaps just log it and go on.  */
745/*    JLM	if (p->serno<1) {
746			if (DEBUG) log(LOG_DEBUG,
747			"%s: Peer did not specify serial number when initiating call\n", __FUNCTION__);
748			call_close(p);
749			return -EINVAL;
750		} */
751
752#ifdef IP_ALLOCATION
753        p->addr = get_addr (t->lns->range);
754        if (!p->addr)
755        {
756            set_error (p, ERROR_NORES, "No available IP address");
757            call_close (p);
758            log (LOG_DEBUG, "%s: Out of IP addresses on tunnel %d!\n",
759                 __FUNCTION__, t->tid);
760            return -EINVAL;
761        }
762#endif
763
764        reserve_addr (p->addr);
765        p->state = ICRP;
766        buf = new_outgoing (t);
767        add_message_type_avp (buf, ICRP);
768        if (t->hbit)
769        {
770            mk_challenge (t->chal_them.vector, VECTOR_SIZE);
771            add_randvect_avp (buf, t->chal_them.vector, VECTOR_SIZE);
772        }
773#ifdef TEST_HIDDEN
774        add_callid_avp (buf, p->ourcid, t);
775#else
776        add_callid_avp (buf, p->ourcid);
777#endif
778/*		if (p->ourrws >=0)
779			add_avp_rws(buf, p->ourrws); */
780        /*
781         * FIXME: I should really calculate
782         * Packet Processing Delay
783         */
784        /* add_ppd_avp(buf,ppd); */
785        add_control_hdr (t, p, buf);
786        if (packet_dump)
787            do_packet_dump (buf);
788        p->cnu = 0;
789        if (debug_state)
790            log (LOG_DEBUG, "%s: Sending ICRP\n", __FUNCTION__);
791        control_xmit (buf);
792        break;
793    case ICRP:
794        if (c->cid < 0)
795        {
796            if (DEBUG)
797                log (LOG_DEBUG,
798                     "%s: Peer tried to negotiate ICRP without specifying call ID\n",
799                     __FUNCTION__);
800            c->needclose = -1;
801            return -EINVAL;
802        }
803        c->state = ICCN;
804        if (t->fc & SYNC_FRAMING)
805            c->frame = SYNC_FRAMING;
806        else
807            c->frame = ASYNC_FRAMING;
808
809        buf = new_outgoing (t);
810        add_message_type_avp (buf, ICCN);
811        if (t->hbit)
812        {
813            mk_challenge (t->chal_them.vector, VECTOR_SIZE);
814            add_randvect_avp (buf, t->chal_them.vector, VECTOR_SIZE);
815        }
816        add_txspeed_avp (buf, DEFAULT_TX_BPS);
817        add_frame_avp (buf, c->frame);
818/*		if (c->ourrws >= 0)
819			add_avp_rws(buf, c->ourrws); */
820        /* FIXME: Packet Processing Delay */
821        /* We don't need any kind of proxy PPP stuff */
822        /* Can we proxy authenticate ourselves??? */
823        add_rxspeed_avp (buf, DEFAULT_RX_BPS);
824/* add_seqreqd_avp (buf); *//* We don't have sequencing code, so
825 * don't ask for sequencing */
826        add_control_hdr (t, c, buf);
827        if (packet_dump)
828            do_packet_dump (buf);
829        c->cnu = 0;
830#ifdef USE_KERNEL
831        if (kernel_support)
832        {
833            co.ourtid = c->container->ourtid;
834            co.ourcid = c->ourcid;
835            ioctl (server_socket, L2TPIOCGETCALLOPTS, &co);
836            co.cid = c->cid;
837            co.flags = co.flags | L2TP_FLAG_CALL_UP;
838            co.rws = c->rws;
839            co.ourrws = c->ourrws;
840            co.flags |= c->lbit;
841            ioctl (server_socket, L2TPIOCSETCALLOPTS, &co);
842        }
843#endif
844        if (debug_state)
845            log (LOG_DEBUG, "%s: Sending ICCN\n", __FUNCTION__);
846        log (LOG_LOG,
847             "%s: Call established with %s, Local: %d, Remote: %d, Serial: %d\n",
848             __FUNCTION__, IPADDY (t->peer.sin_addr), c->ourcid, c->cid,
849             c->serno);
850
851#ifdef PPPOX_L2TP
852        /* Foxconn, add start by MJ. for building pppol2tp socket*/
853        //struct sockaddr_pppol2tp sax;
854        //int pox_fd, ppp_fd;
855        //int ret;//session_fd;
856        //int chindex;
857
858        pox_fd = socket(AF_PPPOX, SOCK_DGRAM, PX_PROTO_OL2TP);
859
860        sax.sa_family = AF_PPPOX;
861        sax.sa_protocol = PX_PROTO_OL2TP;
862        sax.pppol2tp.fd = server_socket; // bound UDP socket
863        sax.pppol2tp.pid = 0;        // current pid owns UDP socket
864        sax.pppol2tp.addr.sin_addr.s_addr = t->peer.sin_addr.s_addr;
865        sax.pppol2tp.addr.sin_port = t->peer.sin_port;
866        sax.pppol2tp.addr.sin_family = AF_INET;
867        sax.pppol2tp.s_tunnel  = t->ourtid;
868        sax.pppol2tp.s_session = c->ourcid;
869        sax.pppol2tp.d_tunnel  = t->tid;
870        sax.pppol2tp.d_session = c->cid;
871
872        if(pox_fd > 0)
873        {
874            int ret = -1;
875
876            /* Connect to the PPPOL2TP device */
877            ret = connect(pox_fd, (struct sockaddr *)&sax, sizeof(sax));
878
879            if(ret == 0)
880            {
881                int chindex;
882                int flags;
883                /* Try to get PPP channel from PPPoL2TP device */
884                if (ioctl(pox_fd, PPPIOCGCHAN, &chindex) == -1)
885                    log (LOG_DEBUG, "Couldn't get channel number\n");
886                /* Open ppp device */
887                ppp_fd = open("/dev/ppp", O_RDWR);
888
889                if(ppp_fd >=0)
890                {
891                    /* Attach to PPP channel */
892                    if ((ret = ioctl(ppp_fd, PPPIOCATTCHAN, &chindex)) < 0)
893                        log (LOG_DEBUG, "Couldn't attach channel to ppp device\n");
894                    flags = fcntl(ppp_fd, F_GETFL);
895                    if (flags == -1 || fcntl(ppp_fd, F_SETFL, flags | O_NONBLOCK) == -1)
896                        log (LOG_DEBUG, "Couldn't set /dev/ppp (channel) to nonblock\n");
897                }
898                else
899                    log (LOG_DEBUG, "Couldn't reopen /dev/ppp\n");
900            }
901            else
902                log (LOG_DEBUG, "Couldn't connect PPPoL2TP\n");
903        }
904        else
905            log (LOG_DEBUG, "open PPPoL2TP socket failed\n");
906        /* Foxconn, add edn by MJ.*/
907#endif
908        control_xmit (buf);
909        po = NULL;
910        po = add_opt (po, "passive");
911        po = add_opt (po, "-detach");
912        if (c->lac)
913        {
914            if (c->lac->defaultroute)
915                po = add_opt (po, "defaultroute");
916            strncpy (ip1, IPADDY (c->lac->localaddr), sizeof (ip1));
917            strncpy (ip2, IPADDY (c->lac->remoteaddr), sizeof (ip2));
918#ifdef IP_ALLOCATION
919            po = add_opt (po, "%s:%s", c->lac->localaddr ? ip1 : "",
920                          c->lac->remoteaddr ? ip2 : "");
921#endif
922            if (c->lac->authself)
923            {
924                if (c->lac->pap_refuse)
925                    po = add_opt (po, "refuse-pap");
926                if (c->lac->chap_refuse)
927                    po = add_opt (po, "refuse-chap");
928            }
929            else
930            {
931                po = add_opt (po, "refuse-pap");
932                po = add_opt (po, "refuse-chap");
933            }
934            if (c->lac->authpeer)
935            {
936                po = add_opt (po, "auth");
937                if (c->lac->pap_require)
938                    po = add_opt (po, "require-pap");
939                if (c->lac->chap_require)
940                    po = add_opt (po, "require-chap");
941            }
942            if (c->lac->authname[0])
943            {
944                po = add_opt (po, "name");
945                po = add_opt (po, c->lac->authname);
946            }
947            if (c->lac->debug)
948                po = add_opt (po, "debug");
949            if (c->lac->pppoptfile[0])
950            {
951                po = add_opt (po, "file");
952                po = add_opt (po, c->lac->pppoptfile);
953            }
954        };
955        start_pppd (c, po);
956        opt_destroy (po);
957        if (c->lac)
958            c->lac->rtries = 0;
959        break;
960    case ICCN:
961        if (c == t->self)
962        {
963            log (LOG_DEBUG,
964                 "%s: Peer attempted ICCN on the actual tunnel, not the call",
965                 __FUNCTION__);
966            return -EINVAL;
967        }
968        if (c->txspeed < 1)
969        {
970            log (LOG_DEBUG,
971                 "%s: Peer did not specify transmit speed\n", __FUNCTION__);
972            c->needclose = -1;
973            return -EINVAL;
974        };
975        if (c->frame < 1)
976        {
977            log (LOG_DEBUG,
978                 "%s: Peer did not specify framing type\n", __FUNCTION__);
979            c->needclose = -1;
980            return -EINVAL;
981        }
982        c->state = ICCN;
983#ifdef USE_KERNEL
984        if (kernel_support)
985        {
986            co.ourtid = c->container->ourtid;
987            co.ourcid = c->ourcid;
988            if (ioctl (server_socket, L2TPIOCGETCALLOPTS, &co))
989                perror ("ioctl(get)");
990            co.cid = c->cid;
991            co.flags = co.flags | L2TP_FLAG_CALL_UP;
992            co.rws = c->rws;
993            co.ourrws = c->ourrws;
994            co.flags |= c->lbit;
995            if (ioctl (server_socket, L2TPIOCSETCALLOPTS, &co))
996                perror ("ioctl(set)");
997        }
998#endif
999        strncpy (ip1, IPADDY (c->lns->localaddr), sizeof (ip1));
1000        strncpy (ip2, IPADDY (c->addr), sizeof (ip2));
1001        po = NULL;
1002        po = add_opt (po, "passive");
1003        po = add_opt (po, "-detach");
1004        po = add_opt (po, "%s:%s", c->lns->localaddr ? ip1 : "", ip2);
1005        if (c->lns->authself)
1006        {
1007            if (c->lns->pap_refuse)
1008                po = add_opt (po, "refuse-pap");
1009            if (c->lns->chap_refuse)
1010                po = add_opt (po, "refuse-chap");
1011        }
1012        else
1013        {
1014            po = add_opt (po, "refuse-pap");
1015            po = add_opt (po, "refuse-chap");
1016        }
1017        if (c->lns->authpeer)
1018        {
1019            po = add_opt (po, "auth");
1020            if (c->lns->pap_require)
1021                po = add_opt (po, "require-pap");
1022            if (c->lns->chap_require)
1023                po = add_opt (po, "require-chap");
1024            if (c->lns->passwdauth)
1025                po = add_opt (po, "login");
1026        }
1027        if (c->lns->authname[0])
1028        {
1029            po = add_opt (po, "name");
1030            po = add_opt (po, c->lns->authname);
1031        }
1032        if (c->lns->debug)
1033            po = add_opt (po, "debug");
1034        if (c->lns->pppoptfile[0])
1035        {
1036            po = add_opt (po, "file");
1037            po = add_opt (po, c->lns->pppoptfile);
1038        }
1039        start_pppd (c, po);
1040        opt_destroy (po);
1041        log (LOG_LOG,
1042             "%s: Call established with %s, Local: %d, Remote: %d, Serial: %d\n",
1043             __FUNCTION__, IPADDY (t->peer.sin_addr), c->ourcid, c->cid,
1044             c->serno);
1045        break;
1046    case OCRP:                 /* jz: nothing to do for OCRP, waiting for OCCN */
1047        break;
1048    case OCCN:                 /* jz: get OCCN, so the only thing we must do is to start the pppd */
1049        po = NULL;
1050        po = add_opt (po, "passive");
1051        po = add_opt (po, "-detach");
1052        po = add_opt (po, "file");
1053        strcat (dummy_buf, c->dial_no); /* jz: use /etc/ppp/dialnumber.options for pppd - kick it if you dont like */
1054        strcat (dummy_buf, ".options");
1055        po = add_opt (po, dummy_buf);
1056        if (c->lac)
1057        {
1058            if (c->lac->defaultroute)
1059                po = add_opt (po, "defaultroute");
1060            strncpy (ip1, IPADDY (c->lac->localaddr), sizeof (ip1));
1061            strncpy (ip2, IPADDY (c->lac->remoteaddr), sizeof (ip2));
1062            po = add_opt (po, "%s:%s", c->lac->localaddr ? ip1 : "",
1063                          c->lac->remoteaddr ? ip2 : "");
1064            if (c->lac->authself)
1065            {
1066                if (c->lac->pap_refuse)
1067                    po = add_opt (po, "refuse-pap");
1068                if (c->lac->chap_refuse)
1069                    po = add_opt (po, "refuse-chap");
1070            }
1071            else
1072            {
1073                po = add_opt (po, "refuse-pap");
1074                po = add_opt (po, "refuse-chap");
1075            }
1076            if (c->lac->authpeer)
1077            {
1078                po = add_opt (po, "auth");
1079                if (c->lac->pap_require)
1080                    po = add_opt (po, "require-pap");
1081                if (c->lac->chap_require)
1082                    po = add_opt (po, "require-chap");
1083            }
1084            if (c->lac->authname[0])
1085            {
1086                po = add_opt (po, "name");
1087                po = add_opt (po, c->lac->authname);
1088            }
1089            if (c->lac->debug)
1090                po = add_opt (po, "debug");
1091            if (c->lac->pppoptfile[0])
1092            {
1093                po = add_opt (po, "file");
1094                po = add_opt (po, c->lac->pppoptfile);
1095            }
1096        };
1097        start_pppd (c, po);
1098
1099        log (LOG_LOG, "parameters: Local: %d , Remote: %d , Serial: %d , Pid: %d , Tunnelid: %d , Phoneid: %s\n", c->ourcid, c->cid, c->serno, c->pppd, t->ourtid, c->dial_no); /*  jz: just show some information */
1100
1101        opt_destroy (po);
1102        if (c->lac)
1103            c->lac->rtries = 0;
1104        break;
1105
1106
1107    case CDN:
1108        if (c->qcid < 0)
1109        {
1110            if (DEBUG)
1111                log (LOG_DEBUG,
1112                     "%s: Peer tried to disconnect without specifying call ID\n",
1113                     __FUNCTION__);
1114            return -EINVAL;
1115        }
1116        if (c == t->self)
1117        {
1118            p = t->call_head;
1119            while (p && (p->cid != c->qcid))
1120                p = p->next;
1121            if (!p)
1122            {
1123                if (DEBUG)
1124                    log (LOG_DEBUG,
1125                         "%s: Unable to determine call to be disconnected.\n",
1126                         __FUNCTION__);
1127                return -EINVAL;
1128            }
1129        }
1130        else
1131            p = c;
1132        if ((c->qcid != p->cid) && p->cid > 0)
1133        {
1134            if (DEBUG)
1135                log (LOG_DEBUG,
1136                     "%s: Peer tried to disconnect with invalid CID (%d != %d)\n",
1137                     __FUNCTION__, c->qcid, c->cid);
1138            return -EINVAL;
1139        }
1140        /* Foxconn, add comment, by MJ., Call will be canceled in here. */
1141        c->qcid = -1;
1142        if (c->result < 0)
1143        {
1144            if (DEBUG)
1145                log (LOG_DEBUG,
1146                     "%s: Peer tried to disconnect without specifying result code.\n",
1147                     __FUNCTION__);
1148            return -EINVAL;
1149        }
1150        log (LOG_LOG,
1151             "%s: Connection closed to %s, serial %d (%s)\n", __FUNCTION__,
1152             IPADDY (t->peer.sin_addr), c->serno, c->errormsg);
1153        c->needclose = 0;
1154        c->closing = -1;
1155        /* Foxconn, add by MJ. for kill itself after call closed. 01/20/2010*/
1156        death_handler(SIGTERM);
1157        break;
1158    case Hello:
1159        break;
1160    case SLI:
1161        break;
1162    default:
1163        log (LOG_DEBUG,
1164             "%s: Don't know how to finish a message of type %d\n",
1165             __FUNCTION__, c->msgtype);
1166        set_error (c, VENDOR_ERROR, "Unimplemented message %d\n", c->msgtype);
1167    }
1168    return 0;
1169}
1170
1171inline int check_control (const struct buffer *buf, struct tunnel *t,
1172                          struct call *c)
1173{
1174    /*
1175     * Check if this is a valid control
1176     * or not.  Returns 0 on success
1177     */
1178    struct control_hdr *h = (struct control_hdr *) (buf->start);
1179    struct buffer *zlb;
1180    if (buf->len < sizeof (struct control_hdr))
1181    {
1182        if (DEBUG)
1183        {
1184            log (LOG_DEBUG,
1185                 "%s: Received too small of packet\n", __FUNCTION__);
1186        }
1187        return -EINVAL;
1188    }
1189#ifdef SANITY
1190    if (buf->len != h->length)
1191    {
1192        if (DEBUG)
1193        {
1194            log (LOG_DEBUG,
1195                 "%s: Reported and actual sizes differ (%d != %d)\n",
1196                 __FUNCTION__, h->length, buf->len);
1197        }
1198        return -EINVAL;
1199    }
1200    /*
1201     * FIXME: H-bit handling goes here
1202     */
1203#ifdef DEBUG_CONTROL
1204    log (LOG_DEBUG, "%s: control, cid = %d, Ns = %d, Nr = %d\n", __FUNCTION__,
1205         c->cid, h->Ns, h->Nr);
1206#endif
1207    if (h->Ns != t->control_rec_seq_num)
1208    {
1209        if (DEBUG)
1210            log (LOG_DEBUG,
1211                 "%s: Received out of order control packet on tunnel %d (%d != %d)\n",
1212                 __FUNCTION__, t->tid, h->Ns, t->control_rec_seq_num);
1213        if (((h->Ns < t->control_rec_seq_num) &&
1214            ((t->control_rec_seq_num - h->Ns) < 32768)) ||
1215            ((h->Ns > t->control_rec_seq_num) &&
1216            ((t->control_rec_seq_num - h->Ns) > 32768)))
1217        {
1218            /*
1219               * Woopsies, they sent us a message we should have already received
1220               * so we should send them a ZLB so they know
1221               * for sure that we already have it.
1222             */
1223#ifdef DEBUG_ZLB
1224            if (DEBUG)
1225                log (LOG_DEBUG, "%s: Sending an updated ZLB in reponse\n",
1226                     __FUNCTION__);
1227#endif
1228            zlb = new_outgoing (t);
1229            control_zlb (zlb, t, c);
1230            udp_xmit (zlb);
1231            toss (zlb);
1232        }
1233        else if (!t->control_rec_seq_num && (t->tid == -1))
1234        {
1235            /* We made this tunnel just for this message, so let's
1236               destroy it.  */
1237            c->needclose = 0;
1238            c->closing = -1;
1239        }
1240        return -EINVAL;
1241    }
1242    else
1243    {
1244        t->control_rec_seq_num++;
1245        c->cnu = -1;
1246    }
1247    /*
1248     * So we know what the other end has received
1249     * so far
1250     */
1251
1252    t->cLr = h->Nr;
1253    if (t->sanity)
1254    {
1255        if (!CTBIT (h->ver))
1256        {
1257            if (DEBUG)
1258            {
1259                log (LOG_DEBUG, "%s: Control bit not set\n", __FUNCTION__);
1260            }
1261            return -EINVAL;
1262        }
1263        if (!CLBIT (h->ver))
1264        {
1265            if (DEBUG)
1266            {
1267                log (LOG_DEBUG, "%s: Length bit not set\n", __FUNCTION__);
1268            }
1269            return -EINVAL;
1270        }
1271        if (!CFBIT (h->ver))
1272        {
1273            if (DEBUG)
1274            {
1275                log (LOG_DEBUG, "%s: Flow bit not set\n", __FUNCTION__);
1276            }
1277            return -EINVAL;
1278        }
1279        if (CVER (h->ver) != VER_L2TP)
1280        {
1281            if (DEBUG)
1282            {
1283                if (CVER (h->ver) == VER_PPTP)
1284                {
1285                    log (LOG_DEBUG,
1286                         "%s: PPTP packet received\n", __FUNCTION__);
1287                }
1288                else if (CVER (h->ver) < VER_L2TP)
1289                {
1290                    log (LOG_DEBUG,
1291                         "%s: L2F packet received\n", __FUNCTION__);
1292                }
1293                else
1294                {
1295                    log (LOG_DEBUG,
1296                         "%s: Unknown version received\n", __FUNCTION__);
1297                }
1298            }
1299            return -EINVAL;
1300        }
1301
1302    }
1303#endif
1304    return 0;
1305}
1306
1307inline int check_payload (struct buffer *buf, struct tunnel *t,
1308                          struct call *c)
1309{
1310    /*
1311     * Check if this is a valid payload
1312     * or not.  Returns 0 on success.
1313     */
1314
1315    int ehlen = MIN_PAYLOAD_HDR_LEN;
1316    struct payload_hdr *h = (struct payload_hdr *) (buf->start);
1317    if (!c)
1318    {
1319        if (DEBUG)
1320        {
1321            log (LOG_DEBUG, "%s: Aempted to send payload on tunnel\n",
1322                 __FUNCTION__);
1323        }
1324        return -EINVAL;
1325    }
1326    if (buf->len < MIN_PAYLOAD_HDR_LEN)
1327    {
1328        /* has to be at least MIN_PAYLOAD_HDR_LEN
1329           no matter what.  we'll look more later */
1330        if (DEBUG)
1331        {
1332            log (LOG_DEBUG, "%s:Recieved to small of packet\n", __FUNCTION__);
1333        }
1334        return -EINVAL;
1335    }
1336#ifdef SANITY
1337    if (t->sanity)
1338    {
1339        if (PTBIT (h->ver))
1340        {
1341            if (DEBUG)
1342            {
1343                log (LOG_DEBUG, "%s Control bit set\n", __FUNCTION__);
1344            }
1345            return -EINVAL;
1346        }
1347        if (PLBIT (h->ver))
1348            ehlen += 2;         /* Should have length information */
1349        if (PFBIT (h->ver))
1350        {
1351/*			if (!c->fbit && !c->ourfbit) {
1352				if (DEBUG)
1353					log(LOG_DEBUG,"%s: flow bit set, but no RWS negotiated.\n",__FUNCTION__);
1354				return -EINVAL;
1355			} */
1356            ehlen += 4;         /* Should have Ns and Nr too */
1357        }
1358/*		if (!PFBIT(h->ver)) {
1359			if (c->fbit || c->ourfbit) {
1360				if (DEBUG)
1361					log(LOG_DEBUG, "%s: no flow bit, but RWS was negotiated.\n",__FUNCTION__);
1362				return -EINVAL;;
1363			}
1364		} */
1365        if (PSBIT (h->ver))
1366            ehlen += 4;         /* Offset information */
1367        if (PLBIT (h->ver))
1368            ehlen += h->length; /* include length if available */
1369        if (PVER (h->ver) != VER_L2TP)
1370        {
1371            if (DEBUG)
1372            {
1373                if (PVER (h->ver) == VER_PPTP)
1374                {
1375                    log (LOG_DEBUG, "%s: PPTP packet received\n",
1376                         __FUNCTION__);
1377                }
1378                else if (CVER (h->ver) < VER_L2TP)
1379                {
1380                    log (LOG_DEBUG, "%s: L2F packet received\n",
1381                         __FUNCTION__);
1382                }
1383                else
1384                {
1385                    log (LOG_DEBUG, "%s: Unknown version received\n",
1386                         __FUNCTION__);
1387                }
1388            }
1389            return -EINVAL;
1390        }
1391        if ((buf->len < ehlen) && !PLBIT (h->ver))
1392        {
1393            if (DEBUG)
1394            {
1395                log (LOG_DEBUG, "%s payload too small (%d < %d)\n",
1396                     __FUNCTION__, buf->len, ehlen);
1397            }
1398            return -EINVAL;
1399        }
1400        if ((buf->len != h->length) && PLBIT (h->ver))
1401        {
1402            if (DEBUG)
1403            {
1404                log (LOG_DEBUG, "%s: size mismatch (%d != %d)\n",
1405                     __FUNCTION__, buf->len, h->length);
1406            }
1407            return -EINVAL;
1408        }
1409    }
1410#endif
1411    return 0;
1412}
1413inline int expand_payload (struct buffer *buf, struct tunnel *t,
1414                           struct call *c)
1415{
1416    /*
1417     * Expands payload header.  Does not check for valid header,
1418     * check_payload() should already be called as a prerequisite.
1419     */
1420    struct payload_hdr *h = (struct payload_hdr *) (buf->start);
1421    _u16 *r = (_u16 *) h;       /* Nice to have raw word pointers */
1422    struct payload_hdr *new_hdr;
1423    int ehlen = 0;
1424    /*
1425     * We first calculate our offset
1426     */
1427    if (!PLBIT (h->ver))
1428        ehlen += 2;             /* Should have length information */
1429    if (!PFBIT (h->ver))
1430        ehlen += 4;             /* Should have Ns and Nr too */
1431    if (!PSBIT (h->ver))
1432        ehlen += 4;             /* Offset information */
1433    if (ehlen)
1434    {
1435        /*
1436         * If this payload is missing any information, we'll
1437         * fill it in
1438         */
1439        new_hdr = (struct payload_hdr *) (buf->start - ehlen);
1440        if ((void *) new_hdr < (void *) buf->rstart)
1441        {
1442            log (LOG_WARN, "%s: not enough space to decompress frame\n",
1443                 __FUNCTION__);
1444            return -EINVAL;
1445
1446        };
1447        new_hdr->ver = *r;
1448        if (PLBIT (new_hdr->ver))
1449        {
1450            r++;
1451            new_hdr->length = *r;
1452        }
1453        else
1454        {
1455            new_hdr->length = buf->len + ehlen;
1456        };
1457        r++;
1458        new_hdr->tid = *r;
1459        r++;
1460        new_hdr->cid = *r;
1461        if (PFBIT (new_hdr->ver))
1462        {
1463            r++;
1464            new_hdr->Ns = *r;
1465            r++;
1466            new_hdr->Nr = *r;
1467        }
1468        else
1469        {
1470            new_hdr->Nr = c->data_seq_num;
1471            new_hdr->Ns = c->data_rec_seq_num;
1472        };
1473        if (PSBIT (new_hdr->ver))
1474        {
1475            r++;
1476            new_hdr->o_size = *r;
1477            r++;
1478            new_hdr->o_pad = *r;
1479        }
1480        else
1481        {
1482            new_hdr->o_size = 0;
1483            new_hdr->o_pad = 0;
1484        }
1485    }
1486    else
1487        new_hdr = h;
1488    /*
1489       * Handle sequence numbers
1490       *
1491     */
1492/*  JLM	if (PRBIT(new_hdr->ver)) {
1493		if (c->pSr > new_hdr->Ns) {
1494			log(LOG_DEBUG, "%s: R-bit set with Ns < pSr!\n",__FUNCTION__);
1495			return -EINVAL;
1496		}
1497#ifdef DEBUG_FLOW
1498		log(LOG_DEBUG, "%s: R-bit set on packet %d\n",__FUNCTION__,new_hdr->Ns);
1499#endif
1500		c->pSr=new_hdr->Ns;
1501	} */
1502#ifdef DEBUG_PAYLOAD
1503    log (LOG_DEBUG, "%s: payload, cid = %d, Ns = %d, Nr = %d\n", __FUNCTION__,
1504         c->cid, new_hdr->Ns, new_hdr->Nr);
1505#endif
1506    if (new_hdr->Ns != c->data_seq_num)
1507    {
1508        /* RFC1982-esque comparison of serial numbers */
1509        if (((new_hdr->Ns < c->data_rec_seq_num) &&
1510            ((c->data_rec_seq_num - new_hdr->Ns) < 32768)) ||
1511            ((new_hdr->Ns > c->data_rec_seq_num) &&
1512            ((c->data_rec_seq_num - new_hdr->Ns) > 32768)))
1513        {
1514#ifdef DEBUG_FLOW
1515            if (DEBUG)
1516                log (LOG_DEBUG,
1517                     "%s: Already seen this packet before (%d < %d)\n",
1518                     __FUNCTION__, new_hdr->Ns, c->pSr);
1519#endif
1520            return -EINVAL;
1521        }
1522        /* Foxconn modified start pling 06/10/2011 */
1523        /* Disable seq number check, to avoid L2TP disconnect in heavy traffic */
1524        else /* if (new_hdr->Ns <= c->data_rec_seq_num + PAYLOAD_FUDGE) */
1525        /* Foxconn modified end pling 06/10/2011 */
1526        {
1527            /* FIXME: I should buffer for out of order packets */
1528#ifdef DEBUG_FLOW
1529            if (DEBUG)
1530                log (LOG_DEBUG,
1531                     "%s: Oops, lost a packet or two (%d != %d).  continuing...\n",
1532                     __FUNCTION__, new_hdr->Ns, c->pSr);
1533#endif
1534            c->data_rec_seq_num = new_hdr->Ns;
1535        }
1536        /* Foxconn removed start pling 06/10/2011 */
1537        /* Disable seq number check, to avoid L2TP disconnect in heavy traffic */
1538#if 0
1539        else
1540        {
1541#ifdef DEBUG_FLOW
1542            if (DEBUG)
1543                log (LOG_DEBUG,
1544                     "%s: Received out of order payload packet (%d != %d)\n",
1545                     __FUNCTION__, new_hdr->Ns, c->pSr);
1546#endif
1547            return -EINVAL;
1548        }
1549#endif
1550        /* Foxconn removed end pling 06/10/2011 */
1551    }
1552    else
1553    {
1554        c->data_rec_seq_num++;
1555        c->pnu = -1;
1556    }
1557    /*
1558     * Check to see what the last thing
1559     * we got back was
1560     */
1561    c->pLr = new_hdr->Nr;
1562    buf->start = new_hdr;
1563    buf->len += ehlen;
1564    return 0;
1565}
1566
1567void send_zlb (void *data)
1568{
1569    /*
1570     * Send a ZLB.  This procedure should be schedule()able
1571     */
1572    struct call *c;
1573    struct tunnel *t;
1574    struct buffer *buf;
1575    c = (struct call *) data;
1576    if (!c)
1577    {
1578        log (LOG_WARN, "%s: called on NULL call\n", __FUNCTION__);
1579        return;
1580    }
1581    t = c->container;
1582    if (!t)
1583    {
1584        log (LOG_WARN, "%s: called on call with NULL container\n",
1585             __FUNCTION__);
1586        return;
1587    }
1588    /* Update the counter so we know what Lr was when we last transmited a ZLB */
1589    c->prx = c->data_rec_seq_num;
1590    buf = new_payload (t->peer);
1591    add_payload_hdr (t, c, buf);
1592    c->data_seq_num--;                   /* We don't increment on ZLB's */
1593    c->zlb_xmit = NULL;
1594#ifdef DEBUG_ZLB
1595    log (LOG_DEBUG, "%s: sending payload ZLB\n", __FUNCTION__);
1596#endif
1597    udp_xmit (buf);
1598    toss (buf);
1599}
1600
1601inline int write_packet (struct buffer *buf, struct tunnel *t, struct call *c,
1602                         int convert)
1603{
1604    /*
1605     * Write a packet, doing sync->async conversion if
1606     * necessary
1607     */
1608    int x;
1609    unsigned char e;
1610    int err;
1611    static unsigned char wbuf[MAX_RECV_SIZE];
1612    int pos = 0;
1613
1614    if (c->fd < 0)
1615    {
1616        if (DEBUG)
1617            log (LOG_DEBUG, "%s: tty is not open yet.\n", __FUNCTION__);
1618        return -EIO;
1619    }
1620    /* Modified by MJ.*/
1621    //log (LOG_DEBUG, "-> enter write_packet.\n");
1622
1623
1624    /*
1625     * Skip over header
1626     */
1627    buf->start += sizeof (struct payload_hdr);
1628    buf->len -= sizeof (struct payload_hdr);
1629
1630    c->rx_pkts++;
1631    c->rx_bytes += buf->len;
1632
1633    /*
1634     * FIXME:  What about offset?
1635     */
1636
1637    while (!convert)
1638    {
1639        /* We are given async frames, so write them
1640           directly to the tty */
1641        err = write (c->fd, buf->start, buf->len);
1642
1643        /*Foxconn, by MJ., I use STDOUT to replace the fd for writting.*/
1644        //log (LOG_DEBUG, "write %d bytes to tty:%d\n", err,c->fd);
1645
1646
1647        if (err == buf->len)
1648        {
1649            return 0;
1650        }
1651        else if (err == 0)
1652        {
1653            log (LOG_WARN, "%s: wrote no bytes of async packet\n",
1654                 __FUNCTION__);
1655            return -EINVAL;
1656        }
1657        else if (err < 0)
1658        {
1659            if ((errno == EAGAIN) || (errno == EINTR))
1660            {
1661                continue;
1662            }
1663            else
1664            {
1665                log (LOG_WARN, "%s: async write failed: %s\n", __FUNCTION__,
1666                     strerror (errno));
1667            }
1668        }
1669        else if (err < buf->len)
1670        {
1671            log (LOG_WARN, "%s: short write (%d of %d bytes)\n", __FUNCTION__,
1672                 err, buf->len);
1673            return -EINVAL;
1674        }
1675        else if (err > buf->len)
1676        {
1677            log (LOG_WARN, "%s: write returned LONGER than buffer length?\n",
1678                 __FUNCTION__);
1679            return -EINVAL;
1680        }
1681    }
1682
1683    /*
1684     * sync->async conversion if we're doing sync frames
1685     * since the pppd driver will expect async frames
1686     * Write leading flag character
1687     */
1688
1689    add_fcs (buf);
1690    e = PPP_FLAG;
1691    wbuf[pos++] = e;
1692    for (x = 0; x < buf->len; x++)
1693    {
1694        e = *((char *) buf->start + x);
1695        if ((e < 0x20) || (e == PPP_ESCAPE) || (e == PPP_FLAG))
1696        {
1697            /* Escape this */
1698            e = e ^ 0x20;
1699            wbuf[pos++] = PPP_ESCAPE;
1700        }
1701        wbuf[pos++] = e;
1702
1703    }
1704    wbuf[pos++] = PPP_FLAG;
1705    x = write (c->fd, wbuf, pos);
1706
1707    /*Foxconn, by MJ., for Debugging. */
1708    //log (LOG_DEBUG, "write %d bytes to ttyfd:%d\n", x, c->fd);
1709
1710
1711    if (x < pos)
1712    {
1713        if (!(errno == EINTR) && !(errno == EAGAIN))
1714        {
1715            /*
1716               * I guess pppd died.  we'll pretend
1717               * everything ended normally
1718             */
1719            if (DEBUG)
1720                log (LOG_WARN, "%s: %s(%d)\n", __FUNCTION__, strerror (errno),
1721                     errno);
1722            c->needclose = -1;
1723            c->fd = -1;
1724            return -EIO;
1725        }
1726    }
1727    return 0;
1728}
1729
1730void handle_special (struct buffer *buf, struct call *c, _u16 call)
1731{
1732    /*
1733       * This procedure is called when we have received a packet
1734       * on a call which doesn't exist in our tunnel.  We want to
1735       * send back a ZLB to keep the tunnel alive, on that particular
1736       * call if it was a CDN, otherwise, send a CDN to notify them
1737       * that this call has been terminated.
1738     */
1739    struct buffer *outgoing;
1740    struct tunnel *t = c->container;
1741    /* Don't do anything unless it's a control packet */
1742    if (!CTBIT (*((_u16 *) buf->start)))
1743        return;
1744    /* Temporarily, we make the tunnel have cid of call instead of 0,
1745       but we need to stop any scheduled events (like Hello's in
1746       particular) which might use this value */
1747    c->cid = call;
1748    if (!check_control (buf, t, c))
1749    {
1750        if (buf->len == sizeof (struct control_hdr))
1751        {
1752            /* If it's a ZLB, we ignore it */
1753            if (debug_tunnel)
1754                log (LOG_DEBUG, "%s: ZLB for closed call\n", __FUNCTION__);
1755            c->cid = 0;
1756            return;
1757        }
1758        /* Make a packet with the specified call number */
1759        outgoing = new_outgoing (t);
1760        /* FIXME: If I'm not a CDN, I need to send a CDN */
1761        control_zlb (buf, t, c);
1762        c->cid = 0;
1763        udp_xmit (buf);
1764        toss (buf);
1765    }
1766    else
1767    {
1768        c->cid = 0;
1769        if (debug_tunnel)
1770            log (LOG_DEBUG, "%s: invalid control packet\n", __FUNCTION__);
1771    }
1772}
1773
1774inline int handle_packet (struct buffer *buf, struct tunnel *t,
1775                          struct call *c)
1776{
1777    int res;
1778    struct timeval tv;
1779    if (CTBIT (*((_u16 *) buf->start)))
1780    {
1781        /* We have a control packet */
1782        if (!check_control (buf, t, c))
1783        {
1784            c->msgtype = -1;
1785            if (buf->len == sizeof (struct control_hdr))
1786            {
1787#ifdef DEBUG_ZLB
1788                log (LOG_DEBUG, "%s: control ZLB received\n", __FUNCTION__);
1789#endif
1790                t->control_rec_seq_num--;
1791                c->cnu = 0;
1792                if (c->needclose && c->closing)
1793                {
1794                    if (c->container->cLr >= c->closeSs)
1795                    {
1796#ifdef DEBUG_ZLB
1797                        log (LOG_DEBUG, "%s: ZLB for closing message found\n",
1798                             __FUNCTION__);
1799#endif
1800                        c->needclose = 0;
1801                        /* Trigger final closing of call */
1802                    }
1803                }
1804                return 0;
1805            }
1806            else if (!handle_avps (buf, t, c))
1807            {
1808                return control_finish (t, c);
1809            }
1810            else
1811            {
1812                if (debug_tunnel)
1813                    log (LOG_DEBUG, "%s: bad AVP handling!\n", __FUNCTION__);
1814                return -EINVAL;
1815            }
1816        }
1817        else
1818        {
1819            log (LOG_DEBUG, "%s: bad control packet!\n", __FUNCTION__);
1820            return -EINVAL;
1821        }
1822    }
1823    else
1824    {
1825        if (!check_payload (buf, t, c))
1826        {
1827            if (!expand_payload (buf, t, c))
1828            {
1829                if (buf->len > sizeof (struct payload_hdr))
1830                {
1831/*					if (c->throttle) {
1832						if (c->pSs > c->pLr + c->rws) {
1833#ifdef DEBUG_FLOW
1834							log(LOG_DEBUG, "%s: not yet dethrottling call\n",__FUNCTION__);
1835#endif
1836						} else {
1837#ifdef DEBUG_FLOW
1838							log(LOG_DEBUG, "%s: dethrottling call\n",__FUNCTION__);
1839#endif
1840							if (c->dethrottle) deschedule(c->dethrottle);
1841							c->dethrottle=NULL;
1842							c->throttle = 0;
1843						}
1844					} */
1845/*	JLM				res = write_packet(buf,t,c, c->frame & SYNC_FRAMING); */
1846                    res = write_packet (buf, t, c, SYNC_FRAMING);
1847                    if (res)
1848                        return res;
1849                    /*
1850                       * Assuming we wrote to the ppp driver okay, we should
1851                       * do something about ZLB's unless *we* requested no
1852                       * window size or if they we have turned off our fbit.
1853                     */
1854
1855/*					if (c->ourfbit && (c->ourrws > 0)) {
1856						if (c->pSr >= c->prx + c->ourrws - 2) {
1857						We've received enough to fill our receive window.  At
1858						this point, we should immediately send a ZLB!
1859#ifdef DEBUG_ZLB
1860							log(LOG_DEBUG, "%s: Sending immediate ZLB!\n",__FUNCTION__);
1861#endif
1862							if (c->zlb_xmit) {
1863							Deschedule any existing zlb_xmit's
1864								deschedule(c->zlb_xmit);
1865								c->zlb_xmit = NULL;
1866							}
1867							send_zlb((void *)c);
1868						} else {
1869						We need to schedule sending a ZLB.  FIXME:  Should
1870						be 1/4 RTT instead, when rate adaptive stuff is
1871						in place. Spec allows .5 seconds though
1872							tv.tv_sec = 0;
1873							tv.tv_usec = 500000;
1874							if (c->zlb_xmit)
1875								deschedule(c->zlb_xmit);
1876#ifdef DEBUG_ZLB
1877							log(LOG_DEBUG, "%s: scheduling ZLB\n",__FUNCTION__);
1878#endif
1879							c->zlb_xmit = schedule(tv, &send_zlb, (void *)c);
1880						}
1881					} */
1882                    return 0;
1883                }
1884                else if (buf->len == sizeof (struct payload_hdr))
1885                {
1886#ifdef DEBUG_ZLB
1887                    log (LOG_DEBUG, "%s: payload ZLB received\n",
1888                         __FUNCTION__);
1889#endif
1890/*					if (c->throttle) {
1891						if (c->pSs > c->pLr + c->rws) {
1892#ifdef DEBUG_FLOW
1893							log(LOG_DEBUG, "%s: not yet dethrottling call\n",__FUNCTION__);
1894#endif
1895						} else {
1896#ifdef DEBUG_FLOW
1897							log(LOG_DEBUG, "%s: dethrottling call\n",__FUNCTION__);
1898#endif
1899							if (c->dethrottle)
1900								deschedule(c->dethrottle);
1901							c->dethrottle=NULL;
1902							c->throttle = 0;
1903						}
1904					} */
1905                    c->data_rec_seq_num--;
1906                    return 0;
1907                }
1908                else
1909                {
1910                    log (LOG_DEBUG, "%s: payload too small!\n", __FUNCTION__);
1911                    return -EINVAL;
1912                }
1913            }
1914            else
1915            {
1916                if (debug_tunnel)
1917                    log (LOG_DEBUG, "%s: unable to expand payload!\n",
1918                         __FUNCTION__);
1919                return -EINVAL;
1920            }
1921        }
1922        else
1923        {
1924            log (LOG_DEBUG, "%s: invalid payload packet!\n", __FUNCTION__);
1925            return -EINVAL;
1926        }
1927    }
1928}
1929
1930/* foxconn wklin added start, 04/12/2011 */
1931void connect_pppunit(void)
1932{
1933#define cprintf(level, fmt, args...) do { \
1934	FILE *fp = fopen("/dev/console", "w"); \
1935	if (fp) { \
1936		fprintf(fp, fmt , ## args); \
1937		fclose(fp); \
1938	} \
1939} while (0)
1940    static int connected = 0;
1941    int ppp_unit = 0;
1942    if (connected) return;
1943    if (ppp_fd < 0 || (ioctl(ppp_fd, PPPIOCCONNECT, &ppp_unit)) < 0)
1944        ; /* cprintf(LOG_DEBUG, "Couldn't connect channel to ppp0\n"); */
1945    else
1946        connected = 1;
1947    return;
1948}
1949/* foxconn wklin added end, 04/12/2011 */
1950