0d62ed6de8d3e7b0c165e2beed2fd0927ec5191b
[dragonfly.git] / usr.sbin / ppp / ipcp.c
1 /*-
2  * Copyright (c) 1996 - 2001 Brian Somers <brian@Awfulhak.org>
3  *          based on work by Toshiharu OHNO <tony-o@iij.ad.jp>
4  *                           Internet Initiative Japan, Inc (IIJ)
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD: src/usr.sbin/ppp/ipcp.c,v 1.90.2.12 2002/09/28 10:16:25 brian Exp $
29  * $DragonFly: src/usr.sbin/ppp/ipcp.c,v 1.2 2003/06/17 04:30:00 dillon Exp $
30  */
31
32 #include <sys/param.h>
33 #include <netinet/in_systm.h>
34 #include <netinet/in.h>
35 #include <netinet/ip.h>
36 #include <arpa/inet.h>
37 #include <sys/socket.h>
38 #include <net/if.h>
39 #include <net/route.h>
40 #include <netdb.h>
41 #include <sys/un.h>
42
43 #include <errno.h>
44 #include <fcntl.h>
45 #include <resolv.h>
46 #include <stdarg.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <sys/stat.h>
50 #include <termios.h>
51 #include <unistd.h>
52
53 #ifndef NONAT
54 #ifdef LOCALNAT
55 #include "alias.h"
56 #else
57 #include <alias.h>
58 #endif
59 #endif
60
61 #include "layer.h"
62 #include "ua.h"
63 #include "defs.h"
64 #include "command.h"
65 #include "mbuf.h"
66 #include "log.h"
67 #include "timer.h"
68 #include "fsm.h"
69 #include "proto.h"
70 #include "iplist.h"
71 #include "throughput.h"
72 #include "slcompress.h"
73 #include "lqr.h"
74 #include "hdlc.h"
75 #include "lcp.h"
76 #include "ncpaddr.h"
77 #include "ip.h"
78 #include "ipcp.h"
79 #include "filter.h"
80 #include "descriptor.h"
81 #include "vjcomp.h"
82 #include "async.h"
83 #include "ccp.h"
84 #include "link.h"
85 #include "physical.h"
86 #include "mp.h"
87 #ifndef NORADIUS
88 #include "radius.h"
89 #endif
90 #include "ipv6cp.h"
91 #include "ncp.h"
92 #include "bundle.h"
93 #include "id.h"
94 #include "arp.h"
95 #include "systems.h"
96 #include "prompt.h"
97 #include "route.h"
98 #include "iface.h"
99
100 #undef REJECTED
101 #define REJECTED(p, x)  ((p)->peer_reject & (1<<(x)))
102 #define issep(ch) ((ch) == ' ' || (ch) == '\t')
103 #define isip(ch) (((ch) >= '0' && (ch) <= '9') || (ch) == '.')
104
105 struct compreq {
106   u_short proto;
107   u_char slots;
108   u_char compcid;
109 };
110
111 static int IpcpLayerUp(struct fsm *);
112 static void IpcpLayerDown(struct fsm *);
113 static void IpcpLayerStart(struct fsm *);
114 static void IpcpLayerFinish(struct fsm *);
115 static void IpcpInitRestartCounter(struct fsm *, int);
116 static void IpcpSendConfigReq(struct fsm *);
117 static void IpcpSentTerminateReq(struct fsm *);
118 static void IpcpSendTerminateAck(struct fsm *, u_char);
119 static void IpcpDecodeConfig(struct fsm *, u_char *, u_char *, int,
120                              struct fsm_decode *);
121
122 static struct fsm_callbacks ipcp_Callbacks = {
123   IpcpLayerUp,
124   IpcpLayerDown,
125   IpcpLayerStart,
126   IpcpLayerFinish,
127   IpcpInitRestartCounter,
128   IpcpSendConfigReq,
129   IpcpSentTerminateReq,
130   IpcpSendTerminateAck,
131   IpcpDecodeConfig,
132   fsm_NullRecvResetReq,
133   fsm_NullRecvResetAck
134 };
135
136 static const char *
137 protoname(int proto)
138 {
139   static struct {
140     int id;
141     const char *txt;
142   } cftypes[] = {
143     /* Check out the latest ``Assigned numbers'' rfc (rfc1700.txt) */
144     { 1, "IPADDRS" },           /* IP-Addresses */      /* deprecated */
145     { 2, "COMPPROTO" },         /* IP-Compression-Protocol */
146     { 3, "IPADDR" },            /* IP-Address */
147     { 129, "PRIDNS" },          /* 129: Primary DNS Server Address */
148     { 130, "PRINBNS" },         /* 130: Primary NBNS Server Address */
149     { 131, "SECDNS" },          /* 131: Secondary DNS Server Address */
150     { 132, "SECNBNS" }          /* 132: Secondary NBNS Server Address */
151   };
152   unsigned f;
153
154   for (f = 0; f < sizeof cftypes / sizeof *cftypes; f++)
155     if (cftypes[f].id == proto)
156       return cftypes[f].txt;
157
158   return NumStr(proto, NULL, 0);
159 }
160
161 void
162 ipcp_AddInOctets(struct ipcp *ipcp, int n)
163 {
164   throughput_addin(&ipcp->throughput, n);
165 }
166
167 void
168 ipcp_AddOutOctets(struct ipcp *ipcp, int n)
169 {
170   throughput_addout(&ipcp->throughput, n);
171 }
172
173 void
174 ipcp_LoadDNS(struct ipcp *ipcp)
175 {
176   int fd;
177
178   ipcp->ns.dns[0].s_addr = ipcp->ns.dns[1].s_addr = INADDR_NONE;
179
180   if (ipcp->ns.resolv != NULL) {
181     free(ipcp->ns.resolv);
182     ipcp->ns.resolv = NULL;
183   }
184   if (ipcp->ns.resolv_nons != NULL) {
185     free(ipcp->ns.resolv_nons);
186     ipcp->ns.resolv_nons = NULL;
187   }
188   ipcp->ns.resolver = 0;
189
190   if ((fd = open(_PATH_RESCONF, O_RDONLY)) != -1) {
191     struct stat st;
192
193     if (fstat(fd, &st) == 0) {
194       ssize_t got;
195
196       if ((ipcp->ns.resolv_nons = (char *)malloc(st.st_size + 1)) == NULL)
197         log_Printf(LogERROR, "Failed to malloc %lu for %s: %s\n",
198                    (unsigned long)st.st_size, _PATH_RESCONF, strerror(errno));
199       else if ((ipcp->ns.resolv = (char *)malloc(st.st_size + 1)) == NULL) {
200         log_Printf(LogERROR, "Failed(2) to malloc %lu for %s: %s\n",
201                    (unsigned long)st.st_size, _PATH_RESCONF, strerror(errno));
202         free(ipcp->ns.resolv_nons);
203         ipcp->ns.resolv_nons = NULL;
204       } else if ((got = read(fd, ipcp->ns.resolv, st.st_size)) != st.st_size) {
205         if (got == -1)
206           log_Printf(LogERROR, "Failed to read %s: %s\n",
207                      _PATH_RESCONF, strerror(errno));
208         else
209           log_Printf(LogERROR, "Failed to read %s, got %lu not %lu\n",
210                      _PATH_RESCONF, (unsigned long)got,
211                      (unsigned long)st.st_size);
212         free(ipcp->ns.resolv_nons);
213         ipcp->ns.resolv_nons = NULL;
214         free(ipcp->ns.resolv);
215         ipcp->ns.resolv = NULL;
216       } else {
217         char *cp, *cp_nons, *ncp, ch;
218         int n;
219
220         ipcp->ns.resolv[st.st_size] = '\0';
221         ipcp->ns.resolver = 1;
222
223         cp_nons = ipcp->ns.resolv_nons;
224         cp = ipcp->ns.resolv;
225         n = 0;
226
227         while ((ncp = strstr(cp, "nameserver")) != NULL) {
228           if (ncp != cp) {
229             memcpy(cp_nons, cp, ncp - cp);
230             cp_nons += ncp - cp;
231           }
232           if ((ncp != cp && ncp[-1] != '\n') || !issep(ncp[10])) {
233             memcpy(cp_nons, ncp, 9);
234             cp_nons += 9;
235             cp = ncp + 9;       /* Can't match "nameserver" at cp... */
236             continue;
237           }
238
239           for (cp = ncp + 11; issep(*cp); cp++) /* Skip whitespace */
240             ;
241
242           for (ncp = cp; isip(*ncp); ncp++)             /* Jump over IP */
243             ;
244
245           ch = *ncp;
246           *ncp = '\0';
247           if (n < 2 && inet_aton(cp, ipcp->ns.dns))
248             n++;
249           *ncp = ch;
250
251           if ((cp = strchr(ncp, '\n')) == NULL) /* Point at next line */
252             cp = ncp + strlen(ncp);
253           else
254             cp++;
255         }
256         strcpy(cp_nons, cp);    /* Copy the end - including the NUL */
257         cp_nons += strlen(cp_nons) - 1;
258         while (cp_nons >= ipcp->ns.resolv_nons && *cp_nons == '\n')
259           *cp_nons-- = '\0';
260         if (n == 2 && ipcp->ns.dns[0].s_addr == INADDR_ANY) {
261           ipcp->ns.dns[0].s_addr = ipcp->ns.dns[1].s_addr;
262           ipcp->ns.dns[1].s_addr = INADDR_ANY;
263         }
264         bundle_AdjustDNS(ipcp->fsm.bundle);
265       }
266     } else
267       log_Printf(LogERROR, "Failed to stat opened %s: %s\n",
268                  _PATH_RESCONF, strerror(errno));
269
270     close(fd);
271   }
272 }
273
274 int
275 ipcp_WriteDNS(struct ipcp *ipcp)
276 {
277   const char *paddr;
278   mode_t mask;
279   FILE *fp;
280
281   if (ipcp->ns.dns[0].s_addr == INADDR_ANY &&
282       ipcp->ns.dns[1].s_addr == INADDR_ANY) {
283     log_Printf(LogIPCP, "%s not modified: All nameservers NAKd\n",
284               _PATH_RESCONF);
285     return 0;
286   }
287
288   if (ipcp->ns.dns[0].s_addr == INADDR_ANY) {
289     ipcp->ns.dns[0].s_addr = ipcp->ns.dns[1].s_addr;
290     ipcp->ns.dns[1].s_addr = INADDR_ANY;
291   }
292
293   mask = umask(022);
294   if ((fp = ID0fopen(_PATH_RESCONF, "w")) != NULL) {
295     umask(mask);
296     if (ipcp->ns.resolv_nons)
297       fputs(ipcp->ns.resolv_nons, fp);
298     paddr = inet_ntoa(ipcp->ns.dns[0]);
299     log_Printf(LogIPCP, "Primary nameserver set to %s\n", paddr);
300     fprintf(fp, "\nnameserver %s\n", paddr);
301     if (ipcp->ns.dns[1].s_addr != INADDR_ANY &&
302         ipcp->ns.dns[1].s_addr != INADDR_NONE &&
303         ipcp->ns.dns[1].s_addr != ipcp->ns.dns[0].s_addr) {
304       paddr = inet_ntoa(ipcp->ns.dns[1]);
305       log_Printf(LogIPCP, "Secondary nameserver set to %s\n", paddr);
306       fprintf(fp, "nameserver %s\n", paddr);
307     }
308     if (fclose(fp) == EOF) {
309       log_Printf(LogERROR, "write(): Failed updating %s: %s\n", _PATH_RESCONF,
310                  strerror(errno));
311       return 0;
312     }
313   } else
314     umask(mask);
315
316   return 1;
317 }
318
319 void
320 ipcp_RestoreDNS(struct ipcp *ipcp)
321 {
322   if (ipcp->ns.resolver) {
323     ssize_t got, len;
324     int fd;
325
326     if ((fd = ID0open(_PATH_RESCONF, O_WRONLY|O_TRUNC, 0644)) != -1) {
327       len = strlen(ipcp->ns.resolv);
328       if ((got = write(fd, ipcp->ns.resolv, len)) != len) {
329         if (got == -1)
330           log_Printf(LogERROR, "Failed rewriting %s: write: %s\n",
331                      _PATH_RESCONF, strerror(errno));
332         else
333           log_Printf(LogERROR, "Failed rewriting %s: wrote %ld of %ld\n",
334                      _PATH_RESCONF, (long)got, (long)len);
335       }
336       close(fd);
337     } else
338       log_Printf(LogERROR, "Failed rewriting %s: open: %s\n", _PATH_RESCONF,
339                  strerror(errno));
340   } else if (remove(_PATH_RESCONF) == -1)
341     log_Printf(LogERROR, "Failed removing %s: %s\n", _PATH_RESCONF,
342                strerror(errno));
343
344 }
345
346 int
347 ipcp_Show(struct cmdargs const *arg)
348 {
349   struct ipcp *ipcp = &arg->bundle->ncp.ipcp;
350
351   prompt_Printf(arg->prompt, "%s [%s]\n", ipcp->fsm.name,
352                 State2Nam(ipcp->fsm.state));
353   if (ipcp->fsm.state == ST_OPENED) {
354     prompt_Printf(arg->prompt, " His side:        %s, %s\n",
355                   inet_ntoa(ipcp->peer_ip), vj2asc(ipcp->peer_compproto));
356     prompt_Printf(arg->prompt, " My side:         %s, %s\n",
357                   inet_ntoa(ipcp->my_ip), vj2asc(ipcp->my_compproto));
358     prompt_Printf(arg->prompt, " Queued packets:  %lu\n",
359                   (unsigned long)ipcp_QueueLen(ipcp));
360   }
361
362   prompt_Printf(arg->prompt, "\nDefaults:\n");
363   prompt_Printf(arg->prompt, " FSM retry = %us, max %u Config"
364                 " REQ%s, %u Term REQ%s\n", ipcp->cfg.fsm.timeout,
365                 ipcp->cfg.fsm.maxreq, ipcp->cfg.fsm.maxreq == 1 ? "" : "s",
366                 ipcp->cfg.fsm.maxtrm, ipcp->cfg.fsm.maxtrm == 1 ? "" : "s");
367   prompt_Printf(arg->prompt, " My Address:      %s\n",
368                 ncprange_ntoa(&ipcp->cfg.my_range));
369   if (ipcp->cfg.HaveTriggerAddress)
370     prompt_Printf(arg->prompt, " Trigger address: %s\n",
371                   inet_ntoa(ipcp->cfg.TriggerAddress));
372
373   prompt_Printf(arg->prompt, " VJ compression:  %s (%d slots %s slot "
374                 "compression)\n", command_ShowNegval(ipcp->cfg.vj.neg),
375                 ipcp->cfg.vj.slots, ipcp->cfg.vj.slotcomp ? "with" : "without");
376
377   if (iplist_isvalid(&ipcp->cfg.peer_list))
378     prompt_Printf(arg->prompt, " His Address:     %s\n",
379                   ipcp->cfg.peer_list.src);
380   else
381     prompt_Printf(arg->prompt, " His Address:     %s\n",
382                   ncprange_ntoa(&ipcp->cfg.peer_range));
383
384   prompt_Printf(arg->prompt, " DNS:             %s",
385                 ipcp->cfg.ns.dns[0].s_addr == INADDR_NONE ?
386                 "none" : inet_ntoa(ipcp->cfg.ns.dns[0]));
387   if (ipcp->cfg.ns.dns[1].s_addr != INADDR_NONE)
388     prompt_Printf(arg->prompt, ", %s",
389                   inet_ntoa(ipcp->cfg.ns.dns[1]));
390   prompt_Printf(arg->prompt, ", %s\n",
391                 command_ShowNegval(ipcp->cfg.ns.dns_neg));
392   prompt_Printf(arg->prompt, " Resolver DNS:    %s",
393                 ipcp->ns.dns[0].s_addr == INADDR_NONE ?
394                 "none" : inet_ntoa(ipcp->ns.dns[0]));
395   if (ipcp->ns.dns[1].s_addr != INADDR_NONE &&
396       ipcp->ns.dns[1].s_addr != ipcp->ns.dns[0].s_addr)
397     prompt_Printf(arg->prompt, ", %s",
398                   inet_ntoa(ipcp->ns.dns[1]));
399   prompt_Printf(arg->prompt, "\n NetBIOS NS:      %s, ",
400                 inet_ntoa(ipcp->cfg.ns.nbns[0]));
401   prompt_Printf(arg->prompt, "%s\n\n",
402                 inet_ntoa(ipcp->cfg.ns.nbns[1]));
403
404   throughput_disp(&ipcp->throughput, arg->prompt);
405
406   return 0;
407 }
408
409 int
410 ipcp_vjset(struct cmdargs const *arg)
411 {
412   if (arg->argc != arg->argn+2)
413     return -1;
414   if (!strcasecmp(arg->argv[arg->argn], "slots")) {
415     int slots;
416
417     slots = atoi(arg->argv[arg->argn+1]);
418     if (slots < 4 || slots > 16)
419       return 1;
420     arg->bundle->ncp.ipcp.cfg.vj.slots = slots;
421     return 0;
422   } else if (!strcasecmp(arg->argv[arg->argn], "slotcomp")) {
423     if (!strcasecmp(arg->argv[arg->argn+1], "on"))
424       arg->bundle->ncp.ipcp.cfg.vj.slotcomp = 1;
425     else if (!strcasecmp(arg->argv[arg->argn+1], "off"))
426       arg->bundle->ncp.ipcp.cfg.vj.slotcomp = 0;
427     else
428       return 2;
429     return 0;
430   }
431   return -1;
432 }
433
434 void
435 ipcp_Init(struct ipcp *ipcp, struct bundle *bundle, struct link *l,
436           const struct fsm_parent *parent)
437 {
438   struct hostent *hp;
439   struct in_addr host;
440   char name[MAXHOSTNAMELEN];
441   static const char * const timer_names[] =
442     {"IPCP restart", "IPCP openmode", "IPCP stopped"};
443
444   fsm_Init(&ipcp->fsm, "IPCP", PROTO_IPCP, 1, IPCP_MAXCODE, LogIPCP,
445            bundle, l, parent, &ipcp_Callbacks, timer_names);
446
447   ipcp->cfg.vj.slots = DEF_VJ_STATES;
448   ipcp->cfg.vj.slotcomp = 1;
449   memset(&ipcp->cfg.my_range, '\0', sizeof ipcp->cfg.my_range);
450
451   host.s_addr = htonl(INADDR_LOOPBACK);
452   ipcp->cfg.netmask.s_addr = INADDR_ANY;
453   if (gethostname(name, sizeof name) == 0) {
454     hp = gethostbyname(name);
455     if (hp && hp->h_addrtype == AF_INET && hp->h_length == sizeof host.s_addr)
456       memcpy(&host.s_addr, hp->h_addr, sizeof host.s_addr);
457   }
458   ncprange_setip4(&ipcp->cfg.my_range, host, ipcp->cfg.netmask);
459   ncprange_setip4(&ipcp->cfg.peer_range, ipcp->cfg.netmask, ipcp->cfg.netmask);
460
461   iplist_setsrc(&ipcp->cfg.peer_list, "");
462   ipcp->cfg.HaveTriggerAddress = 0;
463
464   ipcp->cfg.ns.dns[0].s_addr = INADDR_NONE;
465   ipcp->cfg.ns.dns[1].s_addr = INADDR_NONE;
466   ipcp->cfg.ns.dns_neg = 0;
467   ipcp->cfg.ns.nbns[0].s_addr = INADDR_ANY;
468   ipcp->cfg.ns.nbns[1].s_addr = INADDR_ANY;
469
470   ipcp->cfg.fsm.timeout = DEF_FSMRETRY;
471   ipcp->cfg.fsm.maxreq = DEF_FSMTRIES;
472   ipcp->cfg.fsm.maxtrm = DEF_FSMTRIES;
473   ipcp->cfg.vj.neg = NEG_ENABLED|NEG_ACCEPTED;
474
475   memset(&ipcp->vj, '\0', sizeof ipcp->vj);
476
477   ipcp->ns.resolv = NULL;
478   ipcp->ns.resolv_nons = NULL;
479   ipcp->ns.writable = 1;
480   ipcp_LoadDNS(ipcp);
481
482   throughput_init(&ipcp->throughput, SAMPLE_PERIOD);
483   memset(ipcp->Queue, '\0', sizeof ipcp->Queue);
484   ipcp_Setup(ipcp, INADDR_NONE);
485 }
486
487 void
488 ipcp_Destroy(struct ipcp *ipcp)
489 {
490   throughput_destroy(&ipcp->throughput);
491
492   if (ipcp->ns.resolv != NULL) {
493     free(ipcp->ns.resolv);
494     ipcp->ns.resolv = NULL;
495   }
496   if (ipcp->ns.resolv_nons != NULL) {
497     free(ipcp->ns.resolv_nons);
498     ipcp->ns.resolv_nons = NULL;
499   }
500 }
501
502 void
503 ipcp_SetLink(struct ipcp *ipcp, struct link *l)
504 {
505   ipcp->fsm.link = l;
506 }
507
508 void
509 ipcp_Setup(struct ipcp *ipcp, u_int32_t mask)
510 {
511   struct iface *iface = ipcp->fsm.bundle->iface;
512   struct ncpaddr ipaddr;
513   struct in_addr peer;
514   int pos;
515   unsigned n;
516
517   ipcp->fsm.open_mode = 0;
518   ipcp->ifmask.s_addr = mask == INADDR_NONE ? ipcp->cfg.netmask.s_addr : mask;
519
520   if (iplist_isvalid(&ipcp->cfg.peer_list)) {
521     /* Try to give the peer a previously configured IP address */
522     for (n = 0; n < iface->addrs; n++) {
523       if (!ncpaddr_getip4(&iface->addr[n].peer, &peer))
524         continue;
525       if ((pos = iplist_ip2pos(&ipcp->cfg.peer_list, peer)) != -1) {
526         ncpaddr_setip4(&ipaddr, iplist_setcurpos(&ipcp->cfg.peer_list, pos));
527         break;
528       }
529     }
530     if (n == iface->addrs)
531       /* Ok, so none of 'em fit.... pick a random one */
532       ncpaddr_setip4(&ipaddr, iplist_setrandpos(&ipcp->cfg.peer_list));
533
534     ncprange_sethost(&ipcp->cfg.peer_range, &ipaddr);
535   }
536
537   ipcp->heis1172 = 0;
538   ipcp->peer_req = 0;
539   ncprange_getip4addr(&ipcp->cfg.peer_range, &ipcp->peer_ip);
540   ipcp->peer_compproto = 0;
541
542   if (ipcp->cfg.HaveTriggerAddress) {
543     /*
544      * Some implementations of PPP require that we send a
545      * *special* value as our address, even though the rfc specifies
546      * full negotiation (e.g. "0.0.0.0" or Not "0.0.0.0").
547      */
548     ipcp->my_ip = ipcp->cfg.TriggerAddress;
549     log_Printf(LogIPCP, "Using trigger address %s\n",
550               inet_ntoa(ipcp->cfg.TriggerAddress));
551   } else {
552     /*
553      * Otherwise, if we've used an IP number before and it's still within
554      * the network specified on the ``set ifaddr'' line, we really
555      * want to keep that IP number so that we can keep any existing
556      * connections that are bound to that IP.
557      */
558     for (n = 0; n < iface->addrs; n++) {
559       ncprange_getaddr(&iface->addr[n].ifa, &ipaddr);
560       if (ncprange_contains(&ipcp->cfg.my_range, &ipaddr)) {
561         ncpaddr_getip4(&ipaddr, &ipcp->my_ip);
562         break;
563       }
564     }
565     if (n == iface->addrs)
566       ncprange_getip4addr(&ipcp->cfg.my_range, &ipcp->my_ip);
567   }
568
569   if (IsEnabled(ipcp->cfg.vj.neg)
570 #ifndef NORADIUS
571       || (ipcp->fsm.bundle->radius.valid && ipcp->fsm.bundle->radius.vj)
572 #endif
573      )
574     ipcp->my_compproto = (PROTO_VJCOMP << 16) +
575                          ((ipcp->cfg.vj.slots - 1) << 8) +
576                          ipcp->cfg.vj.slotcomp;
577   else
578     ipcp->my_compproto = 0;
579   sl_compress_init(&ipcp->vj.cslc, ipcp->cfg.vj.slots - 1);
580
581   ipcp->peer_reject = 0;
582   ipcp->my_reject = 0;
583
584   /* Copy startup values into ipcp->ns.dns */
585   if (ipcp->cfg.ns.dns[0].s_addr != INADDR_NONE)
586     memcpy(ipcp->ns.dns, ipcp->cfg.ns.dns, sizeof ipcp->ns.dns);
587 }
588
589 static int
590 numaddresses(struct in_addr mask)
591 {
592   u_int32_t bit, haddr;
593   int n;
594
595   haddr = ntohl(mask.s_addr);
596   bit = 1;
597   n = 1;
598
599   do {
600     if (!(haddr & bit))
601       n <<= 1;
602   } while (bit <<= 1);
603
604   return n;
605 }
606
607 static int
608 ipcp_proxyarp(struct ipcp *ipcp,
609               int (*proxyfun)(struct bundle *, struct in_addr),
610               const struct iface_addr *addr)
611 {
612   struct bundle *bundle = ipcp->fsm.bundle;
613   struct in_addr peer, mask, ip;
614   int n, ret;
615
616   mask.s_addr = 0;      /* avoid gcc warnings */
617
618   if (!ncpaddr_getip4(&addr->peer, &peer)) {
619     log_Printf(LogERROR, "Oops, ipcp_proxyarp() called with unexpected addr\n");
620     return 0;
621   }
622
623   ret = 0;
624
625   if (Enabled(bundle, OPT_PROXYALL)) {
626     ncprange_getip4mask(&addr->ifa, &mask);
627     if ((n = numaddresses(mask)) > 256) {
628       log_Printf(LogWARN, "%s: Too many addresses for proxyall\n",
629                  ncprange_ntoa(&addr->ifa));
630       return 0;
631     }
632     ip.s_addr = peer.s_addr & mask.s_addr;
633     if (n >= 4) {
634       ip.s_addr = htonl(ntohl(ip.s_addr) + 1);
635       n -= 2;
636     }
637     while (n) {
638       if (!((ip.s_addr ^ peer.s_addr) & mask.s_addr)) {
639         if (!(ret = (*proxyfun)(bundle, ip)))
640           break;
641         n--;
642       }
643       ip.s_addr = htonl(ntohl(ip.s_addr) + 1);
644     }
645     ret = !n;
646   } else if (Enabled(bundle, OPT_PROXY))
647     ret = (*proxyfun)(bundle, peer);
648
649   return ret;
650 }
651
652 static int
653 ipcp_SetIPaddress(struct ipcp *ipcp, struct in_addr myaddr,
654                   struct in_addr hisaddr)
655 {
656   struct bundle *bundle = ipcp->fsm.bundle;
657   struct ncpaddr myncpaddr, hisncpaddr;
658   struct ncprange myrange;
659   struct in_addr mask;
660   struct sockaddr_storage ssdst, ssgw, ssmask;
661   struct sockaddr *sadst, *sagw, *samask;
662
663   sadst = (struct sockaddr *)&ssdst;
664   sagw = (struct sockaddr *)&ssgw;
665   samask = (struct sockaddr *)&ssmask;
666
667   ncpaddr_setip4(&hisncpaddr, hisaddr);
668   ncpaddr_setip4(&myncpaddr, myaddr);
669   ncprange_sethost(&myrange, &myncpaddr);
670
671   mask = addr2mask(myaddr);
672
673   if (ipcp->ifmask.s_addr != INADDR_ANY &&
674       (ipcp->ifmask.s_addr & mask.s_addr) == mask.s_addr)
675     ncprange_setip4mask(&myrange, ipcp->ifmask);
676
677   if (!iface_Add(bundle->iface, &bundle->ncp, &myrange, &hisncpaddr,
678                  IFACE_ADD_FIRST|IFACE_FORCE_ADD|IFACE_SYSTEM))
679     return 0;
680
681   if (!Enabled(bundle, OPT_IFACEALIAS))
682     iface_Clear(bundle->iface, &bundle->ncp, AF_INET,
683                 IFACE_CLEAR_ALIASES|IFACE_SYSTEM);
684
685   if (bundle->ncp.cfg.sendpipe > 0 || bundle->ncp.cfg.recvpipe > 0) {
686     ncprange_getsa(&myrange, &ssgw, &ssmask);
687     ncpaddr_getsa(&hisncpaddr, &ssdst);
688     rt_Update(bundle, sadst, sagw, samask);
689   }
690
691   if (Enabled(bundle, OPT_SROUTES))
692     route_Change(bundle, bundle->ncp.route, &myncpaddr, &hisncpaddr);
693
694 #ifndef NORADIUS
695   if (bundle->radius.valid)
696     route_Change(bundle, bundle->radius.routes, &myncpaddr, &hisncpaddr);
697 #endif
698
699   return 1;     /* Ok */
700 }
701
702 static struct in_addr
703 ChooseHisAddr(struct bundle *bundle, struct in_addr gw)
704 {
705   struct in_addr try;
706   u_long f;
707
708   for (f = 0; f < bundle->ncp.ipcp.cfg.peer_list.nItems; f++) {
709     try = iplist_next(&bundle->ncp.ipcp.cfg.peer_list);
710     log_Printf(LogDEBUG, "ChooseHisAddr: Check item %ld (%s)\n",
711               f, inet_ntoa(try));
712     if (ipcp_SetIPaddress(&bundle->ncp.ipcp, gw, try)) {
713       log_Printf(LogIPCP, "Selected IP address %s\n", inet_ntoa(try));
714       break;
715     }
716   }
717
718   if (f == bundle->ncp.ipcp.cfg.peer_list.nItems) {
719     log_Printf(LogDEBUG, "ChooseHisAddr: All addresses in use !\n");
720     try.s_addr = INADDR_ANY;
721   }
722
723   return try;
724 }
725
726 static void
727 IpcpInitRestartCounter(struct fsm *fp, int what)
728 {
729   /* Set fsm timer load */
730   struct ipcp *ipcp = fsm2ipcp(fp);
731
732   fp->FsmTimer.load = ipcp->cfg.fsm.timeout * SECTICKS;
733   switch (what) {
734     case FSM_REQ_TIMER:
735       fp->restart = ipcp->cfg.fsm.maxreq;
736       break;
737     case FSM_TRM_TIMER:
738       fp->restart = ipcp->cfg.fsm.maxtrm;
739       break;
740     default:
741       fp->restart = 1;
742       break;
743   }
744 }
745
746 static void
747 IpcpSendConfigReq(struct fsm *fp)
748 {
749   /* Send config REQ please */
750   struct physical *p = link2physical(fp->link);
751   struct ipcp *ipcp = fsm2ipcp(fp);
752   u_char buff[24];
753   struct fsm_opt *o;
754
755   o = (struct fsm_opt *)buff;
756
757   if ((p && !physical_IsSync(p)) || !REJECTED(ipcp, TY_IPADDR)) {
758     memcpy(o->data, &ipcp->my_ip.s_addr, 4);
759     INC_FSM_OPT(TY_IPADDR, 6, o);
760   }
761
762   if (ipcp->my_compproto && !REJECTED(ipcp, TY_COMPPROTO)) {
763     if (ipcp->heis1172) {
764       u_int16_t proto = PROTO_VJCOMP;
765
766       ua_htons(&proto, o->data);
767       INC_FSM_OPT(TY_COMPPROTO, 4, o);
768     } else {
769       struct compreq req;
770
771       req.proto = htons(ipcp->my_compproto >> 16);
772       req.slots = (ipcp->my_compproto >> 8) & 255;
773       req.compcid = ipcp->my_compproto & 1;
774       memcpy(o->data, &req, 4);
775       INC_FSM_OPT(TY_COMPPROTO, 6, o);
776     }
777   }
778
779   if (IsEnabled(ipcp->cfg.ns.dns_neg)) {
780     if (!REJECTED(ipcp, TY_PRIMARY_DNS - TY_ADJUST_NS)) {
781       memcpy(o->data, &ipcp->ns.dns[0].s_addr, 4);
782       INC_FSM_OPT(TY_PRIMARY_DNS, 6, o);
783     }
784
785     if (!REJECTED(ipcp, TY_SECONDARY_DNS - TY_ADJUST_NS)) {
786       memcpy(o->data, &ipcp->ns.dns[1].s_addr, 4);
787       INC_FSM_OPT(TY_SECONDARY_DNS, 6, o);
788     }
789   }
790
791   fsm_Output(fp, CODE_CONFIGREQ, fp->reqid, buff, (u_char *)o - buff,
792              MB_IPCPOUT);
793 }
794
795 static void
796 IpcpSentTerminateReq(struct fsm *fp __unused)
797 {
798   /* Term REQ just sent by FSM */
799 }
800
801 static void
802 IpcpSendTerminateAck(struct fsm *fp, u_char id)
803 {
804   /* Send Term ACK please */
805   fsm_Output(fp, CODE_TERMACK, id, NULL, 0, MB_IPCPOUT);
806 }
807
808 static void
809 IpcpLayerStart(struct fsm *fp)
810 {
811   /* We're about to start up ! */
812   struct ipcp *ipcp = fsm2ipcp(fp);
813
814   log_Printf(LogIPCP, "%s: LayerStart.\n", fp->link->name);
815   throughput_start(&ipcp->throughput, "IPCP throughput",
816                    Enabled(fp->bundle, OPT_THROUGHPUT));
817   fp->more.reqs = fp->more.naks = fp->more.rejs = ipcp->cfg.fsm.maxreq * 3;
818   ipcp->peer_req = 0;
819 }
820
821 static void
822 IpcpLayerFinish(struct fsm *fp)
823 {
824   /* We're now down */
825   struct ipcp *ipcp = fsm2ipcp(fp);
826
827   log_Printf(LogIPCP, "%s: LayerFinish.\n", fp->link->name);
828   throughput_stop(&ipcp->throughput);
829   throughput_log(&ipcp->throughput, LogIPCP, NULL);
830 }
831
832 /*
833  * Called from iface_Add() via ncp_IfaceAddrAdded()
834  */
835 void
836 ipcp_IfaceAddrAdded(struct ipcp *ipcp, const struct iface_addr *addr)
837 {
838   struct bundle *bundle = ipcp->fsm.bundle;
839
840   if (Enabled(bundle, OPT_PROXY) || Enabled(bundle, OPT_PROXYALL))
841     ipcp_proxyarp(ipcp, arp_SetProxy, addr);
842 }
843
844 /*
845  * Called from iface_Clear() and iface_Delete() via ncp_IfaceAddrDeleted()
846  */
847 void
848 ipcp_IfaceAddrDeleted(struct ipcp *ipcp, const struct iface_addr *addr)
849 {
850   struct bundle *bundle = ipcp->fsm.bundle;
851
852   if (Enabled(bundle, OPT_PROXY) || Enabled(bundle, OPT_PROXYALL))
853     ipcp_proxyarp(ipcp, arp_ClearProxy, addr);
854 }
855
856 static void
857 IpcpLayerDown(struct fsm *fp)
858 {
859   /* About to come down */
860   struct ipcp *ipcp = fsm2ipcp(fp);
861   static int recursing;
862   char addr[16];
863
864   if (!recursing++) {
865     snprintf(addr, sizeof addr, "%s", inet_ntoa(ipcp->my_ip));
866     log_Printf(LogIPCP, "%s: LayerDown: %s\n", fp->link->name, addr);
867
868 #ifndef NORADIUS
869     radius_Account(&fp->bundle->radius, &fp->bundle->radacct,
870                    fp->bundle->links, RAD_STOP, &ipcp->peer_ip, &ipcp->ifmask,
871                    &ipcp->throughput);
872
873   if (fp->bundle->radius.cfg.file && fp->bundle->radius.filterid)
874     system_Select(fp->bundle, fp->bundle->radius.filterid, LINKDOWNFILE,
875                   NULL, NULL);
876 #endif
877
878     /*
879      * XXX this stuff should really live in the FSM.  Our config should
880      * associate executable sections in files with events.
881      */
882     if (system_Select(fp->bundle, addr, LINKDOWNFILE, NULL, NULL) < 0) {
883       if (bundle_GetLabel(fp->bundle)) {
884          if (system_Select(fp->bundle, bundle_GetLabel(fp->bundle),
885                           LINKDOWNFILE, NULL, NULL) < 0)
886          system_Select(fp->bundle, "MYADDR", LINKDOWNFILE, NULL, NULL);
887       } else
888         system_Select(fp->bundle, "MYADDR", LINKDOWNFILE, NULL, NULL);
889     }
890
891     ipcp_Setup(ipcp, INADDR_NONE);
892   }
893   recursing--;
894 }
895
896 int
897 ipcp_InterfaceUp(struct ipcp *ipcp)
898 {
899   if (!ipcp_SetIPaddress(ipcp, ipcp->my_ip, ipcp->peer_ip)) {
900     log_Printf(LogERROR, "ipcp_InterfaceUp: unable to set ip address\n");
901     return 0;
902   }
903
904   if (!iface_SetFlags(ipcp->fsm.bundle->iface->name, IFF_UP)) {
905     log_Printf(LogERROR, "ipcp_InterfaceUp: Can't set the IFF_UP flag on %s\n",
906                ipcp->fsm.bundle->iface->name);
907     return 0;
908   }
909
910 #ifndef NONAT
911   if (ipcp->fsm.bundle->NatEnabled)
912     PacketAliasSetAddress(ipcp->my_ip);
913 #endif
914
915   return 1;
916 }
917
918 static int
919 IpcpLayerUp(struct fsm *fp)
920 {
921   /* We're now up */
922   struct ipcp *ipcp = fsm2ipcp(fp);
923   char tbuff[16];
924
925   log_Printf(LogIPCP, "%s: LayerUp.\n", fp->link->name);
926   snprintf(tbuff, sizeof tbuff, "%s", inet_ntoa(ipcp->my_ip));
927   log_Printf(LogIPCP, "myaddr %s hisaddr = %s\n",
928              tbuff, inet_ntoa(ipcp->peer_ip));
929
930   if (ipcp->peer_compproto >> 16 == PROTO_VJCOMP)
931     sl_compress_init(&ipcp->vj.cslc, (ipcp->peer_compproto >> 8) & 255);
932
933   if (!ipcp_InterfaceUp(ipcp))
934     return 0;
935
936 #ifndef NORADIUS
937   radius_Account(&fp->bundle->radius, &fp->bundle->radacct, fp->bundle->links,
938                  RAD_START, &ipcp->peer_ip, &ipcp->ifmask, &ipcp->throughput);
939
940   if (fp->bundle->radius.cfg.file && fp->bundle->radius.filterid)
941     system_Select(fp->bundle, fp->bundle->radius.filterid, LINKUPFILE,
942                   NULL, NULL);
943 #endif
944
945   /*
946    * XXX this stuff should really live in the FSM.  Our config should
947    * associate executable sections in files with events.
948    */
949   if (system_Select(fp->bundle, tbuff, LINKUPFILE, NULL, NULL) < 0) {
950     if (bundle_GetLabel(fp->bundle)) {
951       if (system_Select(fp->bundle, bundle_GetLabel(fp->bundle),
952                        LINKUPFILE, NULL, NULL) < 0)
953         system_Select(fp->bundle, "MYADDR", LINKUPFILE, NULL, NULL);
954     } else
955       system_Select(fp->bundle, "MYADDR", LINKUPFILE, NULL, NULL);
956   }
957
958   fp->more.reqs = fp->more.naks = fp->more.rejs = ipcp->cfg.fsm.maxreq * 3;
959   log_DisplayPrompts();
960
961   return 1;
962 }
963
964 static void
965 ipcp_ValidateReq(struct ipcp *ipcp, struct in_addr ip, struct fsm_decode *dec)
966 {
967   struct bundle *bundle = ipcp->fsm.bundle;
968   struct iface *iface = bundle->iface;
969   struct in_addr myaddr, peer;
970   unsigned n;
971
972   if (iplist_isvalid(&ipcp->cfg.peer_list)) {
973     ncprange_getip4addr(&ipcp->cfg.my_range, &myaddr);
974     if (ip.s_addr == INADDR_ANY ||
975         iplist_ip2pos(&ipcp->cfg.peer_list, ip) < 0 ||
976         !ipcp_SetIPaddress(ipcp, myaddr, ip)) {
977       log_Printf(LogIPCP, "%s: Address invalid or already in use\n",
978                  inet_ntoa(ip));
979       /*
980        * If we've already had a valid address configured for the peer,
981        * try NAKing with that so that we don't have to upset things
982        * too much.
983        */
984       for (n = 0; n < iface->addrs; n++) {
985         if (!ncpaddr_getip4(&iface->addr[n].peer, &peer))
986           continue;
987         if (iplist_ip2pos(&ipcp->cfg.peer_list, peer) >= 0) {
988           ipcp->peer_ip = peer;
989           break;
990         }
991       }
992
993       if (n == iface->addrs) {
994         /* Just pick an IP number from our list */
995         ipcp->peer_ip = ChooseHisAddr(bundle, myaddr);
996       }
997
998       if (ipcp->peer_ip.s_addr == INADDR_ANY) {
999         *dec->rejend++ = TY_IPADDR;
1000         *dec->rejend++ = 6;
1001         memcpy(dec->rejend, &ip.s_addr, 4);
1002         dec->rejend += 4;
1003       } else {
1004         *dec->nakend++ = TY_IPADDR;
1005         *dec->nakend++ = 6;
1006         memcpy(dec->nakend, &ipcp->peer_ip.s_addr, 4);
1007         dec->nakend += 4;
1008       }
1009       return;
1010     }
1011   } else if (ip.s_addr == INADDR_ANY ||
1012              !ncprange_containsip4(&ipcp->cfg.peer_range, ip)) {
1013     /*
1014      * If the destination address is not acceptable, NAK with what we
1015      * want to use.
1016      */
1017     *dec->nakend++ = TY_IPADDR;
1018     *dec->nakend++ = 6;
1019     for (n = 0; n < iface->addrs; n++)
1020       if (ncprange_contains(&ipcp->cfg.peer_range, &iface->addr[n].peer)) {
1021         /* We prefer the already-configured address */
1022         ncpaddr_getip4addr(&iface->addr[n].peer, (u_int32_t *)dec->nakend);
1023         break;
1024       }
1025
1026     if (n == iface->addrs)
1027       memcpy(dec->nakend, &ipcp->peer_ip.s_addr, 4);
1028
1029     dec->nakend += 4;
1030     return;
1031   }
1032
1033   ipcp->peer_ip = ip;
1034   *dec->ackend++ = TY_IPADDR;
1035   *dec->ackend++ = 6;
1036   memcpy(dec->ackend, &ip.s_addr, 4);
1037   dec->ackend += 4;
1038 }
1039
1040 static void
1041 IpcpDecodeConfig(struct fsm *fp, u_char *cp, u_char *end, int mode_type,
1042                  struct fsm_decode *dec)
1043 {
1044   /* Deal with incoming PROTO_IPCP */
1045   struct ncpaddr ncpaddr;
1046   struct ipcp *ipcp = fsm2ipcp(fp);
1047   int gotdnsnak;
1048   u_int32_t compproto;
1049   struct compreq *pcomp;
1050   struct in_addr ipaddr, dstipaddr, have_ip;
1051   char tbuff[100], tbuff2[100];
1052   struct fsm_opt *opt, nak;
1053
1054   gotdnsnak = 0;
1055
1056   while (end - cp >= (int)sizeof(opt->hdr)) {
1057     if ((opt = fsm_readopt(&cp)) == NULL)
1058       break;
1059
1060     snprintf(tbuff, sizeof tbuff, " %s[%d]", protoname(opt->hdr.id),
1061              opt->hdr.len);
1062
1063     switch (opt->hdr.id) {
1064     case TY_IPADDR:             /* RFC1332 */
1065       memcpy(&ipaddr.s_addr, opt->data, 4);
1066       log_Printf(LogIPCP, "%s %s\n", tbuff, inet_ntoa(ipaddr));
1067
1068       switch (mode_type) {
1069       case MODE_REQ:
1070         ipcp->peer_req = 1;
1071         ipcp_ValidateReq(ipcp, ipaddr, dec);
1072         break;
1073
1074       case MODE_NAK:
1075         if (ncprange_containsip4(&ipcp->cfg.my_range, ipaddr)) {
1076           /* Use address suggested by peer */
1077           snprintf(tbuff2, sizeof tbuff2, "%s changing address: %s ", tbuff,
1078                    inet_ntoa(ipcp->my_ip));
1079           log_Printf(LogIPCP, "%s --> %s\n", tbuff2, inet_ntoa(ipaddr));
1080           ipcp->my_ip = ipaddr;
1081           ncpaddr_setip4(&ncpaddr, ipcp->my_ip);
1082           bundle_AdjustFilters(fp->bundle, &ncpaddr, NULL);
1083         } else {
1084           log_Printf(log_IsKept(LogIPCP) ? LogIPCP : LogPHASE,
1085                     "%s: Unacceptable address!\n", inet_ntoa(ipaddr));
1086           fsm_Close(&ipcp->fsm);
1087         }
1088         break;
1089
1090       case MODE_REJ:
1091         ipcp->peer_reject |= (1 << opt->hdr.id);
1092         break;
1093       }
1094       break;
1095
1096     case TY_COMPPROTO:
1097       pcomp = (struct compreq *)opt->data;
1098       compproto = (ntohs(pcomp->proto) << 16) + ((int)pcomp->slots << 8) +
1099                   pcomp->compcid;
1100       log_Printf(LogIPCP, "%s %s\n", tbuff, vj2asc(compproto));
1101
1102       switch (mode_type) {
1103       case MODE_REQ:
1104         if (!IsAccepted(ipcp->cfg.vj.neg))
1105           fsm_rej(dec, opt);
1106         else {
1107           switch (opt->hdr.len) {
1108           case 4:               /* RFC1172 */
1109             if (ntohs(pcomp->proto) == PROTO_VJCOMP) {
1110               log_Printf(LogWARN, "Peer is speaking RFC1172 compression "
1111                          "protocol !\n");
1112               ipcp->heis1172 = 1;
1113               ipcp->peer_compproto = compproto;
1114               fsm_ack(dec, opt);
1115             } else {
1116               pcomp->proto = htons(PROTO_VJCOMP);
1117               nak.hdr.id = TY_COMPPROTO;
1118               nak.hdr.len = 4;
1119               memcpy(nak.data, &pcomp, 2);
1120               fsm_nak(dec, &nak);
1121             }
1122             break;
1123           case 6:               /* RFC1332 */
1124             if (ntohs(pcomp->proto) == PROTO_VJCOMP) {
1125               /* We know pcomp->slots' max value == MAX_VJ_STATES */
1126               if (pcomp->slots >= MIN_VJ_STATES) {
1127                 /* Ok, we can do that */
1128                 ipcp->peer_compproto = compproto;
1129                 ipcp->heis1172 = 0;
1130                 fsm_ack(dec, opt);
1131               } else {
1132                 /* Get as close as we can to what he wants */
1133                 ipcp->heis1172 = 0;
1134                 pcomp->slots = MIN_VJ_STATES;
1135                 nak.hdr.id = TY_COMPPROTO;
1136                 nak.hdr.len = 4;
1137                 memcpy(nak.data, &pcomp, 2);
1138                 fsm_nak(dec, &nak);
1139               }
1140             } else {
1141               /* What we really want */
1142               pcomp->proto = htons(PROTO_VJCOMP);
1143               pcomp->slots = DEF_VJ_STATES;
1144               pcomp->compcid = 1;
1145               nak.hdr.id = TY_COMPPROTO;
1146               nak.hdr.len = 6;
1147               memcpy(nak.data, &pcomp, sizeof pcomp);
1148               fsm_nak(dec, &nak);
1149             }
1150             break;
1151           default:
1152             fsm_rej(dec, opt);
1153             break;
1154           }
1155         }
1156         break;
1157
1158       case MODE_NAK:
1159         if (ntohs(pcomp->proto) == PROTO_VJCOMP) {
1160           /* We know pcomp->slots' max value == MAX_VJ_STATES */
1161           if (pcomp->slots < MIN_VJ_STATES)
1162             pcomp->slots = MIN_VJ_STATES;
1163           compproto = (ntohs(pcomp->proto) << 16) + (pcomp->slots << 8) +
1164                       pcomp->compcid;
1165         } else
1166           compproto = 0;
1167         log_Printf(LogIPCP, "%s changing compproto: %08x --> %08x\n",
1168                    tbuff, ipcp->my_compproto, compproto);
1169         ipcp->my_compproto = compproto;
1170         break;
1171
1172       case MODE_REJ:
1173         ipcp->peer_reject |= (1 << opt->hdr.id);
1174         break;
1175       }
1176       break;
1177
1178     case TY_IPADDRS:            /* RFC1172 */
1179       memcpy(&ipaddr.s_addr, opt->data, 4);
1180       memcpy(&dstipaddr.s_addr, opt->data + 4, 4);
1181       snprintf(tbuff2, sizeof tbuff2, "%s %s,", tbuff, inet_ntoa(ipaddr));
1182       log_Printf(LogIPCP, "%s %s\n", tbuff2, inet_ntoa(dstipaddr));
1183
1184       switch (mode_type) {
1185       case MODE_REQ:
1186         fsm_rej(dec, opt);
1187         break;
1188
1189       case MODE_NAK:
1190       case MODE_REJ:
1191         break;
1192       }
1193       break;
1194
1195     case TY_PRIMARY_DNS:        /* DNS negotiation (rfc1877) */
1196     case TY_SECONDARY_DNS:
1197       memcpy(&ipaddr.s_addr, opt->data, 4);
1198       log_Printf(LogIPCP, "%s %s\n", tbuff, inet_ntoa(ipaddr));
1199
1200       switch (mode_type) {
1201       case MODE_REQ:
1202         if (!IsAccepted(ipcp->cfg.ns.dns_neg)) {
1203           ipcp->my_reject |= (1 << (opt->hdr.id - TY_ADJUST_NS));
1204           fsm_rej(dec, opt);
1205           break;
1206         }
1207         have_ip = ipcp->ns.dns[opt->hdr.id == TY_PRIMARY_DNS ? 0 : 1];
1208
1209         if (opt->hdr.id == TY_PRIMARY_DNS && ipaddr.s_addr != have_ip.s_addr &&
1210             ipaddr.s_addr == ipcp->ns.dns[1].s_addr) {
1211           /* Swap 'em 'round */
1212           ipcp->ns.dns[0] = ipcp->ns.dns[1];
1213           ipcp->ns.dns[1] = have_ip;
1214           have_ip = ipcp->ns.dns[0];
1215         }
1216
1217         if (ipaddr.s_addr != have_ip.s_addr) {
1218           /*
1219            * The client has got the DNS stuff wrong (first request) so
1220            * we'll tell 'em how it is
1221            */
1222           nak.hdr.id = opt->hdr.id;
1223           nak.hdr.len = 6;
1224           memcpy(nak.data, &have_ip.s_addr, 4);
1225           fsm_nak(dec, &nak);
1226         } else {
1227           /*
1228            * Otherwise they have it right (this time) so we send a ack packet
1229            * back confirming it... end of story
1230            */
1231           fsm_ack(dec, opt);
1232         }
1233         break;
1234
1235       case MODE_NAK:
1236         if (IsEnabled(ipcp->cfg.ns.dns_neg)) {
1237           gotdnsnak = 1;
1238           memcpy(&ipcp->ns.dns[opt->hdr.id == TY_PRIMARY_DNS ? 0 : 1].s_addr,
1239                  opt->data, 4);
1240         }
1241         break;
1242
1243       case MODE_REJ:            /* Can't do much, stop asking */
1244         ipcp->peer_reject |= (1 << (opt->hdr.id - TY_ADJUST_NS));
1245         break;
1246       }
1247       break;
1248
1249     case TY_PRIMARY_NBNS:       /* M$ NetBIOS nameserver hack (rfc1877) */
1250     case TY_SECONDARY_NBNS:
1251       memcpy(&ipaddr.s_addr, opt->data, 4);
1252       log_Printf(LogIPCP, "%s %s\n", tbuff, inet_ntoa(ipaddr));
1253
1254       switch (mode_type) {
1255       case MODE_REQ:
1256         have_ip.s_addr =
1257           ipcp->cfg.ns.nbns[opt->hdr.id == TY_PRIMARY_NBNS ? 0 : 1].s_addr;
1258
1259         if (have_ip.s_addr == INADDR_ANY) {
1260           log_Printf(LogIPCP, "NBNS REQ - rejected - nbns not set\n");
1261           ipcp->my_reject |= (1 << (opt->hdr.id - TY_ADJUST_NS));
1262           fsm_rej(dec, opt);
1263           break;
1264         }
1265
1266         if (ipaddr.s_addr != have_ip.s_addr) {
1267           nak.hdr.id = opt->hdr.id;
1268           nak.hdr.len = 6;
1269           memcpy(nak.data, &have_ip.s_addr, 4);
1270           fsm_nak(dec, &nak);
1271         } else
1272           fsm_ack(dec, opt);
1273         break;
1274
1275       case MODE_NAK:
1276         log_Printf(LogIPCP, "MS NBNS req %d - NAK??\n", opt->hdr.id);
1277         break;
1278
1279       case MODE_REJ:
1280         log_Printf(LogIPCP, "MS NBNS req %d - REJ??\n", opt->hdr.id);
1281         break;
1282       }
1283       break;
1284
1285     default:
1286       if (mode_type != MODE_NOP) {
1287         ipcp->my_reject |= (1 << opt->hdr.id);
1288         fsm_rej(dec, opt);
1289       }
1290       break;
1291     }
1292   }
1293
1294   if (gotdnsnak) {
1295     if (ipcp->ns.writable) {
1296       log_Printf(LogDEBUG, "Updating resolver\n");
1297       if (!ipcp_WriteDNS(ipcp)) {
1298         ipcp->peer_reject |= (1 << (TY_PRIMARY_DNS - TY_ADJUST_NS));
1299         ipcp->peer_reject |= (1 << (TY_SECONDARY_DNS - TY_ADJUST_NS));
1300       } else
1301         bundle_AdjustDNS(fp->bundle);
1302     } else {
1303       log_Printf(LogDEBUG, "Not updating resolver (readonly)\n");
1304       bundle_AdjustDNS(fp->bundle);
1305     }
1306   }
1307
1308   if (mode_type != MODE_NOP) {
1309     if (mode_type == MODE_REQ && !ipcp->peer_req) {
1310       if (dec->rejend == dec->rej && dec->nakend == dec->nak) {
1311         /*
1312          * Pretend the peer has requested an IP.
1313          * We do this to ensure that we only send one NAK if the only
1314          * reason for the NAK is because the peer isn't sending a
1315          * TY_IPADDR REQ.  This stops us from repeatedly trying to tell
1316          * the peer that we have to have an IP address on their end.
1317          */
1318         ipcp->peer_req = 1;
1319       }
1320       ipaddr.s_addr = INADDR_ANY;
1321       ipcp_ValidateReq(ipcp, ipaddr, dec);
1322     }
1323     fsm_opt_normalise(dec);
1324   }
1325 }
1326
1327 extern struct mbuf *
1328 ipcp_Input(struct bundle *bundle, struct link *l, struct mbuf *bp)
1329 {
1330   /* Got PROTO_IPCP from link */
1331   m_settype(bp, MB_IPCPIN);
1332   if (bundle_Phase(bundle) == PHASE_NETWORK)
1333     fsm_Input(&bundle->ncp.ipcp.fsm, bp);
1334   else {
1335     if (bundle_Phase(bundle) < PHASE_NETWORK)
1336       log_Printf(LogIPCP, "%s: Error: Unexpected IPCP in phase %s (ignored)\n",
1337                  l->name, bundle_PhaseName(bundle));
1338     m_freem(bp);
1339   }
1340   return NULL;
1341 }
1342
1343 int
1344 ipcp_UseHisIPaddr(struct bundle *bundle, struct in_addr hisaddr)
1345 {
1346   struct ipcp *ipcp = &bundle->ncp.ipcp;
1347   struct in_addr myaddr;
1348
1349   memset(&ipcp->cfg.peer_range, '\0', sizeof ipcp->cfg.peer_range);
1350   iplist_reset(&ipcp->cfg.peer_list);
1351   ipcp->peer_ip = hisaddr;
1352   ncprange_setip4host(&ipcp->cfg.peer_range, hisaddr);
1353   ncprange_getip4addr(&ipcp->cfg.my_range, &myaddr);
1354
1355   return ipcp_SetIPaddress(ipcp, myaddr, hisaddr);
1356 }
1357
1358 int
1359 ipcp_UseHisaddr(struct bundle *bundle, const char *hisaddr, int setaddr)
1360 {
1361   struct in_addr myaddr;
1362   struct ncp *ncp = &bundle->ncp;
1363   struct ipcp *ipcp = &ncp->ipcp;
1364   struct ncpaddr ncpaddr;
1365
1366   /* Use `hisaddr' for the peers address (set iface if `setaddr') */
1367   memset(&ipcp->cfg.peer_range, '\0', sizeof ipcp->cfg.peer_range);
1368   iplist_reset(&ipcp->cfg.peer_list);
1369   if (strpbrk(hisaddr, ",-")) {
1370     iplist_setsrc(&ipcp->cfg.peer_list, hisaddr);
1371     if (iplist_isvalid(&ipcp->cfg.peer_list)) {
1372       iplist_setrandpos(&ipcp->cfg.peer_list);
1373       ipcp->peer_ip = ChooseHisAddr(bundle, ipcp->my_ip);
1374       if (ipcp->peer_ip.s_addr == INADDR_ANY) {
1375         log_Printf(LogWARN, "%s: None available !\n", ipcp->cfg.peer_list.src);
1376         return 0;
1377       }
1378       ncprange_setip4host(&ipcp->cfg.peer_range, ipcp->peer_ip);
1379     } else {
1380       log_Printf(LogWARN, "%s: Invalid range !\n", hisaddr);
1381       return 0;
1382     }
1383   } else if (ncprange_aton(&ipcp->cfg.peer_range, ncp, hisaddr) != 0) {
1384     if (ncprange_family(&ipcp->cfg.my_range) != AF_INET) {
1385       log_Printf(LogWARN, "%s: Not an AF_INET address !\n", hisaddr);
1386       return 0;
1387     }
1388     ncprange_getip4addr(&ipcp->cfg.my_range, &myaddr);
1389     ncprange_getip4addr(&ipcp->cfg.peer_range, &ipcp->peer_ip);
1390
1391     if (setaddr && !ipcp_SetIPaddress(ipcp, myaddr, ipcp->peer_ip))
1392       return 0;
1393   } else
1394     return 0;
1395
1396   ncpaddr_setip4(&ncpaddr, ipcp->peer_ip);
1397   bundle_AdjustFilters(bundle, NULL, &ncpaddr);
1398
1399   return 1;     /* Ok */
1400 }
1401
1402 struct in_addr
1403 addr2mask(struct in_addr addr)
1404 {
1405   u_int32_t haddr = ntohl(addr.s_addr);
1406
1407   haddr = IN_CLASSA(haddr) ? IN_CLASSA_NET :
1408           IN_CLASSB(haddr) ? IN_CLASSB_NET :
1409           IN_CLASSC_NET;
1410   addr.s_addr = htonl(haddr);
1411
1412   return addr;
1413 }
1414
1415 size_t
1416 ipcp_QueueLen(struct ipcp *ipcp)
1417 {
1418   struct mqueue *q;
1419   size_t result;
1420
1421   result = 0;
1422   for (q = ipcp->Queue; q < ipcp->Queue + IPCP_QUEUES(ipcp); q++)
1423     result += q->len;
1424
1425   return result;
1426 }
1427
1428 int
1429 ipcp_PushPacket(struct ipcp *ipcp, struct link *l)
1430 {
1431   struct bundle *bundle = ipcp->fsm.bundle;
1432   struct mqueue *queue;
1433   struct mbuf *bp;
1434   int m_len;
1435   u_int32_t secs = 0;
1436   unsigned alivesecs = 0;
1437
1438   if (ipcp->fsm.state != ST_OPENED)
1439     return 0;
1440
1441   /*
1442    * If ccp is not open but is required, do nothing.
1443    */
1444   if (l->ccp.fsm.state != ST_OPENED && ccp_Required(&l->ccp)) {
1445     log_Printf(LogPHASE, "%s: Not transmitting... waiting for CCP\n", l->name);
1446     return 0;
1447   }
1448
1449   queue = ipcp->Queue + IPCP_QUEUES(ipcp) - 1;
1450   do {
1451     if (queue->top) {
1452       bp = m_dequeue(queue);
1453       bp = mbuf_Read(bp, &secs, sizeof secs);
1454       bp = m_pullup(bp);
1455       m_len = m_length(bp);
1456       if (!FilterCheck(MBUF_CTOP(bp), AF_INET, &bundle->filter.alive,
1457                        &alivesecs)) {
1458         if (secs == 0)
1459           secs = alivesecs;
1460         bundle_StartIdleTimer(bundle, secs);
1461       }
1462       link_PushPacket(l, bp, bundle, 0, PROTO_IP);
1463       ipcp_AddOutOctets(ipcp, m_len);
1464       return 1;
1465     }
1466   } while (queue-- != ipcp->Queue);
1467
1468   return 0;
1469 }