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