http://downloads.netgear.com/files/GPL/GPL_Source_V361j_DM111PSP_series_consumer_rele...
[bcm963xx.git] / userapps / opensource / ppp / pppoe / ipcp.c
1 /*
2  * ipcp.c - PPP IP Control Protocol.
3  *
4  * Copyright (c) 1989 Carnegie Mellon University.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms are permitted
8  * provided that the above copyright notice and this paragraph are
9  * duplicated in all such forms and that any documentation,
10  * advertising materials, and other materials related to such
11  * distribution and use acknowledge that the software was developed
12  * by Carnegie Mellon University.  The name of the
13  * University may not be used to endorse or promote products derived
14  * from this software without specific prior written permission.
15  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
17  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
18  */
19
20 #define RCSID   "$Id: ipcp.c,v 1.6 2006/12/14 05:58:40 andylin Exp $"
21
22 /*
23  * TODO:
24  */
25
26 #include <stdio.h>
27 #include <string.h>
28 #include <stdlib.h>
29 #include <netdb.h>
30 #include <sys/param.h>
31 #include <sys/types.h>
32 #include <sys/socket.h>
33 #include <netinet/in.h>
34 #include <arpa/inet.h>
35
36 #include "pppd.h"
37 #include "fsm.h"
38 #include "ipcp.h"
39 #include "pathnames.h"
40
41 // brcm
42 #include <syscall.h>
43 #include <syslog.h>
44
45 static const char rcsid[] = RCSID;
46
47 /* global vars */
48 ipcp_options ipcp_wantoptions[NUM_PPP]; /* Options that we want to request */
49 ipcp_options ipcp_gotoptions[NUM_PPP];  /* Options that peer ack'd */
50 ipcp_options ipcp_allowoptions[NUM_PPP]; /* Options we allow peer to request */
51 ipcp_options ipcp_hisoptions[NUM_PPP];  /* Options that we ack'd */
52
53 u_int32_t netmask = 0;          /* IP netmask to set on interface */
54
55 bool    disable_defaultip = 0;  /* Don't use hostname for default IP adrs */
56
57 //Charles 11/30/2003, add for unnumbered PPP
58 bool unnumbered=0;
59 char wan_IP[16]="";
60 char wan_submask[16]="";
61 extern int ppp_session;
62 #if defined(ODM_LANG_LLL)
63 extern int glbppppid;
64 extern int got_ppp_down;
65 #endif
66 /* Hook for a plugin to know when IP protocol has come up */
67 void (*ip_up_hook) __P((void)) = NULL;
68
69 /* Hook for a plugin to know when IP protocol has come down */
70 void (*ip_down_hook) __P((void)) = NULL;
71
72 /* Hook for a plugin to choose the remote IP address */
73 void (*ip_choose_hook) __P((u_int32_t *)) = NULL;
74
75 /* local vars */
76 static int default_route_set[NUM_PPP];  /* Have set up a default route */
77 static int proxy_arp_set[NUM_PPP];      /* Have created proxy arp entry */
78 static bool usepeerdns=1;                       /* Ask peer for DNS addrs */
79 static int ipcp_is_up;                  /* have called np_up() */
80 static bool ask_for_local;              /* request our address from peer */
81 static char vj_value[8];                /* string form of vj option value */
82 static char netmask_str[20];            /* string form of netmask value */
83
84 /*
85  * Callbacks for fsm code.  (CI = Configuration Information)
86  */
87 static void ipcp_resetci __P((fsm *));  /* Reset our CI */
88 static int  ipcp_cilen __P((fsm *));            /* Return length of our CI */
89 static void ipcp_addci __P((fsm *, u_char *, int *)); /* Add our CI */
90 static int  ipcp_ackci __P((fsm *, u_char *, int));     /* Peer ack'd our CI */
91 static int  ipcp_nakci __P((fsm *, u_char *, int));     /* Peer nak'd our CI */
92 static int  ipcp_rejci __P((fsm *, u_char *, int));     /* Peer rej'd our CI */
93 static int  ipcp_reqci __P((fsm *, u_char *, int *, int)); /* Rcv CI */
94 static void ipcp_up __P((fsm *));               /* We're UP */
95 static void ipcp_down __P((fsm *));             /* We're DOWN */
96 static void ipcp_finished __P((fsm *)); /* Don't need lower layer */
97
98 fsm ipcp_fsm[NUM_PPP];          /* IPCP fsm structure */
99
100 static fsm_callbacks ipcp_callbacks = { /* IPCP callback routines */
101     ipcp_resetci,               /* Reset our Configuration Information */
102     ipcp_cilen,                 /* Length of our Configuration Information */
103     ipcp_addci,                 /* Add our Configuration Information */
104     ipcp_ackci,                 /* ACK our Configuration Information */
105     ipcp_nakci,                 /* NAK our Configuration Information */
106     ipcp_rejci,                 /* Reject our Configuration Information */
107     ipcp_reqci,                 /* Request peer's Configuration Information */
108     ipcp_up,                    /* Called when fsm reaches OPENED state */
109     ipcp_down,                  /* Called when fsm leaves OPENED state */
110     NULL,                       /* Called when we want the lower layer up */
111     ipcp_finished,              /* Called when we want the lower layer down */
112     NULL,                       /* Called when Protocol-Reject received */
113     NULL,                       /* Retransmission is necessary */
114     NULL,                       /* Called to handle protocol-specific codes */
115     "IPCP"                      /* String name of protocol */
116 };
117
118 /*
119  * Command-line options.
120  */
121 static int setvjslots __P((char **));
122 static int setdnsaddr __P((char **));
123 static int setwinsaddr __P((char **));
124 static int setnetmask __P((char **));
125 // brcm
126 int setipaddr __P((char *, char **, int));
127 // brcm
128 static void printipaddr __P((option_t *, void (*)(void *, char *,...),void *));
129
130 static option_t ipcp_option_list[] = {
131     { "noip", o_bool, &ipcp_protent.enabled_flag,
132       "Disable IP and IPCP" },
133     { "-ip", o_bool, &ipcp_protent.enabled_flag,
134       "Disable IP and IPCP", OPT_ALIAS },
135
136     { "novj", o_bool, &ipcp_wantoptions[0].neg_vj,
137       "Disable VJ compression", OPT_A2CLR, &ipcp_allowoptions[0].neg_vj },
138     { "-vj", o_bool, &ipcp_wantoptions[0].neg_vj,
139       "Disable VJ compression", OPT_ALIAS | OPT_A2CLR,
140       &ipcp_allowoptions[0].neg_vj },
141
142     { "novjccomp", o_bool, &ipcp_wantoptions[0].cflag,
143       "Disable VJ connection-ID compression", OPT_A2CLR,
144       &ipcp_allowoptions[0].cflag },
145     { "-vjccomp", o_bool, &ipcp_wantoptions[0].cflag,
146       "Disable VJ connection-ID compression", OPT_ALIAS | OPT_A2CLR,
147       &ipcp_allowoptions[0].cflag },
148
149     { "vj-max-slots", o_special, (void *)setvjslots,
150       "Set maximum VJ header slots",
151       OPT_PRIO | OPT_A2STRVAL | OPT_STATIC, vj_value },
152
153     { "ipcp-accept-local", o_bool, &ipcp_wantoptions[0].accept_local,
154       "Accept peer's address for us", 1 },
155     { "ipcp-accept-remote", o_bool, &ipcp_wantoptions[0].accept_remote,
156       "Accept peer's address for it", 1 },
157
158     { "ipparam", o_string, &ipparam,
159       "Set ip script parameter", OPT_PRIO },
160
161     { "noipdefault", o_bool, &disable_defaultip,
162       "Don't use name for default IP adrs", 1 },
163
164     { "ms-dns", 1, (void *)setdnsaddr,
165       "DNS address for the peer's use" },
166     { "dns-addr", 1, setdnsaddr,            /*wilson add for MS-CHAPv2, 05/26/2005*/
167       "DNS address for the peer's use" },   /*wilson add for MS-CHAPv2, 05/26/2005*/
168     { "ms-wins", 1, (void *)setwinsaddr,
169       "Nameserver for SMB over TCP/IP for peer" },
170
171     { "ipcp-restart", o_int, &ipcp_fsm[0].timeouttime,
172       "Set timeout for IPCP", OPT_PRIO },
173     { "ipcp-max-terminate", o_int, &ipcp_fsm[0].maxtermtransmits,
174       "Set max #xmits for term-reqs", OPT_PRIO },
175     { "ipcp-max-configure", o_int, &ipcp_fsm[0].maxconfreqtransmits,
176       "Set max #xmits for conf-reqs", OPT_PRIO },
177     { "ipcp-max-failure", o_int, &ipcp_fsm[0].maxnakloops,
178       "Set max #conf-naks for IPCP", OPT_PRIO },
179
180     { "defaultroute", o_bool, &ipcp_wantoptions[0].default_route,
181       "Add default route", OPT_ENABLE|1, &ipcp_allowoptions[0].default_route },
182     { "nodefaultroute", o_bool, &ipcp_allowoptions[0].default_route,
183       "disable defaultroute option", OPT_A2CLR,
184       &ipcp_wantoptions[0].default_route },
185     { "-defaultroute", o_bool, &ipcp_allowoptions[0].default_route,
186       "disable defaultroute option", OPT_ALIAS | OPT_A2CLR,
187       &ipcp_wantoptions[0].default_route },
188
189     { "proxyarp", o_bool, &ipcp_wantoptions[0].proxy_arp,
190       "Add proxy ARP entry", OPT_ENABLE|1, &ipcp_allowoptions[0].proxy_arp },
191     { "noproxyarp", o_bool, &ipcp_allowoptions[0].proxy_arp,
192       "disable proxyarp option", OPT_A2CLR,
193       &ipcp_wantoptions[0].proxy_arp },
194     { "-proxyarp", o_bool, &ipcp_allowoptions[0].proxy_arp,
195       "disable proxyarp option", OPT_ALIAS | OPT_A2CLR,
196       &ipcp_wantoptions[0].proxy_arp },
197
198     { "usepeerdns", o_bool, &usepeerdns,
199       "Ask peer for DNS address(es)", 1 },
200
201     { "netmask", o_special, (void *)setnetmask,
202       "set netmask", OPT_PRIO | OPT_A2STRVAL | OPT_STATIC, netmask_str },
203
204     { "IP addresses", o_wild, (void *) &setipaddr,
205       "set local and remote IP addresses",
206       OPT_NOARG | OPT_A2PRINTER, (void *) &printipaddr },
207
208     { NULL }
209 };
210
211 /*
212  * Protocol entry points from main code.
213  */
214 static void ipcp_init __P((int));
215 static void ipcp_open __P((int));
216 static void ipcp_close __P((int, char *));
217 static void ipcp_lowerup __P((int));
218 static void ipcp_lowerdown __P((int));
219 static void ipcp_input __P((int, u_char *, int));
220 static void ipcp_protrej __P((int));
221 static int  ipcp_printpkt __P((u_char *, int,
222                                void (*) __P((void *, char *, ...)), void *));
223 static void ip_check_options __P((void));
224 static int  ip_demand_conf __P((int));
225 static int  ip_active_pkt __P((u_char *, int));
226 static void create_resolv __P((u_int32_t, u_int32_t));
227
228 struct protent ipcp_protent = {
229     PPP_IPCP,
230     ipcp_init,
231     ipcp_input,
232     ipcp_protrej,
233     ipcp_lowerup,
234     ipcp_lowerdown,
235     ipcp_open,
236     ipcp_close,
237     ipcp_printpkt,
238     NULL,
239     1,
240     "IPCP",
241     "IP",
242     ipcp_option_list,
243     ip_check_options,
244     ip_demand_conf,
245     ip_active_pkt
246 };
247
248 static void ipcp_clear_addrs __P((int, u_int32_t, u_int32_t));
249 static void ipcp_script __P((char *));          /* Run an up/down script */
250 static void ipcp_script_done __P((void *));
251
252 /*
253  * Lengths of configuration options.
254  */
255 #define CILEN_VOID      2
256 #define CILEN_COMPRESS  4       /* min length for compression protocol opt. */
257 #define CILEN_VJ        6       /* length for RFC1332 Van-Jacobson opt. */
258 #define CILEN_ADDR      6       /* new-style single address option */
259 #define CILEN_ADDRS     10      /* old-style dual address option */
260 //Charles 07/07/2003
261 #define PPP_HISTORY_REC_MAX 100
262
263 #define CODENAME(x)     ((x) == CONFACK ? "ACK" : \
264                          (x) == CONFNAK ? "NAK" : "REJ")
265
266 /*
267  * This state variable is used to ensure that we don't
268  * run an ipcp-up/down script while one is already running.
269  */
270 static enum script_state {
271     s_down,
272     s_up,
273 } ipcp_script_state;
274 static pid_t ipcp_script_pid;
275
276 // brcm
277 static char local_ip[32]="";
278 static char subnet_ip[32]="";
279 static char router_ip[32]="";
280 static char dns_ip[64]="";
281 static int  glbpppgw = 0;
282
283 // brcm2
284 int redisconn=0;
285 /* Charles 07/07/2003, Time when the link went up/down. */
286 time_t ppp_start_time;  
287 time_t ppp_end_time;            
288 int ppp_hist_num=0;
289 struct time_rec {
290         time_t start;
291         time_t end;
292 };
293
294 struct time_rec ppp_history[PPP_HISTORY_REC_MAX];
295
296 /*
297  * ODM Charles 07/07/2003
298  * Write PPP connection start time and end time to a history file. 
299  * This only make sense while PPP is UP
300  */
301  void write_conn_time(time_t start) {
302         char fname[50];
303         FILE *fd;
304
305         //sprintf(fname, "/var/ppp%d_connect_time",req_unit);
306         sprintf(fname, "/var/ppp_%s_connect_time",req_name);
307         if((fd=fopen(fname, "w"))) {
308                 fwrite(&start, 4, 1, fd);
309                 fclose(fd);
310         }
311         else
312                 printf("PPP: Error in writing connect history log file!Open log file failed!!!\n");
313 }
314
315 /*
316  * ODM Charles 07/07/2003
317  * Write PPP connection start time and end time to a history file. 
318  * The size for one record is 8 bytes, so there will not be memory problems even if there are 500 records 
319  * (it takes 4KB in this case). If this history log has to be saved to PSI, we should setup a record limit. 
320  */
321  void write_conn_history(time_t start, time_t end) {
322         char fname[50];
323         FILE *fd;
324         int i;
325
326         //sprintf(fname, "/var/ppp%d_connect_history",req_unit);
327         sprintf(fname, "/var/ppp_%s_connect_history",req_name);
328         //append the start time and end time to the end of file.
329         if(end > start) {
330                 //add this record to the array, shift as necessary (it's better to use a circular queue, but for simplicity...)
331                 if(ppp_hist_num<PPP_HISTORY_REC_MAX) {
332                         ppp_history[ppp_hist_num].start=start;
333                         ppp_history[ppp_hist_num++].end=end;
334                 }
335                 else {  //record number exceeds upper limit
336                         //forward shift the array (keep the newest record in the tail)
337                         for(i=0;i<PPP_HISTORY_REC_MAX-1;i++) {
338                                 ppp_history[i].start=ppp_history[i+1].start;
339                                 ppp_history[i].end=ppp_history[i+1].end;
340                         }
341                         ppp_history[ppp_hist_num-1].start=start;
342                         ppp_history[ppp_hist_num-1].end=end;
343                 }
344                 if((fd=fopen(fname, "w"))) {
345                         //dump the record to file, in "descending" order (newest--->oldest)
346                         for(i=ppp_hist_num-1;i>=0;i--) {
347                                 fwrite(&ppp_history[i].start, 4, 1, fd);
348                                 fwrite(&ppp_history[i].end, 4, 1, fd);
349                         }
350                         fclose(fd);
351                 }
352                 else
353                         printf("PPP: Error in writing connect history log file!Open log file failed!!!\n");
354         }
355         else
356                 printf("PPP: Error in writing connect history log! the start time > end time!!!\n");
357 }
358
359
360 /*
361  * Make a string representation of a network IP address.
362  */
363 char *
364 ip_ntoa(ipaddr)
365 u_int32_t ipaddr;
366 {
367     static char b[64];
368
369     slprintf(b, sizeof(b), "%I", ipaddr);
370     return b;
371 }
372
373 /*
374  * Option parsing.
375  */
376
377 /*
378  * setvjslots - set maximum number of connection slots for VJ compression
379  */
380 static int
381 setvjslots(argv)
382     char **argv;
383 {
384     int value;
385
386     if (!int_option(*argv, &value))
387         return 0;
388     if (value < 2 || value > 16) {
389         option_error("vj-max-slots value must be between 2 and 16");
390         return 0;
391     }
392     ipcp_wantoptions [0].maxslotindex =
393         ipcp_allowoptions[0].maxslotindex = value - 1;
394     slprintf(vj_value, sizeof(vj_value), "%d", value);
395     return 1;
396 }
397
398 /*
399  * setdnsaddr - set the dns address(es)
400  */
401 static int
402 setdnsaddr(argv)
403     char **argv;
404 {
405     u_int32_t dns;
406     struct hostent *hp;
407
408     dns = inet_addr(*argv);
409     if (dns == (u_int32_t) -1) {
410         if ((hp = gethostbyname(*argv)) == NULL) {
411             option_error("invalid address parameter '%s' for ms-dns option",
412                          *argv);
413             return 0;
414         }
415         dns = *(u_int32_t *)hp->h_addr;
416     }
417
418     /* We take the last 2 values given, the 2nd-last as the primary
419        and the last as the secondary.  If only one is given it
420        becomes both primary and secondary. */
421     if (ipcp_allowoptions[0].dnsaddr[1] == 0)
422         ipcp_allowoptions[0].dnsaddr[0] = dns;
423     else
424         ipcp_allowoptions[0].dnsaddr[0] = ipcp_allowoptions[0].dnsaddr[1];
425
426     /* always set the secondary address value. */
427     ipcp_allowoptions[0].dnsaddr[1] = dns;
428
429     return (1);
430 }
431
432 /*
433  * setwinsaddr - set the wins address(es)
434  * This is primrarly used with the Samba package under UNIX or for pointing
435  * the caller to the existing WINS server on a Windows NT platform.
436  */
437 static int
438 setwinsaddr(argv)
439     char **argv;
440 {
441     u_int32_t wins;
442     struct hostent *hp;
443
444     wins = inet_addr(*argv);
445     if (wins == (u_int32_t) -1) {
446         if ((hp = gethostbyname(*argv)) == NULL) {
447             option_error("invalid address parameter '%s' for ms-wins option",
448                          *argv);
449             return 0;
450         }
451         wins = *(u_int32_t *)hp->h_addr;
452     }
453
454     /* We take the last 2 values given, the 2nd-last as the primary
455        and the last as the secondary.  If only one is given it
456        becomes both primary and secondary. */
457     if (ipcp_allowoptions[0].winsaddr[1] == 0)
458         ipcp_allowoptions[0].winsaddr[0] = wins;
459     else
460         ipcp_allowoptions[0].winsaddr[0] = ipcp_allowoptions[0].winsaddr[1];
461
462     /* always set the secondary address value. */
463     ipcp_allowoptions[0].winsaddr[1] = wins;
464
465     return (1);
466 }
467
468 /*
469  * setipaddr - Set the IP address
470  * If doit is 0, the call is to check whether this option is
471  * potentially an IP address specification.
472  */
473 int
474 setipaddr(arg, argv, doit)
475     char *arg;
476     char **argv;
477     int doit;
478 {
479     struct hostent *hp;
480     char *colon;
481     u_int32_t local, remote;
482     ipcp_options *wo = &ipcp_wantoptions[0];
483     static int prio_local = 0, prio_remote = 0;
484
485     /*
486      * IP address pair separated by ":".
487      */
488     if ((colon = strchr(arg, ':')) == NULL)
489         return 0;
490     if (!doit)
491         return 1;
492   
493     /*
494      * If colon first character, then no local addr.
495      */
496     if (colon != arg && option_priority >= prio_local) {
497         *colon = '\0';
498         if ((local = inet_addr(arg)) == (u_int32_t) -1) {
499             if ((hp = gethostbyname(arg)) == NULL) {
500                 option_error("unknown host: %s", arg);
501                 return 0;
502             }
503             local = *(u_int32_t *)hp->h_addr;
504         }
505         if (bad_ip_adrs(local)) {
506             option_error("bad local IP address %s", ip_ntoa(local));
507             return 0;
508         }
509         if (local != 0)
510             wo->ouraddr = local;
511         *colon = ':';
512         prio_local = option_priority;
513     }
514  
515     /*
516      * If colon last character, then no remote addr.
517      */
518     if (*++colon != '\0' && option_priority >= prio_remote) {
519         if ((remote = inet_addr(colon)) == (u_int32_t) -1) {
520             if ((hp = gethostbyname(colon)) == NULL) {
521                 option_error("unknown host: %s", colon);
522                 return 0;
523             }
524             remote = *(u_int32_t *)hp->h_addr;
525             if (remote_name[0] == 0)
526                 strlcpy(remote_name, colon, sizeof(remote_name));
527         }
528         if (bad_ip_adrs(remote)) {
529             option_error("bad remote IP address %s", ip_ntoa(remote));
530             return 0;
531         }
532         if (remote != 0)
533             wo->hisaddr = remote;
534         prio_remote = option_priority;
535     }
536     // brcm
537     ask_for_local = wo->ouraddr != 0 || !disable_defaultip;
538     // brcm
539
540     return 1;
541 }
542
543 static void
544 printipaddr(opt, printer, arg)
545     option_t *opt;
546     void (*printer) __P((void *, char *, ...));
547     void *arg;
548 {
549         ipcp_options *wo = &ipcp_wantoptions[0];
550
551         if (wo->ouraddr != 0)
552                 printer(arg, "%I", wo->ouraddr);
553         printer(arg, ":");
554         if (wo->hisaddr != 0)
555                 printer(arg, "%I", wo->hisaddr);
556 }
557
558 /*
559  * setnetmask - set the netmask to be used on the interface.
560  */
561 static int
562 setnetmask(argv)
563     char **argv;
564 {
565     u_int32_t mask;
566     int n;
567     char *p;
568
569     /*
570      * Unfortunately, if we use inet_addr, we can't tell whether
571      * a result of all 1s is an error or a valid 255.255.255.255.
572      */
573     p = *argv;
574     n = parse_dotted_ip(p, &mask);
575
576     mask = htonl(mask);
577
578     if (n == 0 || p[n] != 0 || (netmask & ~mask) != 0) {
579         option_error("invalid netmask value '%s'", *argv);
580         return 0;
581     }
582
583     netmask = mask;
584     slprintf(netmask_str, sizeof(netmask_str), "%I", mask);
585
586     return (1);
587 }
588
589 int
590 parse_dotted_ip(p, vp)
591     char *p;
592     u_int32_t *vp;
593 {
594     int n;
595     u_int32_t v, b;
596     char *endp, *p0 = p;
597
598     v = 0;
599     for (n = 3;; --n) {
600         b = strtoul(p, &endp, 0);
601         if (endp == p)
602             return 0;
603         if (b > 255) {
604             if (n < 3)
605                 return 0;
606             /* accept e.g. 0xffffff00 */
607             *vp = b;
608             return endp - p0;
609         }
610         v |= b << (n * 8);
611         p = endp;
612         if (n == 0)
613             break;
614         if (*p != '.')
615             return 0;
616         ++p;
617     }
618     *vp = v;
619     return p - p0;
620 }
621
622
623 /*
624  * ipcp_init - Initialize IPCP.
625  */
626 static void
627 ipcp_init(unit)
628     int unit;
629 {
630     fsm *f = &ipcp_fsm[unit];
631     ipcp_options *wo = &ipcp_wantoptions[unit];
632     ipcp_options *ao = &ipcp_allowoptions[unit];
633
634     f->unit = unit;
635     f->protocol = PPP_IPCP;
636     f->callbacks = &ipcp_callbacks;
637     fsm_init(&ipcp_fsm[unit]);
638
639     memset(wo, 0, sizeof(*wo));
640     memset(ao, 0, sizeof(*ao));
641
642     wo->neg_addr = 1;
643     wo->neg_vj = 1;
644     wo->vj_protocol = IPCP_VJ_COMP;
645     wo->maxslotindex = MAX_STATES - 1; /* really max index */
646     wo->cflag = 1;
647
648
649     /* max slots and slot-id compression are currently hardwired in */
650     /* ppp_if.c to 16 and 1, this needs to be changed (among other */
651     /* things) gmc */
652
653     ao->neg_addr = 1;
654     ao->neg_vj = 1;
655     ao->maxslotindex = MAX_STATES - 1;
656     ao->cflag = 1;
657
658     /*
659      * XXX These control whether the user may use the proxyarp
660      * and defaultroute options.
661      */
662     ao->proxy_arp = 1;
663     ao->default_route = 1;
664 }
665
666
667 /*
668  * ipcp_open - IPCP is allowed to come up.
669  */
670 static void
671 ipcp_open(unit)
672     int unit;
673 {
674     fsm_open(&ipcp_fsm[unit]);
675 }
676
677
678 /*
679  * ipcp_close - Take IPCP down.
680  */
681 static void
682 ipcp_close(unit, reason)
683     int unit;
684     char *reason;
685 {
686     fsm_close(&ipcp_fsm[unit], reason);
687 }
688
689
690 /*
691  * ipcp_lowerup - The lower layer is up.
692  */
693 static void
694 ipcp_lowerup(unit)
695     int unit;
696 {
697     //Charles 11/30/2003
698     //ipcp_options *go = &ipcp_gotoptions[unit];
699     ipcp_options *wo = &ipcp_wantoptions[unit];
700
701         //Charles 11/30/2003, set IP address for unnumbered PPP
702         if(unnumbered && strcmp(wan_IP, "")) {
703                 //printf("PPPD--ipcp_lowerup, unnumbered, set wan IP=%s\n", wan_IP);
704                 wo->ouraddr=inet_addr(wan_IP);
705                 ask_for_local=1;
706                 wo->accept_local=0;
707         }
708
709     fsm_lowerup(&ipcp_fsm[unit]);
710 }
711
712
713 /*
714  * ipcp_lowerdown - The lower layer is down.
715  */
716 static void
717 ipcp_lowerdown(unit)
718     int unit;
719 {
720     fsm_lowerdown(&ipcp_fsm[unit]);
721 }
722
723
724 /*
725  * ipcp_input - Input IPCP packet.
726  */
727 static void
728 ipcp_input(unit, p, len)
729     int unit;
730     u_char *p;
731     int len;
732 {
733     fsm_input(&ipcp_fsm[unit], p, len);
734 }
735
736
737 /*
738  * ipcp_protrej - A Protocol-Reject was received for IPCP.
739  *
740  * Pretend the lower layer went down, so we shut up.
741  */
742 static void
743 ipcp_protrej(unit)
744     int unit;
745 {
746     fsm_lowerdown(&ipcp_fsm[unit]);
747 }
748
749
750 /*
751  * ipcp_resetci - Reset our CI.
752  * Called by fsm_sconfreq, Send Configure Request.
753  */
754 static void
755 ipcp_resetci(f)
756     fsm *f;
757 {
758     ipcp_options *wo = &ipcp_wantoptions[f->unit];
759     ipcp_options *go = &ipcp_gotoptions[f->unit];
760
761     wo->req_addr = wo->neg_addr && ipcp_allowoptions[f->unit].neg_addr;
762     if (wo->ouraddr == 0)
763         wo->accept_local = 1;
764     if (wo->hisaddr == 0)
765         wo->accept_remote = 1;
766     wo->req_dns1 = usepeerdns;  /* Request DNS addresses from the peer */
767     wo->req_dns2 = usepeerdns;
768     *go = *wo;
769     if (!ask_for_local)
770         go->ouraddr = 0;
771     if (ip_choose_hook)
772         ip_choose_hook(&wo->hisaddr);
773 }
774
775
776 /*
777  * ipcp_cilen - Return length of our CI.
778  * Called by fsm_sconfreq, Send Configure Request.
779  */
780 static int
781 ipcp_cilen(f)
782     fsm *f;
783 {
784     ipcp_options *go = &ipcp_gotoptions[f->unit];
785     ipcp_options *wo = &ipcp_wantoptions[f->unit];
786     ipcp_options *ho = &ipcp_hisoptions[f->unit];
787
788 #define LENCIVJ(neg, old)       (neg ? (old? CILEN_COMPRESS : CILEN_VJ) : 0)
789 #define LENCIADDR(neg, old)     (neg ? (old? CILEN_ADDRS : CILEN_ADDR) : 0)
790 #define LENCIDNS(neg)           (neg ? (CILEN_ADDR) : 0)
791
792     /*
793      * First see if we want to change our options to the old
794      * forms because we have received old forms from the peer.
795      */
796     if (wo->neg_addr && !go->neg_addr && !go->old_addrs) {
797         /* use the old style of address negotiation */
798         go->neg_addr = 1;
799         go->old_addrs = 1;
800     }
801     if (wo->neg_vj && !go->neg_vj && !go->old_vj) {
802         /* try an older style of VJ negotiation */
803         /* use the old style only if the peer did */
804         if (ho->neg_vj && ho->old_vj) {
805             go->neg_vj = 1;
806             go->old_vj = 1;
807             go->vj_protocol = ho->vj_protocol;
808         }
809     }
810
811     return (LENCIADDR(go->neg_addr, go->old_addrs) +
812             LENCIVJ(go->neg_vj, go->old_vj) +
813             LENCIDNS(go->req_dns1) +
814             LENCIDNS(go->req_dns2)) ;
815 }
816
817
818 /*
819  * ipcp_addci - Add our desired CIs to a packet.
820  * Called by fsm_sconfreq, Send Configure Request.
821  */
822 static void
823 ipcp_addci(f, ucp, lenp)
824     fsm *f;
825     u_char *ucp;
826     int *lenp;
827 {
828     ipcp_options *go = &ipcp_gotoptions[f->unit];
829     int len = *lenp;
830
831 #define ADDCIVJ(opt, neg, val, old, maxslotindex, cflag) \
832     if (neg) { \
833         int vjlen = old? CILEN_COMPRESS : CILEN_VJ; \
834         if (len >= vjlen) { \
835             PUTCHAR(opt, ucp); \
836             PUTCHAR(vjlen, ucp); \
837             PUTSHORT(val, ucp); \
838             if (!old) { \
839                 PUTCHAR(maxslotindex, ucp); \
840                 PUTCHAR(cflag, ucp); \
841             } \
842             len -= vjlen; \
843         } else \
844             neg = 0; \
845     }
846
847 #define ADDCIADDR(opt, neg, old, val1, val2) \
848     if (neg) { \
849         int addrlen = (old? CILEN_ADDRS: CILEN_ADDR); \
850         if (len >= addrlen) { \
851             u_int32_t l; \
852             PUTCHAR(opt, ucp); \
853             PUTCHAR(addrlen, ucp); \
854             l = ntohl(val1); \
855             PUTLONG(l, ucp); \
856             if (old) { \
857                 l = ntohl(val2); \
858                 PUTLONG(l, ucp); \
859             } \
860             len -= addrlen; \
861         } else \
862             neg = 0; \
863     }
864
865 #define ADDCIDNS(opt, neg, addr) \
866     if (neg) { \
867         if (len >= CILEN_ADDR) { \
868             u_int32_t l; \
869             PUTCHAR(opt, ucp); \
870             PUTCHAR(CILEN_ADDR, ucp); \
871             l = ntohl(addr); \
872             PUTLONG(l, ucp); \
873             len -= CILEN_ADDR; \
874         } else \
875             neg = 0; \
876     }
877
878     ADDCIADDR((go->old_addrs? CI_ADDRS: CI_ADDR), go->neg_addr,
879               go->old_addrs, go->ouraddr, go->hisaddr);
880
881     ADDCIVJ(CI_COMPRESSTYPE, go->neg_vj, go->vj_protocol, go->old_vj,
882             go->maxslotindex, go->cflag);
883
884     ADDCIDNS(CI_MS_DNS1, go->req_dns1, go->dnsaddr[0]);
885
886     ADDCIDNS(CI_MS_DNS2, go->req_dns2, go->dnsaddr[1]);
887
888     *lenp -= len;
889 }
890
891
892 /*
893  * ipcp_ackci - Ack our CIs.
894  * Called by fsm_rconfack, Receive Configure ACK.
895  *
896  * Returns:
897  *      0 - Ack was bad.
898  *      1 - Ack was good.
899  */
900 static int
901 ipcp_ackci(f, p, len)
902     fsm *f;
903     u_char *p;
904     int len;
905 {
906     ipcp_options *go = &ipcp_gotoptions[f->unit];
907     u_short cilen, citype, cishort;
908     u_int32_t cilong;
909     u_char cimaxslotindex, cicflag;
910
911     /*
912      * CIs must be in exactly the same order that we sent...
913      * Check packet length and CI length at each step.
914      * If we find any deviations, then this packet is bad.
915      */
916
917 #define ACKCIVJ(opt, neg, val, old, maxslotindex, cflag) \
918     if (neg) { \
919         int vjlen = old? CILEN_COMPRESS : CILEN_VJ; \
920         if ((len -= vjlen) < 0) \
921             goto bad; \
922         GETCHAR(citype, p); \
923         GETCHAR(cilen, p); \
924         if (cilen != vjlen || \
925             citype != opt)  \
926             goto bad; \
927         GETSHORT(cishort, p); \
928         if (cishort != val) \
929             goto bad; \
930         if (!old) { \
931             GETCHAR(cimaxslotindex, p); \
932             if (cimaxslotindex != maxslotindex) \
933                 goto bad; \
934             GETCHAR(cicflag, p); \
935             if (cicflag != cflag) \
936                 goto bad; \
937         } \
938     }
939
940 #define ACKCIADDR(opt, neg, old, val1, val2) \
941     if (neg) { \
942         int addrlen = (old? CILEN_ADDRS: CILEN_ADDR); \
943         u_int32_t l; \
944         if ((len -= addrlen) < 0) \
945             goto bad; \
946         GETCHAR(citype, p); \
947         GETCHAR(cilen, p); \
948         if (cilen != addrlen || \
949             citype != opt) \
950             goto bad; \
951         GETLONG(l, p); \
952         cilong = htonl(l); \
953         if (val1 != cilong) \
954             goto bad; \
955         if (old) { \
956             GETLONG(l, p); \
957             cilong = htonl(l); \
958             if (val2 != cilong) \
959                 goto bad; \
960         } \
961     }
962
963 #define ACKCIDNS(opt, neg, addr) \
964     if (neg) { \
965         u_int32_t l; \
966         if ((len -= CILEN_ADDR) < 0) \
967             goto bad; \
968         GETCHAR(citype, p); \
969         GETCHAR(cilen, p); \
970         if (cilen != CILEN_ADDR || citype != opt) \
971             goto bad; \
972         GETLONG(l, p); \
973         cilong = htonl(l); \
974         if (addr != cilong) \
975             goto bad; \
976     }
977
978     ACKCIADDR((go->old_addrs? CI_ADDRS: CI_ADDR), go->neg_addr,
979               go->old_addrs, go->ouraddr, go->hisaddr);
980
981     ACKCIVJ(CI_COMPRESSTYPE, go->neg_vj, go->vj_protocol, go->old_vj,
982             go->maxslotindex, go->cflag);
983
984     ACKCIDNS(CI_MS_DNS1, go->req_dns1, go->dnsaddr[0]);
985
986     ACKCIDNS(CI_MS_DNS2, go->req_dns2, go->dnsaddr[1]);
987
988     /*
989      * If there are any remaining CIs, then this packet is bad.
990      */
991     if (len != 0)
992         goto bad;
993     return (1);
994
995 bad:
996     IPCPDEBUG(("ipcp_ackci: received bad Ack!"));
997     return (0);
998 }
999
1000 /*
1001  * ipcp_nakci - Peer has sent a NAK for some of our CIs.
1002  * This should not modify any state if the Nak is bad
1003  * or if IPCP is in the OPENED state.
1004  * Calback from fsm_rconfnakrej - Receive Configure-Nak or Configure-Reject.
1005  *
1006  * Returns:
1007  *      0 - Nak was bad.
1008  *      1 - Nak was good.
1009  */
1010 static int
1011 ipcp_nakci(f, p, len)
1012     fsm *f;
1013     u_char *p;
1014     int len;
1015 {
1016     ipcp_options *go = &ipcp_gotoptions[f->unit];
1017     u_char cimaxslotindex, cicflag;
1018     u_char citype, cilen, *next;
1019     u_short cishort;
1020     u_int32_t ciaddr1, ciaddr2, l, cidnsaddr;
1021     ipcp_options no;            /* options we've seen Naks for */
1022     ipcp_options try;           /* options to request next time */
1023
1024
1025     BZERO(&no, sizeof(no));
1026     try = *go;
1027
1028     /*
1029      * Any Nak'd CIs must be in exactly the same order that we sent.
1030      * Check packet length and CI length at each step.
1031      * If we find any deviations, then this packet is bad.
1032      */
1033 #define NAKCIADDR(opt, neg, old, code) \
1034     if (go->neg && \
1035         len >= (cilen = (old? CILEN_ADDRS: CILEN_ADDR)) && \
1036         p[1] == cilen && \
1037         p[0] == opt) { \
1038         len -= cilen; \
1039         INCPTR(2, p); \
1040         GETLONG(l, p); \
1041         ciaddr1 = htonl(l); \
1042         if (old) { \
1043             GETLONG(l, p); \
1044             ciaddr2 = htonl(l); \
1045             no.old_addrs = 1; \
1046         } else \
1047             ciaddr2 = 0; \
1048         no.neg = 1; \
1049         code \
1050     }
1051
1052 #define NAKCIVJ(opt, neg, code) \
1053     if (go->neg && \
1054         ((cilen = p[1]) == CILEN_COMPRESS || cilen == CILEN_VJ) && \
1055         len >= cilen && \
1056         p[0] == opt) { \
1057         len -= cilen; \
1058         INCPTR(2, p); \
1059         GETSHORT(cishort, p); \
1060         no.neg = 1; \
1061         code \
1062     }
1063
1064 #define NAKCIDNS(opt, neg, code) \
1065     if (go->neg && \
1066         ((cilen = p[1]) == CILEN_ADDR) && \
1067         len >= cilen && \
1068         p[0] == opt) { \
1069         len -= cilen; \
1070         INCPTR(2, p); \
1071         GETLONG(l, p); \
1072         cidnsaddr = htonl(l); \
1073         no.neg = 1; \
1074         code \
1075     }
1076
1077     /*
1078      * Accept the peer's idea of {our,his} address, if different
1079      * from our idea, only if the accept_{local,remote} flag is set.
1080      */
1081     NAKCIADDR((go->old_addrs? CI_ADDRS: CI_ADDR), neg_addr, go->old_addrs,
1082               if (go->accept_local && ciaddr1) { /* Do we know our address? */
1083                   try.ouraddr = ciaddr1;
1084               }
1085               if (go->accept_remote && ciaddr2) { /* Does he know his? */
1086                   try.hisaddr = ciaddr2;
1087               }
1088               );
1089
1090     /*
1091      * Accept the peer's value of maxslotindex provided that it
1092      * is less than what we asked for.  Turn off slot-ID compression
1093      * if the peer wants.  Send old-style compress-type option if
1094      * the peer wants.
1095      */
1096     NAKCIVJ(CI_COMPRESSTYPE, neg_vj,
1097             if (cilen == CILEN_VJ) {
1098                 GETCHAR(cimaxslotindex, p);
1099                 GETCHAR(cicflag, p);
1100                 if (cishort == IPCP_VJ_COMP) {
1101                     try.old_vj = 0;
1102                     if (cimaxslotindex < go->maxslotindex)
1103                         try.maxslotindex = cimaxslotindex;
1104                     if (!cicflag)
1105                         try.cflag = 0;
1106                 } else {
1107                     try.neg_vj = 0;
1108                 }
1109             } else {
1110                 if (cishort == IPCP_VJ_COMP || cishort == IPCP_VJ_COMP_OLD) {
1111                     try.old_vj = 1;
1112                     try.vj_protocol = cishort;
1113                 } else {
1114                     try.neg_vj = 0;
1115                 }
1116             }
1117             );
1118
1119     NAKCIDNS(CI_MS_DNS1, req_dns1,
1120             try.dnsaddr[0] = cidnsaddr;
1121             );
1122
1123     NAKCIDNS(CI_MS_DNS2, req_dns2,
1124             try.dnsaddr[1] = cidnsaddr;
1125             );
1126
1127     /*
1128      * There may be remaining CIs, if the peer is requesting negotiation
1129      * on an option that we didn't include in our request packet.
1130      * If they want to negotiate about IP addresses, we comply.
1131      * If they want us to ask for compression, we refuse.
1132      */
1133     while (len > CILEN_VOID) {
1134         GETCHAR(citype, p);
1135         GETCHAR(cilen, p);
1136         if( (len -= cilen) < 0 )
1137             goto bad;
1138         next = p + cilen - 2;
1139
1140         switch (citype) {
1141         case CI_COMPRESSTYPE:
1142             if (go->neg_vj || no.neg_vj ||
1143                 (cilen != CILEN_VJ && cilen != CILEN_COMPRESS))
1144                 goto bad;
1145             no.neg_vj = 1;
1146             break;
1147         case CI_ADDRS:
1148             if ((go->neg_addr && go->old_addrs) || no.old_addrs
1149                 || cilen != CILEN_ADDRS)
1150                 goto bad;
1151             try.neg_addr = 1;
1152             try.old_addrs = 1;
1153             GETLONG(l, p);
1154             ciaddr1 = htonl(l);
1155             if (ciaddr1 && go->accept_local)
1156                 try.ouraddr = ciaddr1;
1157             GETLONG(l, p);
1158             ciaddr2 = htonl(l);
1159             if (ciaddr2 && go->accept_remote)
1160                 try.hisaddr = ciaddr2;
1161             no.old_addrs = 1;
1162             break;
1163         case CI_ADDR:
1164             if (go->neg_addr || no.neg_addr || cilen != CILEN_ADDR)
1165                 goto bad;
1166             try.old_addrs = 0;
1167             GETLONG(l, p);
1168             ciaddr1 = htonl(l);
1169             if (ciaddr1 && go->accept_local)
1170                 try.ouraddr = ciaddr1;
1171             if (try.ouraddr != 0)
1172                 try.neg_addr = 1;
1173             no.neg_addr = 1;
1174             break;
1175         }
1176         p = next;
1177     }
1178
1179     /*
1180      * OK, the Nak is good.  Now we can update state.
1181      * If there are any remaining options, we ignore them.
1182      */
1183     if (f->state != OPENED)
1184         *go = try;
1185
1186     return 1;
1187
1188 bad:
1189     IPCPDEBUG(("ipcp_nakci: received bad Nak!"));
1190     return 0;
1191 }
1192
1193
1194 /*
1195  * ipcp_rejci - Reject some of our CIs.
1196  * Callback from fsm_rconfnakrej.
1197  */
1198 static int
1199 ipcp_rejci(f, p, len)
1200     fsm *f;
1201     u_char *p;
1202     int len;
1203 {
1204     ipcp_options *go = &ipcp_gotoptions[f->unit];
1205     u_char cimaxslotindex, ciflag, cilen;
1206     u_short cishort;
1207     u_int32_t cilong;
1208     ipcp_options try;           /* options to request next time */
1209
1210     try = *go;
1211     /*
1212      * Any Rejected CIs must be in exactly the same order that we sent.
1213      * Check packet length and CI length at each step.
1214      * If we find any deviations, then this packet is bad.
1215      */
1216 #define REJCIADDR(opt, neg, old, val1, val2) \
1217     if (go->neg && \
1218         len >= (cilen = old? CILEN_ADDRS: CILEN_ADDR) && \
1219         p[1] == cilen && \
1220         p[0] == opt) { \
1221         u_int32_t l; \
1222         len -= cilen; \
1223         INCPTR(2, p); \
1224         GETLONG(l, p); \
1225         cilong = htonl(l); \
1226         /* Check rejected value. */ \
1227         if (cilong != val1) \
1228             goto bad; \
1229         if (old) { \
1230             GETLONG(l, p); \
1231             cilong = htonl(l); \
1232             /* Check rejected value. */ \
1233             if (cilong != val2) \
1234                 goto bad; \
1235         } \
1236         try.neg = 0; \
1237     }
1238
1239 #define REJCIVJ(opt, neg, val, old, maxslot, cflag) \
1240     if (go->neg && \
1241         p[1] == (old? CILEN_COMPRESS : CILEN_VJ) && \
1242         len >= p[1] && \
1243         p[0] == opt) { \
1244         len -= p[1]; \
1245         INCPTR(2, p); \
1246         GETSHORT(cishort, p); \
1247         /* Check rejected value. */  \
1248         if (cishort != val) \
1249             goto bad; \
1250         if (!old) { \
1251            GETCHAR(cimaxslotindex, p); \
1252            if (cimaxslotindex != maxslot) \
1253              goto bad; \
1254            GETCHAR(ciflag, p); \
1255            if (ciflag != cflag) \
1256              goto bad; \
1257         } \
1258         try.neg = 0; \
1259      }
1260
1261 #define REJCIDNS(opt, neg, dnsaddr) \
1262     if (go->neg && \
1263         ((cilen = p[1]) == CILEN_ADDR) && \
1264         len >= cilen && \
1265         p[0] == opt) { \
1266         u_int32_t l; \
1267         len -= cilen; \
1268         INCPTR(2, p); \
1269         GETLONG(l, p); \
1270         cilong = htonl(l); \
1271         /* Check rejected value. */ \
1272         if (cilong != dnsaddr) \
1273             goto bad; \
1274         try.neg = 0; \
1275     }
1276
1277
1278     REJCIADDR((go->old_addrs? CI_ADDRS: CI_ADDR), neg_addr,
1279               go->old_addrs, go->ouraddr, go->hisaddr);
1280
1281     REJCIVJ(CI_COMPRESSTYPE, neg_vj, go->vj_protocol, go->old_vj,
1282             go->maxslotindex, go->cflag);
1283
1284     REJCIDNS(CI_MS_DNS1, req_dns1, go->dnsaddr[0]);
1285
1286     REJCIDNS(CI_MS_DNS2, req_dns2, go->dnsaddr[1]);
1287
1288     /*
1289      * If there are any remaining CIs, then this packet is bad.
1290      */
1291     if (len != 0)
1292         goto bad;
1293     /*
1294      * Now we can update state.
1295      */
1296     if (f->state != OPENED)
1297         *go = try;
1298     return 1;
1299
1300 bad:
1301     IPCPDEBUG(("ipcp_rejci: received bad Reject!"));
1302     return 0;
1303 }
1304
1305
1306 /*
1307  * ipcp_reqci - Check the peer's requested CIs and send appropriate response.
1308  * Callback from fsm_rconfreq, Receive Configure Request
1309  *
1310  * Returns: CONFACK, CONFNAK or CONFREJ and input packet modified
1311  * appropriately.  If reject_if_disagree is non-zero, doesn't return
1312  * CONFNAK; returns CONFREJ if it can't return CONFACK.
1313  */
1314 static int
1315 ipcp_reqci(f, inp, len, reject_if_disagree)
1316     fsm *f;
1317     u_char *inp;                /* Requested CIs */
1318     int *len;                   /* Length of requested CIs */
1319     int reject_if_disagree;
1320 {
1321     ipcp_options *wo = &ipcp_wantoptions[f->unit];
1322     ipcp_options *ho = &ipcp_hisoptions[f->unit];
1323     ipcp_options *ao = &ipcp_allowoptions[f->unit];
1324     ipcp_options *go = &ipcp_gotoptions[f->unit];
1325     u_char *cip, *next;         /* Pointer to current and next CIs */
1326     u_short cilen, citype;      /* Parsed len, type */
1327     u_short cishort;            /* Parsed short value */
1328     u_int32_t tl, ciaddr1, ciaddr2;/* Parsed address values */
1329     int rc = CONFACK;           /* Final packet return code */
1330     int orc;                    /* Individual option return code */
1331     u_char *p;                  /* Pointer to next char to parse */
1332     u_char *ucp = inp;          /* Pointer to current output char */
1333     int l = *len;               /* Length left */
1334     u_char maxslotindex, cflag;
1335     int d;
1336
1337     /*
1338      * Reset all his options.
1339      */
1340     BZERO(ho, sizeof(*ho));
1341     
1342     /*
1343      * Process all his options.
1344      */
1345     next = inp;
1346     while (l) {
1347         orc = CONFACK;                  /* Assume success */
1348         cip = p = next;                 /* Remember begining of CI */
1349         if (l < 2 ||                    /* Not enough data for CI header or */
1350             p[1] < 2 ||                 /*  CI length too small or */
1351             p[1] > l) {                 /*  CI length too big? */
1352             IPCPDEBUG(("ipcp_reqci: bad CI length!"));
1353             orc = CONFREJ;              /* Reject bad CI */
1354             cilen = l;                  /* Reject till end of packet */
1355             l = 0;                      /* Don't loop again */
1356             goto endswitch;
1357         }
1358         GETCHAR(citype, p);             /* Parse CI type */
1359         GETCHAR(cilen, p);              /* Parse CI length */
1360         l -= cilen;                     /* Adjust remaining length */
1361         next += cilen;                  /* Step to next CI */
1362
1363         switch (citype) {               /* Check CI type */
1364         case CI_ADDRS:
1365             if (!ao->neg_addr ||
1366                 cilen != CILEN_ADDRS) { /* Check CI length */
1367                 orc = CONFREJ;          /* Reject CI */
1368                 break;
1369             }
1370
1371             /*
1372              * If he has no address, or if we both have his address but
1373              * disagree about it, then NAK it with our idea.
1374              * In particular, if we don't know his address, but he does,
1375              * then accept it.
1376              */
1377             GETLONG(tl, p);             /* Parse source address (his) */
1378             ciaddr1 = htonl(tl);
1379             if (ciaddr1 != wo->hisaddr
1380                 && (ciaddr1 == 0 || !wo->accept_remote)) {
1381                 orc = CONFNAK;
1382                 if (!reject_if_disagree) {
1383                     DECPTR(sizeof(u_int32_t), p);
1384                     tl = ntohl(wo->hisaddr);
1385                     PUTLONG(tl, p);
1386                 }
1387             } else if (ciaddr1 == 0 && wo->hisaddr == 0) {
1388                 /*
1389                  * If neither we nor he knows his address, reject the option.
1390                  */
1391                 orc = CONFREJ;
1392                 wo->req_addr = 0;       /* don't NAK with 0.0.0.0 later */
1393                 break;
1394             }
1395
1396             /*
1397              * If he doesn't know our address, or if we both have our address
1398              * but disagree about it, then NAK it with our idea.
1399              */
1400             GETLONG(tl, p);             /* Parse desination address (ours) */
1401             ciaddr2 = htonl(tl);
1402             if (ciaddr2 != wo->ouraddr) {
1403                 if (ciaddr2 == 0 || !wo->accept_local) {
1404                     orc = CONFNAK;
1405                     if (!reject_if_disagree) {
1406                         DECPTR(sizeof(u_int32_t), p);
1407                         tl = ntohl(wo->ouraddr);
1408                         PUTLONG(tl, p);
1409                     }
1410                 } else {
1411                     go->ouraddr = ciaddr2;      /* accept peer's idea */
1412                 }
1413             }
1414
1415             ho->neg_addr = 1;
1416             ho->old_addrs = 1;
1417             ho->hisaddr = ciaddr1;
1418             ho->ouraddr = ciaddr2;
1419             break;
1420
1421         case CI_ADDR:
1422             if (!ao->neg_addr ||
1423                 cilen != CILEN_ADDR) {  /* Check CI length */
1424                 orc = CONFREJ;          /* Reject CI */
1425                 break;
1426             }
1427
1428             /*
1429              * If he has no address, or if we both have his address but
1430              * disagree about it, then NAK it with our idea.
1431              * In particular, if we don't know his address, but he does,
1432              * then accept it.
1433              */
1434             GETLONG(tl, p);     /* Parse source address (his) */
1435             ciaddr1 = htonl(tl);
1436             if (ciaddr1 != wo->hisaddr
1437                 && (ciaddr1 == 0 || !wo->accept_remote)) {
1438                 orc = CONFNAK;
1439                 if (!reject_if_disagree) {
1440                     DECPTR(sizeof(u_int32_t), p);
1441                     tl = ntohl(wo->hisaddr);
1442                     PUTLONG(tl, p);
1443                 }
1444             } else if (ciaddr1 == 0 && wo->hisaddr == 0) {
1445                 /*
1446                  * Don't ACK an address of 0.0.0.0 - reject it instead.
1447                  */
1448                 orc = CONFREJ;
1449                 wo->req_addr = 0;       /* don't NAK with 0.0.0.0 later */
1450                 break;
1451             }
1452         
1453             ho->neg_addr = 1;
1454             ho->hisaddr = ciaddr1;
1455             break;
1456
1457         case CI_MS_DNS1:
1458         case CI_MS_DNS2:
1459             /* Microsoft primary or secondary DNS request */
1460             d = citype == CI_MS_DNS2;
1461
1462             /* If we do not have a DNS address then we cannot send it */
1463             if (ao->dnsaddr[d] == 0 ||
1464                 cilen != CILEN_ADDR) {  /* Check CI length */
1465                 orc = CONFREJ;          /* Reject CI */
1466                 break;
1467             }
1468             GETLONG(tl, p);
1469             if (htonl(tl) != ao->dnsaddr[d]) {
1470                 DECPTR(sizeof(u_int32_t), p);
1471                 tl = ntohl(ao->dnsaddr[d]);
1472                 PUTLONG(tl, p);
1473                 orc = CONFNAK;
1474             }
1475             break;
1476
1477         case CI_MS_WINS1:
1478         case CI_MS_WINS2:
1479             /* Microsoft primary or secondary WINS request */
1480             d = citype == CI_MS_WINS2;
1481
1482             /* If we do not have a DNS address then we cannot send it */
1483             if (ao->winsaddr[d] == 0 ||
1484                 cilen != CILEN_ADDR) {  /* Check CI length */
1485                 orc = CONFREJ;          /* Reject CI */
1486                 break;
1487             }
1488             GETLONG(tl, p);
1489             if (htonl(tl) != ao->winsaddr[d]) {
1490                 DECPTR(sizeof(u_int32_t), p);
1491                 tl = ntohl(ao->winsaddr[d]);
1492                 PUTLONG(tl, p);
1493                 orc = CONFNAK;
1494             }
1495             break;
1496         
1497         case CI_COMPRESSTYPE:
1498             if (!ao->neg_vj ||
1499                 (cilen != CILEN_VJ && cilen != CILEN_COMPRESS)) {
1500                 orc = CONFREJ;
1501                 break;
1502             }
1503             GETSHORT(cishort, p);
1504
1505             if (!(cishort == IPCP_VJ_COMP ||
1506                   (cishort == IPCP_VJ_COMP_OLD && cilen == CILEN_COMPRESS))) {
1507                 orc = CONFREJ;
1508                 break;
1509             }
1510
1511             ho->neg_vj = 1;
1512             ho->vj_protocol = cishort;
1513             if (cilen == CILEN_VJ) {
1514                 GETCHAR(maxslotindex, p);
1515                 if (maxslotindex > ao->maxslotindex) { 
1516                     orc = CONFNAK;
1517                     if (!reject_if_disagree){
1518                         DECPTR(1, p);
1519                         PUTCHAR(ao->maxslotindex, p);
1520                     }
1521                 }
1522                 GETCHAR(cflag, p);
1523                 if (cflag && !ao->cflag) {
1524                     orc = CONFNAK;
1525                     if (!reject_if_disagree){
1526                         DECPTR(1, p);
1527                         PUTCHAR(wo->cflag, p);
1528                     }
1529                 }
1530                 ho->maxslotindex = maxslotindex;
1531                 ho->cflag = cflag;
1532             } else {
1533                 ho->old_vj = 1;
1534                 ho->maxslotindex = MAX_STATES - 1;
1535                 ho->cflag = 1;
1536             }
1537             break;
1538
1539         default:
1540             orc = CONFREJ;
1541             break;
1542         }
1543 endswitch:
1544         if (orc == CONFACK &&           /* Good CI */
1545             rc != CONFACK)              /*  but prior CI wasnt? */
1546             continue;                   /* Don't send this one */
1547
1548         if (orc == CONFNAK) {           /* Nak this CI? */
1549             if (reject_if_disagree)     /* Getting fed up with sending NAKs? */
1550                 orc = CONFREJ;          /* Get tough if so */
1551             else {
1552                 if (rc == CONFREJ)      /* Rejecting prior CI? */
1553                     continue;           /* Don't send this one */
1554                 if (rc == CONFACK) {    /* Ack'd all prior CIs? */
1555                     rc = CONFNAK;       /* Not anymore... */
1556                     ucp = inp;          /* Backup */
1557                 }
1558             }
1559         }
1560
1561         if (orc == CONFREJ &&           /* Reject this CI */
1562             rc != CONFREJ) {            /*  but no prior ones? */
1563             rc = CONFREJ;
1564             ucp = inp;                  /* Backup */
1565         }
1566
1567         /* Need to move CI? */
1568         if (ucp != cip)
1569             BCOPY(cip, ucp, cilen);     /* Move it */
1570
1571         /* Update output pointer */
1572         INCPTR(cilen, ucp);
1573     }
1574
1575     /*
1576      * If we aren't rejecting this packet, and we want to negotiate
1577      * their address, and they didn't send their address, then we
1578      * send a NAK with a CI_ADDR option appended.  We assume the
1579      * input buffer is long enough that we can append the extra
1580      * option safely.
1581      */
1582     if (rc != CONFREJ && !ho->neg_addr &&
1583         wo->req_addr && !reject_if_disagree) {
1584         if (rc == CONFACK) {
1585             rc = CONFNAK;
1586             ucp = inp;                  /* reset pointer */
1587             wo->req_addr = 0;           /* don't ask again */
1588         }
1589         PUTCHAR(CI_ADDR, ucp);
1590         PUTCHAR(CILEN_ADDR, ucp);
1591         tl = ntohl(wo->hisaddr);
1592         PUTLONG(tl, ucp);
1593     }
1594
1595     *len = ucp - inp;                   /* Compute output length */
1596     IPCPDEBUG(("ipcp: returning Configure-%s", CODENAME(rc)));
1597     return (rc);                        /* Return final code */
1598 }
1599
1600
1601 /*
1602  * ip_check_options - check that any IP-related options are OK,
1603  * and assign appropriate defaults.
1604  */
1605 static void
1606 ip_check_options()
1607 {
1608     struct hostent *hp;
1609     u_int32_t local;
1610     ipcp_options *wo = &ipcp_wantoptions[0];
1611
1612     /*
1613      * Default our local IP address based on our hostname.
1614      * If local IP address already given, don't bother.
1615      */
1616     if (wo->ouraddr == 0 && !disable_defaultip) {
1617         /*
1618          * Look up our hostname (possibly with domain name appended)
1619          * and take the first IP address as our local IP address.
1620          * If there isn't an IP address for our hostname, too bad.
1621          */
1622         wo->accept_local = 1;   /* don't insist on this default value */
1623         if ((hp = gethostbyname(hostname)) != NULL) {
1624             local = *(u_int32_t *)hp->h_addr;
1625             if (local != 0 && !bad_ip_adrs(local))
1626                 wo->ouraddr = local;
1627         }
1628     }
1629     ask_for_local = wo->ouraddr != 0 || !disable_defaultip;
1630 }
1631
1632
1633 /*
1634  * ip_demand_conf - configure the interface as though
1635  * IPCP were up, for use with dial-on-demand.
1636  */
1637 static int
1638 ip_demand_conf(u)
1639     int u;
1640 {
1641     u_int32_t mask;  //Charles 12/06/2003
1642     ipcp_options *wo = &ipcp_wantoptions[u];
1643     char cmd[50];
1644     struct in_addr addr;
1645
1646     if (wo->hisaddr == 0) {
1647         /* make up an arbitrary address for the peer */
1648         wo->hisaddr = htonl(0x0a707070 + ifunit);
1649         wo->accept_remote = 1;
1650     }
1651     if (wo->ouraddr == 0) {
1652         /* make up an arbitrary address for us */
1653         wo->ouraddr = htonl(0x0a404040 + ifunit);
1654         wo->accept_local = 1;
1655         ask_for_local = 0;      /* don't tell the peer this address */
1656     }
1657     //Charles 12/06/2003, for unnumbered PPP
1658     if(unnumbered && strcmp(wan_submask, "")) {
1659                 mask=inet_addr(wan_submask);
1660                 //printf("PPPD--ipcp_up, unnumbered, set mask=%d\n", mask);
1661         }
1662     else 
1663                 mask = GetMask(wo->ouraddr);
1664
1665     if (!sifaddr(u, wo->ouraddr, wo->hisaddr, mask))
1666         return 0;
1667     if (!sifup(u))
1668         return 0;
1669     if (!sifnpmode(u, PPP_IP, NPMODE_QUEUE))
1670         return 0;
1671     if (wo->default_route)
1672         if (sifdefaultroute(u, wo->ouraddr, wo->hisaddr))
1673             default_route_set[u] = 1;
1674     if (wo->proxy_arp)
1675         if (sifproxyarp(u, wo->hisaddr))
1676             proxy_arp_set[u] = 1;
1677
1678     notice("local  IP address %I", wo->ouraddr);
1679     notice("remote IP address %I", wo->hisaddr);
1680
1681     /*==== add by Andy(2005/05/02) ====*/
1682         addr.s_addr = wo->hisaddr;
1683         sprintf(cmd,"route del -host %s", inet_ntoa(addr));
1684         //printf("PPP:%s\n",cmd);
1685         system(cmd);
1686         /*==== end ====*/
1687
1688     return 1;
1689 }
1690
1691 // brcm
1692 //#define _PATH_RESOLV   "/var/fyi/sys/dns"
1693 //#define _PATH_GW       "/var/fyi/sys/gateway"
1694 #define _PATH_SYS_DIR    "/var/fyi/sys"
1695
1696 // brcm
1697 static int file_save(char * path, char * content, int check)
1698 {
1699     FILE *f;
1700
1701     // brcm
1702     if (check) {
1703         if ((f = fopen(path, "r")) > 0) {
1704             // the file already exists.
1705             fclose(f);
1706             return 0;
1707         }
1708     }
1709
1710     f = fopen(path, "w");
1711     if (f == NULL) {
1712         error("Failed to create %s: %m", path);
1713         return -1;
1714     }
1715
1716     fprintf(f, "%s\n", content);
1717
1718     fclose(f);
1719     return 1;
1720 }
1721
1722 #define _PATH_WAN_DIR   "/proc/var/fyi/wan"
1723 #define _PATH_MSG       "daemonstatus"
1724 #define _PATH_IP        "ipaddress"
1725 #define _PATH_MASK      "subnetmask"
1726
1727 // brcm
1728 static void config_save()
1729 {
1730     FILE *fp;
1731     char path[128]="";
1732     static wan_config_router_check=1;
1733     static wan_config_dns_check=1;
1734     int autoDns=0;
1735     char cmd[64]="";
1736     
1737     if (strlen(session_path) > 0)
1738         sprintf(path, "%s/%s/%s", _PATH_WAN_DIR, session_path, _PATH_IP);
1739     file_save(path, local_ip, 0);
1740
1741     if (strlen(session_path) > 0)
1742         sprintf(path, "%s/%s/%s", _PATH_WAN_DIR, session_path, _PATH_MASK);
1743     //previously remarked, enabled by Charles 12/06/2003 for unnumbered PPP
1744     file_save(path, subnet_ip, 0);
1745
1746     sprintf(cmd, "mkdir -p %s", _PATH_SYS_DIR);
1747     system(cmd);
1748     //mkdir(_PATH_SYS_DIR);
1749
1750 #ifdef INCLUDE_EMBHTTPD //modified by Andrew (14/01/2004)
1751     /* write the route_ip/dns_ip to _PATH_GW/_PATH_RESOLV no matter route_ip/dns_ip is change or not */
1752     if (strlen(router_ip) > 0)
1753         file_save(_PATH_GW, router_ip, 0);
1754     if(check_dns() == 0) {
1755         if (strlen(dns_ip) > 0) 
1756             file_save(_PATH_RESOLV, dns_ip, 0);
1757         }
1758 #else
1759         if (ppp_addgw == 1){
1760         if (strlen(router_ip) > 0) {
1761         if (file_save(_PATH_GW, router_ip, wan_config_router_check) > 0)
1762             wan_config_router_check=0;
1763                         
1764                         /*******************************************************
1765                         * Fix bug(492):The default gateway infomation is wrong *
1766                         * if there are two internet connections.               *
1767                         * Andy (2005/10/17)
1768                         ****************************************/
1769                         if (strlen(session_path) > 0){
1770                                 sprintf(path, "/var/%s_gwip", session_path);
1771                         file_save(path, router_ip, 0);
1772                 }       
1773                                 
1774                         if (strlen(session_path) > 0){
1775                                 file_save("/var/fyi/sys/device", session_path, 0);
1776                         }
1777         }
1778                 if (strlen(dns_ip) > 0) {
1779                 fp = fopen("/var/autoGetDns", "r");
1780                 if(fp){
1781                 fscanf(fp, "%d", &autoDns);
1782                 fclose(fp);
1783                 if(autoDns)
1784                         file_save(_PATH_RESOLV, dns_ip, 0);
1785                 else
1786                         file_save(_PATH_RESOLV, dns_ip, 1);
1787                 }else {
1788                         if (file_save(_PATH_RESOLV, dns_ip, wan_config_dns_check) > 0)
1789                         wan_config_dns_check=0; 
1790                         }
1791                 }
1792     } else {
1793         //if (ipext == 1){
1794                 if (strlen(dns_ip) > 0) {
1795                         fp = fopen("/var/autoGetDns", "r");
1796                         if(fp){
1797                         fscanf(fp, "%d", &autoDns);
1798                         fclose(fp);
1799                         if(autoDns)
1800                                 file_save(_PATH_RESOLV, dns_ip, 0);
1801                         else
1802                                 file_save(_PATH_RESOLV, dns_ip, 1);
1803                         }else {
1804                         if (file_save(_PATH_RESOLV, dns_ip, wan_config_dns_check) > 0)
1805                                 wan_config_dns_check=0; 
1806                         }
1807                         }
1808         //}
1809     }   
1810 #endif
1811 }
1812
1813 /*
1814  * ipcp_up - IPCP has come UP.
1815  *
1816  * Configure the IP network interface appropriately and bring it up.
1817  */
1818 static void
1819 ipcp_up(f)
1820     fsm *f;
1821 {
1822     u_int32_t mask;
1823     ipcp_options *ho = &ipcp_hisoptions[f->unit];
1824     ipcp_options *go = &ipcp_gotoptions[f->unit];
1825     ipcp_options *wo = &ipcp_wantoptions[f->unit];
1826         char cmd[128]="";
1827 #if defined(ODM_LANG_LLL)
1828     FILE *wsnfp=NULL;
1829 #endif
1830 #if defined(INCLUDE_EMBHTTPD)
1831    FILE *fp=NULL;
1832    if((fp = fopen("/var/attempt2Disconnect", "r")) != NULL) {
1833       fclose(fp);
1834       unlink("/var/attempt2Disconnect");
1835       }
1836 #endif
1837
1838     IPCPDEBUG(("ipcp: up"));
1839
1840     /*
1841      * We must have a non-zero IP address for both ends of the link.
1842      */
1843     if (!ho->neg_addr)
1844         ho->hisaddr = wo->hisaddr;
1845
1846 #if defined(ODM_LANG_LLL)
1847         if (go->ouraddr == 0 || go->dnsaddr[0] == 0) {//ipcp can't get local ip address or primary ip address
1848                 if (ppp_session == PPPOE){
1849                         wsnfp = fopen("/var/btaolstatus", "w");
1850                         if(wsnfp){
1851                             fprintf(wsnfp, "%d", 3);
1852                             fclose(wsnfp);
1853                         }
1854                         sprintf(cmd,"kill -9 %d",glbppppid);
1855                         system(cmd);    
1856                 }
1857         }
1858 #endif
1859
1860     if (go->ouraddr == 0) {
1861         error("Could not determine local IP address");
1862         ipcp_close(f->unit, "Could not determine local IP address");
1863         return;
1864     }
1865     if (ho->hisaddr == 0) {
1866         ho->hisaddr = htonl(0x0a404040 + ifunit);
1867         warn("Could not determine remote IP address: defaulting to %I",
1868              ho->hisaddr);
1869     }
1870     script_setenv("IPLOCAL", ip_ntoa(go->ouraddr), 0);
1871     script_setenv("IPREMOTE", ip_ntoa(ho->hisaddr), 1);
1872
1873     if (usepeerdns && (go->dnsaddr[0] || go->dnsaddr[1])) {
1874         script_setenv("USEPEERDNS", "1", 0);
1875         if (go->dnsaddr[0])
1876             script_setenv("DNS1", ip_ntoa(go->dnsaddr[0]), 0);
1877         if (go->dnsaddr[1])
1878             script_setenv("DNS2", ip_ntoa(go->dnsaddr[1]), 0);
1879         create_resolv(go->dnsaddr[0], go->dnsaddr[1]);
1880     }
1881
1882     /*
1883      * Check that the peer is allowed to use the IP address it wants.
1884      */
1885     if (!auth_ip_addr(f->unit, ho->hisaddr)) {
1886         error("Peer is not authorized to use remote address %I", ho->hisaddr);
1887         ipcp_close(f->unit, "Unauthorized remote IP address");
1888         return;
1889     }
1890
1891     /* set tcp compression */
1892     sifvjcomp(f->unit, ho->neg_vj, ho->cflag, ho->maxslotindex);
1893
1894     /*
1895      * If we are doing dial-on-demand, the interface is already
1896      * configured, so we put out any saved-up packets, then set the
1897      * interface to pass IP packets.
1898      */
1899     if (demand) {
1900         if (go->ouraddr != wo->ouraddr || ho->hisaddr != wo->hisaddr) {
1901             ipcp_clear_addrs(f->unit, wo->ouraddr, wo->hisaddr);
1902             if (go->ouraddr != wo->ouraddr) {
1903                 warn("Local IP address changed to %I", go->ouraddr);
1904                 script_setenv("OLDIPLOCAL", ip_ntoa(wo->ouraddr), 0);
1905                 wo->ouraddr = go->ouraddr;
1906             } else
1907                 script_unsetenv("OLDIPLOCAL");
1908             if (ho->hisaddr != wo->hisaddr) {
1909                 warn("Remote IP address changed to %I", ho->hisaddr);
1910                 script_setenv("OLDIPREMOTE", ip_ntoa(wo->hisaddr), 0);
1911                 wo->hisaddr = ho->hisaddr;
1912             } else
1913                 script_unsetenv("OLDIPREMOTE");
1914
1915             /* Set the interface to the new addresses */
1916         //Charles 12/06/2003, for unnumbered PPP
1917         if(unnumbered && strcmp(wan_submask, "")) {
1918                 mask=inet_addr(wan_submask);
1919                 //printf("PPPD--ipcp_up, unnumbered, set mask=%d\n", mask);
1920                 }
1921         else 
1922             mask = GetMask(go->ouraddr);
1923             if (!sifaddr(f->unit, go->ouraddr, ho->hisaddr, mask)) {
1924                 if (debug)
1925                     warn("Interface configuration failed");
1926                 ipcp_close(f->unit, "Interface configuration failed");
1927                 return;
1928             }
1929             /* assign a default route through the interface if required */
1930             if (ipcp_wantoptions[f->unit].default_route){ 
1931                 if (sifdefaultroute(f->unit, go->ouraddr, ho->hisaddr))
1932                     default_route_set[f->unit] = 1;
1933                 }    
1934
1935             /* Make a proxy ARP entry if requested. */
1936             if (ipcp_wantoptions[f->unit].proxy_arp)
1937                 if (sifproxyarp(f->unit, ho->hisaddr))
1938                     proxy_arp_set[f->unit] = 1;
1939
1940         }
1941         demand_rexmit(PPP_IP);
1942         sifnpmode(f->unit, PPP_IP, NPMODE_PASS);
1943
1944     } else {
1945         /*
1946          * Set IP addresses and (if specified) netmask.
1947          */
1948     //Charles 12/06/2003, for unnumbered PPP
1949     if(unnumbered && strcmp(wan_submask, "")) {
1950                 mask=inet_addr(wan_submask);
1951                 //printf("PPPD--ipcp_up, unnumbered, set mask=%d\n", mask);
1952         }
1953     else 
1954         mask = GetMask(go->ouraddr);
1955
1956 #if !(defined(SVR4) && (defined(SNI) || defined(__USLC__)))
1957         if (!sifaddr(f->unit, go->ouraddr, ho->hisaddr, mask)) {
1958             if (debug)
1959                 warn("Interface configuration failed");
1960             ipcp_close(f->unit, "Interface configuration failed");
1961             return;
1962         }
1963 #endif
1964
1965         /* bring the interface up for IP */
1966         if (!sifup(f->unit)) {
1967             if (debug)
1968                 warn("Interface failed to come up");
1969             ipcp_close(f->unit, "Interface configuration failed");
1970             return;
1971         }
1972
1973 #if (defined(SVR4) && (defined(SNI) || defined(__USLC__)))
1974         if (!sifaddr(f->unit, go->ouraddr, ho->hisaddr, mask)) {
1975             if (debug)
1976                 warn("Interface configuration failed");
1977             ipcp_close(f->unit, "Interface configuration failed");
1978             return;
1979         }
1980 #endif
1981         sifnpmode(f->unit, PPP_IP, NPMODE_PASS);
1982
1983         /* assign a default route through the interface if required */
1984         if (ipcp_wantoptions[f->unit].default_route){ 
1985             if (sifdefaultroute(f->unit, go->ouraddr, ho->hisaddr))
1986                 default_route_set[f->unit] = 1;
1987         }       
1988
1989         /* Make a proxy ARP entry if requested. */
1990         if (ipcp_wantoptions[f->unit].proxy_arp)
1991             if (sifproxyarp(f->unit, ho->hisaddr))
1992                 proxy_arp_set[f->unit] = 1;
1993
1994         ipcp_wantoptions[0].ouraddr = go->ouraddr;
1995
1996         notice("local  IP address %I", go->ouraddr);
1997         notice("remote IP address %I", ho->hisaddr);
1998         if (go->dnsaddr[0])
1999             notice("primary   DNS address %I", go->dnsaddr[0]);
2000         if (go->dnsaddr[1])
2001             notice("secondary DNS address %I", go->dnsaddr[1]);
2002     }
2003
2004     np_up(f->unit, PPP_IP);
2005     ipcp_is_up = 1;
2006
2007     // brcm
2008     strcpy(local_ip, ip_ntoa(go->ouraddr));
2009     //strcpy(subnet_ip, ip_ntoa(mask));
2010     //Charles 12/06/2003, for unnumbered PPP
2011     if(unnumbered && strcmp(wan_submask, "")) {
2012                 //printf("PPPD--ipcp_up, unnumbered, set wan_submask=%s\n", wan_submask);
2013                 strcpy(subnet_ip,wan_submask);
2014     }
2015     else 
2016     strcpy(subnet_ip, "255.255.255.255");
2017     if (ip_ntoa(ho->hisaddr))
2018         strcpy(router_ip, ip_ntoa(ho->hisaddr));
2019     if (go->dnsaddr[0]) {
2020         strcpy(dns_ip, "nameserver ");
2021         strcat(dns_ip, ip_ntoa(go->dnsaddr[0]));
2022     }
2023     if (go->dnsaddr[1]) {
2024         strcat(dns_ip, "\n");
2025         strcat(dns_ip, "nameserver ");
2026         strcat(dns_ip, ip_ntoa(go->dnsaddr[1]));
2027     }
2028     config_save();
2029 //Ported from 2.10.1. Charles 06/30/2003
2030         ppp_status=1;
2031 //Charles 07/07/2003, for PPP connect time history log
2032         ppp_start_time=time(0);
2033         write_conn_time(ppp_start_time);
2034 //Charles 08/29/2003, remove prevoius default route if any
2035 #ifndef INCLUDE_EMBHTTPD        
2036         if (demand != 0){               
2037                 sprintf(cmd, "route del default metric 120 dev ppp_%s 2> /dev/null", req_name);
2038                 system(cmd);
2039         }
2040 #else
2041         sprintf(cmd, "route del default metric 120 dev ppp_%s", req_name);
2042         system(cmd);
2043 #endif          
2044 //Ported from 2.10.1 Andy Lin 10/23/2003
2045 // brcm
2046     printf("PPP: PPP%s Connection Up.\n", req_name);
2047 #if !defined(ODM_LANG_LLL)    
2048     create_msg(BCM_PPPOE_CLIENT_STATE_UP); 
2049 #endif     
2050     //syslog(LOG_NOTICE,"Received valid IP address from server.  Connection UP.\n");
2051     syslog(LOG_NOTICE,"PPP Connection Up\n");   
2052 // brcm2
2053 //#ifdef BBB_XML_API //Wilson add, (04/18/2005)
2054 #if defined(SUPPORT_XML_API) //Wilson add, (03/14/2006)
2055     FILE *fp=NULL;
2056     fp = fopen("/var/pppStatus", "w+");
2057     if(fp){
2058         fprintf(fp, "3,0");
2059         fclose(fp);
2060     }
2061 #endif //endif BBB_XML_API
2062     redisconn=1;
2063         if (ppp_addgw == 1 ){
2064                 sprintf(cmd, "route add default gw %s dev ppp_%s", router_ip, req_name);
2065                 printf("PPP: %s\n", cmd);
2066                 system(cmd);
2067         }
2068 #if 0 //Andy move the rules to ifcntwkapi.cpp
2069         if (ppp_session == PPPOA){
2070                 sprintf(cmd, "iptables -D FORWARD -o ppp_%s -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu 2> /dev/null", req_name);
2071         system(cmd);
2072         sprintf(cmd, "iptables -D FORWARD -i ppp_%s -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu 2> /dev/null", req_name);
2073         system(cmd);
2074                 sprintf(cmd, "iptables -I FORWARD 1 -o ppp_%s -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu", req_name);
2075         system(cmd);
2076         sprintf(cmd, "iptables -I FORWARD 1 -i ppp_%s -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu", req_name);
2077         system(cmd);
2078         }
2079 #else   
2080         if (ppp_session == PPPOA && peer_mru[f->unit] != 1500){
2081                 sprintf(cmd, "iptables -D FORWARD -o ppp_%s -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu 2> /dev/null", req_name);
2082         system(cmd);
2083         sprintf(cmd, "iptables -D FORWARD -i ppp_%s -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu 2> /dev/null", req_name);
2084         system(cmd);
2085                 sprintf(cmd, "iptables -I FORWARD 1 -o ppp_%s -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu", req_name);
2086         system(cmd);
2087         sprintf(cmd, "iptables -I FORWARD 1 -i ppp_%s -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu", req_name);
2088         system(cmd);
2089         }
2090 #endif  
2091
2092 //Andy add
2093 #if 0
2094         if (strcmp(router_ip,"")!=0){
2095                 char cmd[50]="";
2096 #ifndef INCLUDE_EMBHTTPD
2097                 if (glbpppgw == 0){
2098 #endif
2099                         sprintf(cmd, "route del -host %s dev ppp%s", router_ip, req_name);
2100                         printf("app: %s\n", cmd);
2101                         system(cmd);
2102                         glbpppgw = 1;
2103 #ifndef INCLUDE_EMBHTTPD
2104                 }       
2105 #endif
2106                 sprintf(cmd, "route add -host %s dev ppp%s", router_ip, req_name);
2107                 printf("app: %s\n", cmd);
2108                 system(cmd);
2109         }
2110 #endif
2111
2112     if (ip_up_hook)
2113         ip_up_hook();
2114
2115     /*
2116      * Execute the ip-up script, like this:
2117      *  /etc/ppp/ip-up interface tty speed local-IP remote-IP
2118      */
2119     if (ipcp_script_state == s_down && ipcp_script_pid == 0) {
2120         ipcp_script_state = s_up;
2121 // brcm
2122 //      ipcp_script(_PATH_IPUP);
2123     }
2124 #if defined(ODM_LANG_LLL)
2125         struct hostent *h;
2126         int dnsFlag = 0;
2127         if (ppp_session == PPPOE){
2128                 sleep(1);
2129                 h = gethostbyname( "reachability.aol.com" );
2130                 if (h){   //lookup up reachability.aol.com success
2131                         dnsFlag = 1;//test success
2132                         printf("PPP:lookup up reachability.aol.com success.\n");
2133                 } else {  //lookup up reachability.aol.com fail
2134                         dnsFlag = 0;//test success
2135                         printf("PPP:lookup up reachability.aol.com fail.\n");
2136                 }
2137
2138         wsnfp = fopen("/var/btaolstatus", "w");
2139         if(wsnfp){
2140                 if (dnsFlag)
2141                         fprintf(wsnfp, "%d", 5);
2142                 else
2143                         fprintf(wsnfp, "%d", 4);        
2144             fclose(wsnfp);
2145                 }
2146                 printf("ppp:LLL test is Success!!\n");
2147         }
2148         got_ppp_down = 1;
2149 #endif
2150     // brcm
2151     if (autoscan) {
2152             ipcp_close(f->unit, "Autoscan down");
2153             need_holdoff = 0;
2154             create_msg(BCM_PPPOE_CLIENT_STATE_DOWN);
2155             return;
2156     }
2157
2158 }
2159
2160
2161 /*
2162  * ipcp_down - IPCP has gone DOWN.
2163  *
2164  * Take the IP network interface down, clear its addresses
2165  * and delete routes through it.
2166  */
2167 static void
2168 ipcp_down(f)
2169     fsm *f;
2170 {
2171 #ifdef SUPPORT_PPP_SCHEDULE
2172         extern int ppp_runonce;
2173         extern int kill_link;
2174         if(ppp_runonce) {
2175                 kill_link = 1;
2176                 persist = 0;
2177         }
2178 #endif
2179
2180 #if defined(SUPPORT_PPPDBG_SYSLOG)              
2181         andyreadlogstatus();
2182 #endif
2183 // brcm
2184     printf("PPP: PPP_%s Connection Down.\n", req_name);
2185     create_msg(BCM_PPPOE_CLIENT_STATE_DOWN);    
2186     syslog(LOG_WARNING,"PPP Connection Down\n");   
2187
2188 #if 0
2189 //Andy add
2190         if (strcmp(router_ip,"")!=0){
2191                 char cmd[50]="";
2192                 //sprintf(cmd, "route del -net %s netmask 255.255.255.255 dev ppp%d", router_ip, req_unit);
2193                 sprintf(cmd, "route del -host %s dev ppp%d", router_ip, req_unit);
2194                 printf("app: %s\n", cmd);
2195                 system(cmd);
2196         }
2197 #endif  
2198
2199 #if defined(SUPPORT_XML_API) //Wilson add, (03/16/2006)
2200         FILE *fp=NULL;
2201         fp = fopen("/var/pppStatus", "w+");
2202         if(fp){
2203             fprintf(fp, "1,0");
2204             fclose(fp);
2205         }
2206 #endif //endif BBB_XML_API
2207     IPCPDEBUG(("ipcp: down"));
2208     /* XXX a bit IPv4-centric here, we only need to get the stats
2209      * before the interface is marked down. */
2210     update_link_stats(f->unit);
2211     if (ip_down_hook)
2212         ip_down_hook();
2213     if (ipcp_is_up) {
2214         ipcp_is_up = 0;
2215         np_down(f->unit, PPP_IP);
2216     }
2217     sifvjcomp(f->unit, 0, 0, 0);
2218
2219     /*
2220      * If we are doing dial-on-demand, set the interface
2221      * to queue up outgoing packets (for now).
2222      */
2223     if (demand) {
2224         sifnpmode(f->unit, PPP_IP, NPMODE_QUEUE);
2225     } else {
2226         sifnpmode(f->unit, PPP_IP, NPMODE_DROP);
2227         sifdown(f->unit);
2228         ipcp_clear_addrs(f->unit, ipcp_gotoptions[f->unit].ouraddr,
2229                          ipcp_hisoptions[f->unit].hisaddr);
2230     }
2231
2232     /* Execute the ip-down script */
2233     if (ipcp_script_state == s_up && ipcp_script_pid == 0) {
2234         ipcp_script_state = s_down;
2235         // brcm
2236         //ipcp_script(_PATH_IPDOWN);
2237     }
2238
2239 //Charles 07/07/2003, log PPP connect time history only when PPP goes from UP to DOWN
2240     if(ppp_status) {
2241         ppp_end_time=time(0);
2242         write_conn_history(ppp_start_time, ppp_end_time);
2243     }
2244 //Charles 06/30/2003
2245         ppp_status=0;
2246 }
2247
2248
2249 /*
2250  * ipcp_clear_addrs() - clear the interface addresses, routes,
2251  * proxy arp entries, etc.
2252  */
2253 static void
2254 ipcp_clear_addrs(unit, ouraddr, hisaddr)
2255     int unit;
2256     u_int32_t ouraddr;  /* local address */
2257     u_int32_t hisaddr;  /* remote address */
2258 {
2259     if (proxy_arp_set[unit]) {
2260         cifproxyarp(unit, hisaddr);
2261         proxy_arp_set[unit] = 0;
2262     }
2263     if (default_route_set[unit]) {
2264         cifdefaultroute(unit, ouraddr, hisaddr);
2265         default_route_set[unit] = 0;
2266     }
2267     cifaddr(unit, ouraddr, hisaddr);
2268 }
2269
2270
2271 /*
2272  * ipcp_finished - possibly shut down the lower layers.
2273  */
2274 static void
2275 ipcp_finished(f)
2276     fsm *f;
2277 {
2278     np_finished(f->unit, PPP_IP);
2279 }
2280
2281
2282 /*
2283  * ipcp_script_done - called when the ip-up or ip-down script
2284  * has finished.
2285  */
2286 static void
2287 ipcp_script_done(arg)
2288     void *arg;
2289 {
2290     ipcp_script_pid = 0;
2291     switch (ipcp_script_state) {
2292     case s_up:
2293         if (ipcp_fsm[0].state != OPENED) {
2294             ipcp_script_state = s_down;
2295             ipcp_script(_PATH_IPDOWN);
2296         }
2297         break;
2298     case s_down:
2299         if (ipcp_fsm[0].state == OPENED) {
2300             ipcp_script_state = s_up;
2301             ipcp_script(_PATH_IPUP);
2302         }
2303         break;
2304     }
2305 }
2306
2307
2308 /*
2309  * ipcp_script - Execute a script with arguments
2310  * interface-name tty-name speed local-IP remote-IP.
2311  */
2312 static void
2313 ipcp_script(script)
2314     char *script;
2315 {
2316     char strspeed[32], strlocal[32], strremote[32];
2317     char *argv[8];
2318
2319     slprintf(strspeed, sizeof(strspeed), "%d", baud_rate);
2320     slprintf(strlocal, sizeof(strlocal), "%I", ipcp_gotoptions[0].ouraddr);
2321     slprintf(strremote, sizeof(strremote), "%I", ipcp_hisoptions[0].hisaddr);
2322
2323     argv[0] = script;
2324     argv[1] = ifname;
2325     argv[2] = devnam;
2326     argv[3] = strspeed;
2327     argv[4] = strlocal;
2328     argv[5] = strremote;
2329     argv[6] = ipparam;
2330     argv[7] = NULL;
2331     ipcp_script_pid = run_program(script, argv, 0, ipcp_script_done, NULL);
2332 }
2333
2334 /*
2335  * create_resolv - create the replacement resolv.conf file
2336  */
2337 static void
2338 create_resolv(peerdns1, peerdns2)
2339     u_int32_t peerdns1, peerdns2;
2340 {
2341     FILE *f;
2342
2343     // brcm
2344     if ((f = fopen(_PATH_RESOLV, "r")) > 0) {
2345         // the file already exists.
2346         fclose(f);
2347         return;
2348     }
2349
2350     f = fopen(_PATH_RESOLV, "w");
2351     if (f == NULL) {
2352         error("Failed to create %s: %m", _PATH_RESOLV);
2353         return;
2354     }
2355
2356     if (peerdns1)
2357         fprintf(f, "nameserver %s\n", ip_ntoa(peerdns1));
2358
2359     if (peerdns2)
2360         fprintf(f, "nameserver %s\n", ip_ntoa(peerdns2));
2361
2362     if (ferror(f))
2363         error("Write failed to %s: %m", _PATH_RESOLV);
2364
2365     fclose(f);
2366 }
2367
2368 /*
2369  * ipcp_printpkt - print the contents of an IPCP packet.
2370  */
2371 static char *ipcp_codenames[] = {
2372     "ConfReq", "ConfAck", "ConfNak", "ConfRej",
2373     "TermReq", "TermAck", "CodeRej"
2374 };
2375
2376 static int
2377 ipcp_printpkt(p, plen, printer, arg)
2378     u_char *p;
2379     int plen;
2380     void (*printer) __P((void *, char *, ...));
2381     void *arg;
2382 {
2383     int code, id, len, olen;
2384     u_char *pstart, *optend;
2385     u_short cishort;
2386     u_int32_t cilong;
2387
2388     if (plen < HEADERLEN)
2389         return 0;
2390     pstart = p;
2391     GETCHAR(code, p);
2392     GETCHAR(id, p);
2393     GETSHORT(len, p);
2394     if (len < HEADERLEN || len > plen)
2395         return 0;
2396
2397     if (code >= 1 && code <= sizeof(ipcp_codenames) / sizeof(char *))
2398         printer(arg, " %s", ipcp_codenames[code-1]);
2399     else
2400         printer(arg, " code=0x%x", code);
2401     printer(arg, " id=0x%x", id);
2402     len -= HEADERLEN;
2403     switch (code) {
2404     case CONFREQ:
2405     case CONFACK:
2406     case CONFNAK:
2407     case CONFREJ:
2408         /* print option list */
2409         while (len >= 2) {
2410             GETCHAR(code, p);
2411             GETCHAR(olen, p);
2412             p -= 2;
2413             if (olen < 2 || olen > len) {
2414                 break;
2415             }
2416             printer(arg, " <");
2417             len -= olen;
2418             optend = p + olen;
2419             switch (code) {
2420             case CI_ADDRS:
2421                 if (olen == CILEN_ADDRS) {
2422                     p += 2;
2423                     GETLONG(cilong, p);
2424                     printer(arg, "addrs %I", htonl(cilong));
2425                     GETLONG(cilong, p);
2426                     printer(arg, " %I", htonl(cilong));
2427                 }
2428                 break;
2429             case CI_COMPRESSTYPE:
2430                 if (olen >= CILEN_COMPRESS) {
2431                     p += 2;
2432                     GETSHORT(cishort, p);
2433                     printer(arg, "compress ");
2434                     switch (cishort) {
2435                     case IPCP_VJ_COMP:
2436                         printer(arg, "VJ");
2437                         break;
2438                     case IPCP_VJ_COMP_OLD:
2439                         printer(arg, "old-VJ");
2440                         break;
2441                     default:
2442                         printer(arg, "0x%x", cishort);
2443                     }
2444                 }
2445                 break;
2446             case CI_ADDR:
2447                 if (olen == CILEN_ADDR) {
2448                     p += 2;
2449                     GETLONG(cilong, p);
2450                     printer(arg, "addr %I", htonl(cilong));
2451                 }
2452                 break;
2453             case CI_MS_DNS1:
2454             case CI_MS_DNS2:
2455                 p += 2;
2456                 GETLONG(cilong, p);
2457                 printer(arg, "ms-dns%d %I", code - CI_MS_DNS1 + 1,
2458                         htonl(cilong));
2459                 break;
2460             case CI_MS_WINS1:
2461             case CI_MS_WINS2:
2462                 p += 2;
2463                 GETLONG(cilong, p);
2464                 printer(arg, "ms-wins %I", htonl(cilong));
2465                 break;
2466             }
2467             while (p < optend) {
2468                 GETCHAR(code, p);
2469                 printer(arg, " %.2x", code);
2470             }
2471             printer(arg, ">");
2472         }
2473         break;
2474
2475     case TERMACK:
2476     case TERMREQ:
2477         if (len > 0 && *p >= ' ' && *p < 0x7f) {
2478             printer(arg, " ");
2479             print_string((char *)p, len, printer, arg);
2480             p += len;
2481             len = 0;
2482         }
2483         break;
2484     }
2485
2486     /* print the rest of the bytes in the packet */
2487     for (; len > 0; --len) {
2488         GETCHAR(code, p);
2489         printer(arg, " %.2x", code);
2490     }
2491
2492     return p - pstart;
2493 }
2494
2495 /*
2496  * ip_active_pkt - see if this IP packet is worth bringing the link up for.
2497  * We don't bring the link up for IP fragments or for TCP FIN packets
2498  * with no data.
2499  */
2500 #define IP_HDRLEN       20      /* bytes */
2501 #define IP_OFFMASK      0x1fff
2502 #define IPPROTO_TCP     6
2503 #define TCP_HDRLEN      20
2504 #define TH_FIN          0x01
2505
2506 /*
2507  * We use these macros because the IP header may be at an odd address,
2508  * and some compilers might use word loads to get th_off or ip_hl.
2509  */
2510
2511 #define net_short(x)    (((x)[0] << 8) + (x)[1])
2512 #define get_iphl(x)     (((unsigned char *)(x))[0] & 0xF)
2513 #define get_ipoff(x)    net_short((unsigned char *)(x) + 6)
2514 #define get_ipproto(x)  (((unsigned char *)(x))[9])
2515 #define get_tcpoff(x)   (((unsigned char *)(x))[12] >> 4)
2516 #define get_tcpflags(x) (((unsigned char *)(x))[13])
2517
2518 static int
2519 ip_active_pkt(pkt, len)
2520     u_char *pkt;
2521     int len;
2522 {
2523     u_char *tcp;
2524     int hlen;
2525
2526     len -= PPP_HDRLEN;
2527     pkt += PPP_HDRLEN;
2528     if (len < IP_HDRLEN)
2529         return 0;
2530     if ((get_ipoff(pkt) & IP_OFFMASK) != 0)
2531         return 0;
2532     if (get_ipproto(pkt) != IPPROTO_TCP)
2533         return 1;
2534     hlen = get_iphl(pkt) * 4;
2535     if (len < hlen + TCP_HDRLEN)
2536         return 0;
2537     tcp = pkt + hlen;
2538     if ((get_tcpflags(tcp) & TH_FIN) != 0 && len == hlen + get_tcpoff(tcp) * 4)
2539         return 0;
2540     return 1;
2541 }