xref: /freebsd/usr.sbin/ppp/bundle.c (revision 1d66272a85cde1c8a69c58f4b5dd649babd6eca6)
1 /*-
2  * Copyright (c) 1998 Brian Somers <brian@Awfulhak.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  *
26  * $FreeBSD$
27  */
28 
29 #include <sys/param.h>
30 #include <sys/socket.h>
31 #include <netinet/in.h>
32 #include <net/if.h>
33 #include <net/if_tun.h>		/* For TUNS* ioctls */
34 #include <arpa/inet.h>
35 #include <net/route.h>
36 #include <netinet/in_systm.h>
37 #include <netinet/ip.h>
38 #include <sys/un.h>
39 
40 #include <errno.h>
41 #include <fcntl.h>
42 #ifdef __OpenBSD__
43 #include <util.h>
44 #else
45 #include <libutil.h>
46 #endif
47 #include <paths.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <sys/uio.h>
52 #include <sys/wait.h>
53 #if defined(__FreeBSD__) && !defined(NOKLDLOAD)
54 #ifdef NOSUID
55 #include <sys/linker.h>
56 #endif
57 #include <sys/module.h>
58 #endif
59 #include <termios.h>
60 #include <unistd.h>
61 
62 #include "layer.h"
63 #include "defs.h"
64 #include "command.h"
65 #include "mbuf.h"
66 #include "log.h"
67 #include "id.h"
68 #include "timer.h"
69 #include "fsm.h"
70 #include "iplist.h"
71 #include "lqr.h"
72 #include "hdlc.h"
73 #include "throughput.h"
74 #include "slcompress.h"
75 #include "ipcp.h"
76 #include "filter.h"
77 #include "descriptor.h"
78 #include "route.h"
79 #include "lcp.h"
80 #include "ccp.h"
81 #include "link.h"
82 #include "mp.h"
83 #ifndef NORADIUS
84 #include "radius.h"
85 #endif
86 #include "bundle.h"
87 #include "async.h"
88 #include "physical.h"
89 #include "auth.h"
90 #include "proto.h"
91 #include "chap.h"
92 #include "tun.h"
93 #include "prompt.h"
94 #include "chat.h"
95 #include "cbcp.h"
96 #include "datalink.h"
97 #include "ip.h"
98 #include "iface.h"
99 
100 #define SCATTER_SEGMENTS 7  /* version, datalink, name, physical,
101                                throughput, throughput, device       */
102 
103 #define SEND_MAXFD 3        /* Max file descriptors passed through
104                                the local domain socket              */
105 
106 static int bundle_RemainingIdleTime(struct bundle *);
107 
108 static const char * const PhaseNames[] = {
109   "Dead", "Establish", "Authenticate", "Network", "Terminate"
110 };
111 
112 const char *
113 bundle_PhaseName(struct bundle *bundle)
114 {
115   return bundle->phase <= PHASE_TERMINATE ?
116     PhaseNames[bundle->phase] : "unknown";
117 }
118 
119 void
120 bundle_NewPhase(struct bundle *bundle, u_int new)
121 {
122   if (new == bundle->phase)
123     return;
124 
125   if (new <= PHASE_TERMINATE)
126     log_Printf(LogPHASE, "bundle: %s\n", PhaseNames[new]);
127 
128   switch (new) {
129   case PHASE_DEAD:
130     log_DisplayPrompts();
131     bundle->phase = new;
132     break;
133 
134   case PHASE_ESTABLISH:
135     bundle->phase = new;
136     break;
137 
138   case PHASE_AUTHENTICATE:
139     bundle->phase = new;
140     log_DisplayPrompts();
141     break;
142 
143   case PHASE_NETWORK:
144     fsm_Up(&bundle->ncp.ipcp.fsm);
145     fsm_Open(&bundle->ncp.ipcp.fsm);
146     bundle->phase = new;
147     log_DisplayPrompts();
148     break;
149 
150   case PHASE_TERMINATE:
151     bundle->phase = new;
152     mp_Down(&bundle->ncp.mp);
153     log_DisplayPrompts();
154     break;
155   }
156 }
157 
158 static void
159 bundle_LayerStart(void *v, struct fsm *fp)
160 {
161   /* The given FSM is about to start up ! */
162 }
163 
164 
165 void
166 bundle_Notify(struct bundle *bundle, char c)
167 {
168   if (bundle->notify.fd != -1) {
169     int ret;
170 
171     ret = write(bundle->notify.fd, &c, 1);
172     if (c != EX_REDIAL && c != EX_RECONNECT) {
173       if (ret == 1)
174         log_Printf(LogCHAT, "Parent notified of %s\n",
175                    c == EX_NORMAL ? "success" : "failure");
176       else
177         log_Printf(LogERROR, "Failed to notify parent of success\n");
178       close(bundle->notify.fd);
179       bundle->notify.fd = -1;
180     } else if (ret == 1)
181       log_Printf(LogCHAT, "Parent notified of %s\n", ex_desc(c));
182     else
183       log_Printf(LogERROR, "Failed to notify parent of %s\n", ex_desc(c));
184   }
185 }
186 
187 static void
188 bundle_ClearQueues(void *v)
189 {
190   struct bundle *bundle = (struct bundle *)v;
191   struct datalink *dl;
192 
193   log_Printf(LogPHASE, "Clearing choked output queue\n");
194   timer_Stop(&bundle->choked.timer);
195 
196   /*
197    * Emergency time:
198    *
199    * We've had a full queue for PACKET_DEL_SECS seconds without being
200    * able to get rid of any of the packets.  We've probably given up
201    * on the redials at this point, and the queued data has almost
202    * definitely been timed out by the layer above.  As this is preventing
203    * us from reading the TUN_NAME device (we don't want to buffer stuff
204    * indefinitely), we may as well nuke this data and start with a clean
205    * slate !
206    *
207    * Unfortunately, this has the side effect of shafting any compression
208    * dictionaries in use (causing the relevant RESET_REQ/RESET_ACK).
209    */
210 
211   ip_DeleteQueue(&bundle->ncp.ipcp);
212   mp_DeleteQueue(&bundle->ncp.mp);
213   for (dl = bundle->links; dl; dl = dl->next)
214     physical_DeleteQueue(dl->physical);
215 }
216 
217 static void
218 bundle_LinkAdded(struct bundle *bundle, struct datalink *dl)
219 {
220   bundle->phys_type.all |= dl->physical->type;
221   if (dl->state == DATALINK_OPEN)
222     bundle->phys_type.open |= dl->physical->type;
223 
224   if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
225       != bundle->phys_type.open && bundle->idle.timer.state == TIMER_STOPPED)
226     /* We may need to start our idle timer */
227     bundle_StartIdleTimer(bundle, 0);
228 }
229 
230 void
231 bundle_LinksRemoved(struct bundle *bundle)
232 {
233   struct datalink *dl;
234 
235   bundle->phys_type.all = bundle->phys_type.open = 0;
236   for (dl = bundle->links; dl; dl = dl->next)
237     bundle_LinkAdded(bundle, dl);
238 
239   bundle_CalculateBandwidth(bundle);
240   mp_CheckAutoloadTimer(&bundle->ncp.mp);
241 
242   if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
243       == bundle->phys_type.open)
244     bundle_StopIdleTimer(bundle);
245 }
246 
247 static void
248 bundle_LayerUp(void *v, struct fsm *fp)
249 {
250   /*
251    * The given fsm is now up
252    * If it's an LCP, adjust our phys_mode.open value and check the
253    * autoload timer.
254    * If it's the first NCP, calculate our bandwidth
255    * If it's the first NCP, set our ``upat'' time
256    * If it's the first NCP, start the idle timer.
257    * If it's an NCP, tell our -background parent to go away.
258    * If it's the first NCP, start the autoload timer
259    */
260   struct bundle *bundle = (struct bundle *)v;
261 
262   if (fp->proto == PROTO_LCP) {
263     struct physical *p = link2physical(fp->link);
264 
265     bundle_LinkAdded(bundle, p->dl);
266     mp_CheckAutoloadTimer(&bundle->ncp.mp);
267   } else if (fp->proto == PROTO_IPCP) {
268     bundle_CalculateBandwidth(fp->bundle);
269     time(&bundle->upat);
270     bundle_StartIdleTimer(bundle, 0);
271     bundle_Notify(bundle, EX_NORMAL);
272     mp_CheckAutoloadTimer(&fp->bundle->ncp.mp);
273   }
274 }
275 
276 static void
277 bundle_LayerDown(void *v, struct fsm *fp)
278 {
279   /*
280    * The given FSM has been told to come down.
281    * If it's our last NCP, stop the idle timer.
282    * If it's our last NCP, clear our ``upat'' value.
283    * If it's our last NCP, stop the autoload timer
284    * If it's an LCP, adjust our phys_type.open value and any timers.
285    * If it's an LCP and we're in multilink mode, adjust our tun
286    * If it's the last LCP, down all NCPs
287    * speed and make sure our minimum sequence number is adjusted.
288    */
289 
290   struct bundle *bundle = (struct bundle *)v;
291 
292   if (fp->proto == PROTO_IPCP) {
293     bundle_StopIdleTimer(bundle);
294     bundle->upat = 0;
295     mp_StopAutoloadTimer(&bundle->ncp.mp);
296   } else if (fp->proto == PROTO_LCP) {
297     struct datalink *dl;
298     struct datalink *lost;
299     int others_active;
300 
301     bundle_LinksRemoved(bundle);  /* adjust timers & phys_type values */
302 
303     lost = NULL;
304     others_active = 0;
305     for (dl = bundle->links; dl; dl = dl->next) {
306       if (fp == &dl->physical->link.lcp.fsm)
307         lost = dl;
308       else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
309         others_active++;
310     }
311 
312     if (bundle->ncp.mp.active) {
313       bundle_CalculateBandwidth(bundle);
314 
315       if (lost)
316         mp_LinkLost(&bundle->ncp.mp, lost);
317       else
318         log_Printf(LogALERT, "Oops, lost an unrecognised datalink (%s) !\n",
319                    fp->link->name);
320     }
321 
322     if (!others_active)
323       /* Down the NCPs.  We don't expect to get fsm_Close()d ourself ! */
324       fsm2initial(&bundle->ncp.ipcp.fsm);
325   }
326 }
327 
328 static void
329 bundle_LayerFinish(void *v, struct fsm *fp)
330 {
331   /* The given fsm is now down (fp cannot be NULL)
332    *
333    * If it's the last NCP, fsm_Close all LCPs
334    */
335 
336   struct bundle *bundle = (struct bundle *)v;
337   struct datalink *dl;
338 
339   if (fp->proto == PROTO_IPCP) {
340     if (bundle_Phase(bundle) != PHASE_DEAD)
341       bundle_NewPhase(bundle, PHASE_TERMINATE);
342     for (dl = bundle->links; dl; dl = dl->next)
343       if (dl->state == DATALINK_OPEN)
344         datalink_Close(dl, CLOSE_STAYDOWN);
345     fsm2initial(fp);
346   }
347 }
348 
349 int
350 bundle_LinkIsUp(const struct bundle *bundle)
351 {
352   return bundle->ncp.ipcp.fsm.state == ST_OPENED;
353 }
354 
355 void
356 bundle_Close(struct bundle *bundle, const char *name, int how)
357 {
358   /*
359    * Please close the given datalink.
360    * If name == NULL or name is the last datalink, fsm_Close all NCPs
361    * (except our MP)
362    * If it isn't the last datalink, just Close that datalink.
363    */
364 
365   struct datalink *dl, *this_dl;
366   int others_active;
367 
368   others_active = 0;
369   this_dl = NULL;
370 
371   for (dl = bundle->links; dl; dl = dl->next) {
372     if (name && !strcasecmp(name, dl->name))
373       this_dl = dl;
374     if (name == NULL || this_dl == dl) {
375       switch (how) {
376         case CLOSE_LCP:
377           datalink_DontHangup(dl);
378           /* fall through */
379         case CLOSE_STAYDOWN:
380           datalink_StayDown(dl);
381           break;
382       }
383     } else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
384       others_active++;
385   }
386 
387   if (name && this_dl == NULL) {
388     log_Printf(LogWARN, "%s: Invalid datalink name\n", name);
389     return;
390   }
391 
392   if (!others_active) {
393     bundle_StopIdleTimer(bundle);
394     if (bundle->ncp.ipcp.fsm.state > ST_CLOSED ||
395         bundle->ncp.ipcp.fsm.state == ST_STARTING)
396       fsm_Close(&bundle->ncp.ipcp.fsm);
397     else {
398       fsm2initial(&bundle->ncp.ipcp.fsm);
399       for (dl = bundle->links; dl; dl = dl->next)
400         datalink_Close(dl, how);
401     }
402   } else if (this_dl && this_dl->state != DATALINK_CLOSED &&
403              this_dl->state != DATALINK_HANGUP)
404     datalink_Close(this_dl, how);
405 }
406 
407 void
408 bundle_Down(struct bundle *bundle, int how)
409 {
410   struct datalink *dl;
411 
412   for (dl = bundle->links; dl; dl = dl->next)
413     datalink_Down(dl, how);
414 }
415 
416 static size_t
417 bundle_FillQueues(struct bundle *bundle)
418 {
419   size_t total;
420 
421   if (bundle->ncp.mp.active)
422     total = mp_FillQueues(bundle);
423   else {
424     struct datalink *dl;
425     size_t add;
426 
427     for (total = 0, dl = bundle->links; dl; dl = dl->next)
428       if (dl->state == DATALINK_OPEN) {
429         add = link_QueueLen(&dl->physical->link);
430         if (add == 0 && dl->physical->out == NULL)
431           add = ip_PushPacket(&dl->physical->link, bundle);
432         total += add;
433       }
434   }
435 
436   return total + ip_QueueLen(&bundle->ncp.ipcp);
437 }
438 
439 static int
440 bundle_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
441 {
442   struct bundle *bundle = descriptor2bundle(d);
443   struct datalink *dl;
444   int result, nlinks;
445   u_short ifqueue;
446   size_t queued;
447 
448   result = 0;
449 
450   /* If there are aren't many packets queued, look for some more. */
451   for (nlinks = 0, dl = bundle->links; dl; dl = dl->next)
452     nlinks++;
453 
454   if (nlinks) {
455     queued = r ? bundle_FillQueues(bundle) : ip_QueueLen(&bundle->ncp.ipcp);
456 
457     if (r && (bundle->phase == PHASE_NETWORK ||
458               bundle->phys_type.all & PHYS_AUTO)) {
459       /* enough surplus so that we can tell if we're getting swamped */
460       ifqueue = nlinks > bundle->cfg.ifqueue ? nlinks : bundle->cfg.ifqueue;
461       if (queued < ifqueue) {
462         /* Not enough - select() for more */
463         if (bundle->choked.timer.state == TIMER_RUNNING)
464           timer_Stop(&bundle->choked.timer);	/* Not needed any more */
465         FD_SET(bundle->dev.fd, r);
466         if (*n < bundle->dev.fd + 1)
467           *n = bundle->dev.fd + 1;
468         log_Printf(LogTIMER, "%s: fdset(r) %d\n", TUN_NAME, bundle->dev.fd);
469         result++;
470       } else if (bundle->choked.timer.state == TIMER_STOPPED) {
471         bundle->choked.timer.func = bundle_ClearQueues;
472         bundle->choked.timer.name = "output choke";
473         bundle->choked.timer.load = bundle->cfg.choked.timeout * SECTICKS;
474         bundle->choked.timer.arg = bundle;
475         timer_Start(&bundle->choked.timer);
476       }
477     }
478   }
479 
480 #ifndef NORADIUS
481   result += descriptor_UpdateSet(&bundle->radius.desc, r, w, e, n);
482 #endif
483 
484   /* Which links need a select() ? */
485   for (dl = bundle->links; dl; dl = dl->next)
486     result += descriptor_UpdateSet(&dl->desc, r, w, e, n);
487 
488   /*
489    * This *MUST* be called after the datalink UpdateSet()s as it
490    * might be ``holding'' one of the datalinks (death-row) and
491    * wants to be able to de-select() it from the descriptor set.
492    */
493   result += descriptor_UpdateSet(&bundle->ncp.mp.server.desc, r, w, e, n);
494 
495   return result;
496 }
497 
498 static int
499 bundle_IsSet(struct fdescriptor *d, const fd_set *fdset)
500 {
501   struct bundle *bundle = descriptor2bundle(d);
502   struct datalink *dl;
503 
504   for (dl = bundle->links; dl; dl = dl->next)
505     if (descriptor_IsSet(&dl->desc, fdset))
506       return 1;
507 
508 #ifndef NORADIUS
509   if (descriptor_IsSet(&bundle->radius.desc, fdset))
510     return 1;
511 #endif
512 
513   if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
514     return 1;
515 
516   return FD_ISSET(bundle->dev.fd, fdset);
517 }
518 
519 static void
520 bundle_DescriptorRead(struct fdescriptor *d, struct bundle *bundle,
521                       const fd_set *fdset)
522 {
523   struct datalink *dl;
524   unsigned secs;
525 
526   if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
527     descriptor_Read(&bundle->ncp.mp.server.desc, bundle, fdset);
528 
529   for (dl = bundle->links; dl; dl = dl->next)
530     if (descriptor_IsSet(&dl->desc, fdset))
531       descriptor_Read(&dl->desc, bundle, fdset);
532 
533 #ifndef NORADIUS
534   if (descriptor_IsSet(&bundle->radius.desc, fdset))
535     descriptor_Read(&bundle->radius.desc, bundle, fdset);
536 #endif
537 
538   if (FD_ISSET(bundle->dev.fd, fdset)) {
539     struct tun_data tun;
540     int n, pri;
541     char *data;
542     size_t sz;
543 
544     if (bundle->dev.header) {
545       data = (char *)&tun;
546       sz = sizeof tun;
547     } else {
548       data = tun.data;
549       sz = sizeof tun.data;
550     }
551 
552     /* something to read from tun */
553 
554     n = read(bundle->dev.fd, data, sz);
555     if (n < 0) {
556       log_Printf(LogWARN, "%s: read: %s\n", bundle->dev.Name, strerror(errno));
557       return;
558     }
559 
560     if (bundle->dev.header) {
561       n -= sz - sizeof tun.data;
562       if (n <= 0) {
563         log_Printf(LogERROR, "%s: read: Got only %d bytes of data !\n",
564                    bundle->dev.Name, n);
565         return;
566       }
567       if (ntohl(tun.header.family) != AF_INET)
568         /* XXX: Should be maintaining drop/family counts ! */
569         return;
570     }
571 
572     if (((struct ip *)tun.data)->ip_dst.s_addr ==
573         bundle->ncp.ipcp.my_ip.s_addr) {
574       /* we've been asked to send something addressed *to* us :( */
575       if (Enabled(bundle, OPT_LOOPBACK)) {
576         pri = PacketCheck(bundle, tun.data, n, &bundle->filter.in, NULL, NULL);
577         if (pri >= 0) {
578           n += sz - sizeof tun.data;
579           write(bundle->dev.fd, data, n);
580           log_Printf(LogDEBUG, "Looped back packet addressed to myself\n");
581         }
582         return;
583       } else
584         log_Printf(LogDEBUG, "Oops - forwarding packet addressed to myself\n");
585     }
586 
587     /*
588      * Process on-demand dialup. Output packets are queued within tunnel
589      * device until IPCP is opened.
590      */
591 
592     if (bundle_Phase(bundle) == PHASE_DEAD) {
593       /*
594        * Note, we must be in AUTO mode :-/ otherwise our interface should
595        * *not* be UP and we can't receive data
596        */
597       pri = PacketCheck(bundle, tun.data, n, &bundle->filter.dial, NULL, NULL);
598       if (pri >= 0)
599         bundle_Open(bundle, NULL, PHYS_AUTO, 0);
600       else
601         /*
602          * Drop the packet.  If we were to queue it, we'd just end up with
603          * a pile of timed-out data in our output queue by the time we get
604          * around to actually dialing.  We'd also prematurely reach the
605          * threshold at which we stop select()ing to read() the tun
606          * device - breaking auto-dial.
607          */
608         return;
609     }
610 
611     secs = 0;
612     pri = PacketCheck(bundle, tun.data, n, &bundle->filter.out, NULL, &secs);
613     if (pri >= 0) {
614       /* Prepend the number of seconds timeout given in the filter */
615       tun.header.timeout = secs;
616       ip_Enqueue(&bundle->ncp.ipcp, pri, (char *)&tun, n + sizeof tun.header);
617     }
618   }
619 }
620 
621 static int
622 bundle_DescriptorWrite(struct fdescriptor *d, struct bundle *bundle,
623                        const fd_set *fdset)
624 {
625   struct datalink *dl;
626   int result = 0;
627 
628   /* This is not actually necessary as struct mpserver doesn't Write() */
629   if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
630     descriptor_Write(&bundle->ncp.mp.server.desc, bundle, fdset);
631 
632   for (dl = bundle->links; dl; dl = dl->next)
633     if (descriptor_IsSet(&dl->desc, fdset))
634       result += descriptor_Write(&dl->desc, bundle, fdset);
635 
636   return result;
637 }
638 
639 void
640 bundle_LockTun(struct bundle *bundle)
641 {
642   FILE *lockfile;
643   char pidfile[MAXPATHLEN];
644 
645   snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
646   lockfile = ID0fopen(pidfile, "w");
647   if (lockfile != NULL) {
648     fprintf(lockfile, "%d\n", (int)getpid());
649     fclose(lockfile);
650   }
651 #ifndef RELEASE_CRUNCH
652   else
653     log_Printf(LogERROR, "Warning: Can't create %s: %s\n",
654                pidfile, strerror(errno));
655 #endif
656 }
657 
658 static void
659 bundle_UnlockTun(struct bundle *bundle)
660 {
661   char pidfile[MAXPATHLEN];
662 
663   snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
664   ID0unlink(pidfile);
665 }
666 
667 struct bundle *
668 bundle_Create(const char *prefix, int type, int unit)
669 {
670   static struct bundle bundle;		/* there can be only one */
671   int enoentcount, err, minunit, maxunit;
672   const char *ifname;
673 #if defined(__FreeBSD__) && !defined(NOKLDLOAD)
674   int kldtried;
675 #endif
676 #if defined(TUNSIFMODE) || defined(TUNSLMODE) || defined(TUNSIFHEAD)
677   int iff;
678 #endif
679 
680   if (bundle.iface != NULL) {	/* Already allocated ! */
681     log_Printf(LogALERT, "bundle_Create:  There's only one BUNDLE !\n");
682     return NULL;
683   }
684 
685   if (unit == -1) {
686     minunit = 0;
687     maxunit = -1;
688   } else {
689     minunit = unit;
690     maxunit = unit + 1;
691   }
692   err = ENOENT;
693   enoentcount = 0;
694 #if defined(__FreeBSD__) && !defined(NOKLDLOAD)
695   kldtried = 0;
696 #endif
697   for (bundle.unit = minunit; bundle.unit != maxunit; bundle.unit++) {
698     snprintf(bundle.dev.Name, sizeof bundle.dev.Name, "%s%d",
699              prefix, bundle.unit);
700     bundle.dev.fd = ID0open(bundle.dev.Name, O_RDWR);
701     if (bundle.dev.fd >= 0)
702       break;
703     else if (errno == ENXIO) {
704 #if defined(__FreeBSD__) && !defined(NOKLDLOAD)
705       if (bundle.unit == minunit && !kldtried++) {
706         /*
707 	 * Attempt to load the tunnel interface KLD if it isn't loaded
708 	 * already.
709          */
710         if (modfind("if_tun") == -1) {
711           if (ID0kldload("if_tun") != -1) {
712             bundle.unit--;
713             continue;
714           }
715           log_Printf(LogWARN, "kldload: if_tun: %s\n", strerror(errno));
716         }
717       }
718 #endif
719       err = errno;
720       break;
721     } else if (errno == ENOENT) {
722       if (++enoentcount > 2)
723 	break;
724     } else
725       err = errno;
726   }
727 
728   if (bundle.dev.fd < 0) {
729     if (unit == -1)
730       log_Printf(LogWARN, "No available tunnel devices found (%s)\n",
731                 strerror(err));
732     else
733       log_Printf(LogWARN, "%s%d: %s\n", prefix, unit, strerror(err));
734     return NULL;
735   }
736 
737   log_SetTun(bundle.unit);
738 
739   ifname = strrchr(bundle.dev.Name, '/');
740   if (ifname == NULL)
741     ifname = bundle.dev.Name;
742   else
743     ifname++;
744 
745   bundle.iface = iface_Create(ifname);
746   if (bundle.iface == NULL) {
747     close(bundle.dev.fd);
748     return NULL;
749   }
750 
751 #ifdef TUNSIFMODE
752   /* Make sure we're POINTOPOINT */
753   iff = IFF_POINTOPOINT;
754   if (ID0ioctl(bundle.dev.fd, TUNSIFMODE, &iff) < 0)
755     log_Printf(LogERROR, "bundle_Create: ioctl(TUNSIFMODE): %s\n",
756 	       strerror(errno));
757 #endif
758 
759 #ifdef TUNSLMODE
760   /* Make sure we're not prepending sockaddrs */
761   iff = 0;
762   if (ID0ioctl(bundle.dev.fd, TUNSLMODE, &iff) < 0)
763     log_Printf(LogERROR, "bundle_Create: ioctl(TUNSLMODE): %s\n",
764 	       strerror(errno));
765 #endif
766 
767 #ifdef TUNSIFHEAD
768   /* We want the address family please ! */
769   iff = 1;
770   if (ID0ioctl(bundle.dev.fd, TUNSIFHEAD, &iff) < 0) {
771     log_Printf(LogERROR, "bundle_Create: ioctl(TUNSIFHEAD): %s\n",
772 	       strerror(errno));
773     bundle.dev.header = 0;
774   } else
775     bundle.dev.header = 1;
776 #else
777 #ifdef __OpenBSD__
778   /* Always present for OpenBSD */
779   bundle.dev.header = 1;
780 #else
781   /*
782    * If TUNSIFHEAD isn't available and we're not OpenBSD, assume
783    * everything's AF_INET (hopefully the tun device won't pass us
784    * anything else !).
785    */
786   bundle.dev.header = 0;
787 #endif
788 #endif
789 
790   if (!iface_SetFlags(bundle.iface, IFF_UP)) {
791     iface_Destroy(bundle.iface);
792     bundle.iface = NULL;
793     close(bundle.dev.fd);
794     return NULL;
795   }
796 
797   log_Printf(LogPHASE, "Using interface: %s\n", ifname);
798 
799   bundle.bandwidth = 0;
800   bundle.mtu = 1500;
801   bundle.routing_seq = 0;
802   bundle.phase = PHASE_DEAD;
803   bundle.CleaningUp = 0;
804   bundle.NatEnabled = 0;
805 
806   bundle.fsm.LayerStart = bundle_LayerStart;
807   bundle.fsm.LayerUp = bundle_LayerUp;
808   bundle.fsm.LayerDown = bundle_LayerDown;
809   bundle.fsm.LayerFinish = bundle_LayerFinish;
810   bundle.fsm.object = &bundle;
811 
812   bundle.cfg.idle.timeout = NCP_IDLE_TIMEOUT;
813   bundle.cfg.idle.min_timeout = 0;
814   *bundle.cfg.auth.name = '\0';
815   *bundle.cfg.auth.key = '\0';
816   bundle.cfg.opt = OPT_SROUTES | OPT_IDCHECK | OPT_LOOPBACK | OPT_TCPMSSFIXUP |
817                    OPT_THROUGHPUT | OPT_UTMP;
818   *bundle.cfg.label = '\0';
819   bundle.cfg.mtu = DEF_MTU;
820   bundle.cfg.ifqueue = DEF_IFQUEUE;
821   bundle.cfg.choked.timeout = CHOKED_TIMEOUT;
822   bundle.phys_type.all = type;
823   bundle.phys_type.open = 0;
824   bundle.upat = 0;
825 
826   bundle.links = datalink_Create("deflink", &bundle, type);
827   if (bundle.links == NULL) {
828     log_Printf(LogALERT, "Cannot create data link: %s\n", strerror(errno));
829     iface_Destroy(bundle.iface);
830     bundle.iface = NULL;
831     close(bundle.dev.fd);
832     return NULL;
833   }
834 
835   bundle.desc.type = BUNDLE_DESCRIPTOR;
836   bundle.desc.UpdateSet = bundle_UpdateSet;
837   bundle.desc.IsSet = bundle_IsSet;
838   bundle.desc.Read = bundle_DescriptorRead;
839   bundle.desc.Write = bundle_DescriptorWrite;
840 
841   mp_Init(&bundle.ncp.mp, &bundle);
842 
843   /* Send over the first physical link by default */
844   ipcp_Init(&bundle.ncp.ipcp, &bundle, &bundle.links->physical->link,
845             &bundle.fsm);
846 
847   memset(&bundle.filter, '\0', sizeof bundle.filter);
848   bundle.filter.in.fragok = bundle.filter.in.logok = 1;
849   bundle.filter.in.name = "IN";
850   bundle.filter.out.fragok = bundle.filter.out.logok = 1;
851   bundle.filter.out.name = "OUT";
852   bundle.filter.dial.name = "DIAL";
853   bundle.filter.dial.logok = 1;
854   bundle.filter.alive.name = "ALIVE";
855   bundle.filter.alive.logok = 1;
856   {
857     int	i;
858     for (i = 0; i < MAXFILTERS; i++) {
859         bundle.filter.in.rule[i].f_action = A_NONE;
860         bundle.filter.out.rule[i].f_action = A_NONE;
861         bundle.filter.dial.rule[i].f_action = A_NONE;
862         bundle.filter.alive.rule[i].f_action = A_NONE;
863     }
864   }
865   memset(&bundle.idle.timer, '\0', sizeof bundle.idle.timer);
866   bundle.idle.done = 0;
867   bundle.notify.fd = -1;
868   memset(&bundle.choked.timer, '\0', sizeof bundle.choked.timer);
869 #ifndef NORADIUS
870   radius_Init(&bundle.radius);
871 #endif
872 
873   /* Clean out any leftover crud */
874   iface_Clear(bundle.iface, IFACE_CLEAR_ALL);
875 
876   bundle_LockTun(&bundle);
877 
878   return &bundle;
879 }
880 
881 static void
882 bundle_DownInterface(struct bundle *bundle)
883 {
884   route_IfDelete(bundle, 1);
885   iface_ClearFlags(bundle->iface, IFF_UP);
886 }
887 
888 void
889 bundle_Destroy(struct bundle *bundle)
890 {
891   struct datalink *dl;
892 
893   /*
894    * Clean up the interface.  We don't need to timer_Stop()s, mp_Down(),
895    * ipcp_CleanInterface() and bundle_DownInterface() unless we're getting
896    * out under exceptional conditions such as a descriptor exception.
897    */
898   timer_Stop(&bundle->idle.timer);
899   timer_Stop(&bundle->choked.timer);
900   mp_Down(&bundle->ncp.mp);
901   ipcp_CleanInterface(&bundle->ncp.ipcp);
902   bundle_DownInterface(bundle);
903 
904 #ifndef NORADIUS
905   /* Tell the radius server the bad news */
906   log_Printf(LogDEBUG, "Radius: Destroy called from bundle_Destroy\n");
907   radius_Destroy(&bundle->radius);
908 #endif
909 
910   /* Again, these are all DATALINK_CLOSED unless we're abending */
911   dl = bundle->links;
912   while (dl)
913     dl = datalink_Destroy(dl);
914 
915   ipcp_Destroy(&bundle->ncp.ipcp);
916 
917   close(bundle->dev.fd);
918   bundle_UnlockTun(bundle);
919 
920   /* In case we never made PHASE_NETWORK */
921   bundle_Notify(bundle, EX_ERRDEAD);
922 
923   iface_Destroy(bundle->iface);
924   bundle->iface = NULL;
925 }
926 
927 struct rtmsg {
928   struct rt_msghdr m_rtm;
929   char m_space[64];
930 };
931 
932 int
933 bundle_SetRoute(struct bundle *bundle, int cmd, struct in_addr dst,
934                 struct in_addr gateway, struct in_addr mask, int bang, int ssh)
935 {
936   struct rtmsg rtmes;
937   int s, nb, wb;
938   char *cp;
939   const char *cmdstr;
940   struct sockaddr_in rtdata;
941   int result = 1;
942 
943   if (bang)
944     cmdstr = (cmd == RTM_ADD ? "Add!" : "Delete!");
945   else
946     cmdstr = (cmd == RTM_ADD ? "Add" : "Delete");
947   s = ID0socket(PF_ROUTE, SOCK_RAW, 0);
948   if (s < 0) {
949     log_Printf(LogERROR, "bundle_SetRoute: socket(): %s\n", strerror(errno));
950     return result;
951   }
952   memset(&rtmes, '\0', sizeof rtmes);
953   rtmes.m_rtm.rtm_version = RTM_VERSION;
954   rtmes.m_rtm.rtm_type = cmd;
955   rtmes.m_rtm.rtm_addrs = RTA_DST;
956   rtmes.m_rtm.rtm_seq = ++bundle->routing_seq;
957   rtmes.m_rtm.rtm_pid = getpid();
958   rtmes.m_rtm.rtm_flags = RTF_UP | RTF_GATEWAY | RTF_STATIC;
959 
960   if (cmd == RTM_ADD || cmd == RTM_CHANGE) {
961     if (bundle->ncp.ipcp.cfg.sendpipe > 0) {
962       rtmes.m_rtm.rtm_rmx.rmx_sendpipe = bundle->ncp.ipcp.cfg.sendpipe;
963       rtmes.m_rtm.rtm_inits |= RTV_SPIPE;
964     }
965     if (bundle->ncp.ipcp.cfg.recvpipe > 0) {
966       rtmes.m_rtm.rtm_rmx.rmx_recvpipe = bundle->ncp.ipcp.cfg.recvpipe;
967       rtmes.m_rtm.rtm_inits |= RTV_RPIPE;
968     }
969   }
970 
971   memset(&rtdata, '\0', sizeof rtdata);
972   rtdata.sin_len = sizeof rtdata;
973   rtdata.sin_family = AF_INET;
974   rtdata.sin_port = 0;
975   rtdata.sin_addr = dst;
976 
977   cp = rtmes.m_space;
978   memcpy(cp, &rtdata, rtdata.sin_len);
979   cp += rtdata.sin_len;
980   if (cmd == RTM_ADD) {
981     if (gateway.s_addr == INADDR_ANY) {
982       if (!ssh)
983         log_Printf(LogERROR, "bundle_SetRoute: Cannot add a route with"
984                    " destination 0.0.0.0\n");
985       close(s);
986       return result;
987     } else {
988       rtdata.sin_addr = gateway;
989       memcpy(cp, &rtdata, rtdata.sin_len);
990       cp += rtdata.sin_len;
991       rtmes.m_rtm.rtm_addrs |= RTA_GATEWAY;
992     }
993   }
994 
995   if (dst.s_addr == INADDR_ANY)
996     mask.s_addr = INADDR_ANY;
997 
998   if (cmd == RTM_ADD || dst.s_addr == INADDR_ANY) {
999     rtdata.sin_addr = mask;
1000     memcpy(cp, &rtdata, rtdata.sin_len);
1001     cp += rtdata.sin_len;
1002     rtmes.m_rtm.rtm_addrs |= RTA_NETMASK;
1003   }
1004 
1005   nb = cp - (char *) &rtmes;
1006   rtmes.m_rtm.rtm_msglen = nb;
1007   wb = ID0write(s, &rtmes, nb);
1008   if (wb < 0) {
1009     log_Printf(LogTCPIP, "bundle_SetRoute failure:\n");
1010     log_Printf(LogTCPIP, "bundle_SetRoute:  Cmd = %s\n", cmdstr);
1011     log_Printf(LogTCPIP, "bundle_SetRoute:  Dst = %s\n", inet_ntoa(dst));
1012     log_Printf(LogTCPIP, "bundle_SetRoute:  Gateway = %s\n",
1013                inet_ntoa(gateway));
1014     log_Printf(LogTCPIP, "bundle_SetRoute:  Mask = %s\n", inet_ntoa(mask));
1015 failed:
1016     if (cmd == RTM_ADD && (rtmes.m_rtm.rtm_errno == EEXIST ||
1017                            (rtmes.m_rtm.rtm_errno == 0 && errno == EEXIST))) {
1018       if (!bang) {
1019         log_Printf(LogWARN, "Add route failed: %s already exists\n",
1020 		  dst.s_addr == 0 ? "default" : inet_ntoa(dst));
1021         result = 0;	/* Don't add to our dynamic list */
1022       } else {
1023         rtmes.m_rtm.rtm_type = cmd = RTM_CHANGE;
1024         if ((wb = ID0write(s, &rtmes, nb)) < 0)
1025           goto failed;
1026       }
1027     } else if (cmd == RTM_DELETE &&
1028              (rtmes.m_rtm.rtm_errno == ESRCH ||
1029               (rtmes.m_rtm.rtm_errno == 0 && errno == ESRCH))) {
1030       if (!bang)
1031         log_Printf(LogWARN, "Del route failed: %s: Non-existent\n",
1032                   inet_ntoa(dst));
1033     } else if (rtmes.m_rtm.rtm_errno == 0) {
1034       if (!ssh || errno != ENETUNREACH)
1035         log_Printf(LogWARN, "%s route failed: %s: errno: %s\n", cmdstr,
1036                    inet_ntoa(dst), strerror(errno));
1037     } else
1038       log_Printf(LogWARN, "%s route failed: %s: %s\n",
1039 		 cmdstr, inet_ntoa(dst), strerror(rtmes.m_rtm.rtm_errno));
1040   }
1041   log_Printf(LogDEBUG, "wrote %d: cmd = %s, dst = %x, gateway = %x\n",
1042             wb, cmdstr, (unsigned)dst.s_addr, (unsigned)gateway.s_addr);
1043   close(s);
1044 
1045   return result;
1046 }
1047 
1048 void
1049 bundle_LinkClosed(struct bundle *bundle, struct datalink *dl)
1050 {
1051   /*
1052    * Our datalink has closed.
1053    * CleanDatalinks() (called from DoLoop()) will remove closed
1054    * BACKGROUND, FOREGROUND and DIRECT links.
1055    * If it's the last data link, enter phase DEAD.
1056    *
1057    * NOTE: dl may not be in our list (bundle_SendDatalink()) !
1058    */
1059 
1060   struct datalink *odl;
1061   int other_links;
1062 
1063   log_SetTtyCommandMode(dl);
1064 
1065   other_links = 0;
1066   for (odl = bundle->links; odl; odl = odl->next)
1067     if (odl != dl && odl->state != DATALINK_CLOSED)
1068       other_links++;
1069 
1070   if (!other_links) {
1071     if (dl->physical->type != PHYS_AUTO)	/* Not in -auto mode */
1072       bundle_DownInterface(bundle);
1073     fsm2initial(&bundle->ncp.ipcp.fsm);
1074     bundle_NewPhase(bundle, PHASE_DEAD);
1075     bundle_StopIdleTimer(bundle);
1076   }
1077 }
1078 
1079 void
1080 bundle_Open(struct bundle *bundle, const char *name, int mask, int force)
1081 {
1082   /*
1083    * Please open the given datalink, or all if name == NULL
1084    */
1085   struct datalink *dl;
1086 
1087   for (dl = bundle->links; dl; dl = dl->next)
1088     if (name == NULL || !strcasecmp(dl->name, name)) {
1089       if ((mask & dl->physical->type) &&
1090           (dl->state == DATALINK_CLOSED ||
1091            (force && dl->state == DATALINK_OPENING &&
1092             dl->dial.timer.state == TIMER_RUNNING) ||
1093            dl->state == DATALINK_READY)) {
1094         timer_Stop(&dl->dial.timer);	/* We're finished with this */
1095         datalink_Up(dl, 1, 1);
1096         if (mask & PHYS_AUTO)
1097           break;			/* Only one AUTO link at a time */
1098       }
1099       if (name != NULL)
1100         break;
1101     }
1102 }
1103 
1104 struct datalink *
1105 bundle2datalink(struct bundle *bundle, const char *name)
1106 {
1107   struct datalink *dl;
1108 
1109   if (name != NULL) {
1110     for (dl = bundle->links; dl; dl = dl->next)
1111       if (!strcasecmp(dl->name, name))
1112         return dl;
1113   } else if (bundle->links && !bundle->links->next)
1114     return bundle->links;
1115 
1116   return NULL;
1117 }
1118 
1119 int
1120 bundle_ShowLinks(struct cmdargs const *arg)
1121 {
1122   struct datalink *dl;
1123   struct pppThroughput *t;
1124   unsigned long long octets;
1125   int secs;
1126 
1127   for (dl = arg->bundle->links; dl; dl = dl->next) {
1128     octets = MAX(dl->physical->link.stats.total.in.OctetsPerSecond,
1129                  dl->physical->link.stats.total.out.OctetsPerSecond);
1130 
1131     prompt_Printf(arg->prompt, "Name: %s [%s, %s]",
1132                   dl->name, mode2Nam(dl->physical->type), datalink_State(dl));
1133     if (dl->physical->link.stats.total.rolling && dl->state == DATALINK_OPEN)
1134       prompt_Printf(arg->prompt, " bandwidth %d, %llu bps (%llu bytes/sec)",
1135                     dl->mp.bandwidth ? dl->mp.bandwidth :
1136                                        physical_GetSpeed(dl->physical),
1137                     octets * 8, octets);
1138     prompt_Printf(arg->prompt, "\n");
1139   }
1140 
1141   t = &arg->bundle->ncp.mp.link.stats.total;
1142   octets = MAX(t->in.OctetsPerSecond, t->out.OctetsPerSecond);
1143   secs = t->downtime ? 0 : throughput_uptime(t);
1144   if (secs > t->SamplePeriod)
1145     secs = t->SamplePeriod;
1146   if (secs)
1147     prompt_Printf(arg->prompt, "Currently averaging %llu bps (%llu bytes/sec)"
1148                   " over the last %d secs\n", octets * 8, octets, secs);
1149 
1150   return 0;
1151 }
1152 
1153 static const char *
1154 optval(struct bundle *bundle, int bit)
1155 {
1156   return (bundle->cfg.opt & bit) ? "enabled" : "disabled";
1157 }
1158 
1159 int
1160 bundle_ShowStatus(struct cmdargs const *arg)
1161 {
1162   int remaining;
1163 
1164   prompt_Printf(arg->prompt, "Phase %s\n", bundle_PhaseName(arg->bundle));
1165   prompt_Printf(arg->prompt, " Device:        %s\n", arg->bundle->dev.Name);
1166   prompt_Printf(arg->prompt, " Interface:     %s @ %lubps",
1167                 arg->bundle->iface->name, arg->bundle->bandwidth);
1168 
1169   if (arg->bundle->upat) {
1170     int secs = time(NULL) - arg->bundle->upat;
1171 
1172     prompt_Printf(arg->prompt, ", up time %d:%02d:%02d", secs / 3600,
1173                   (secs / 60) % 60, secs % 60);
1174   }
1175   prompt_Printf(arg->prompt, "\n Queued:        %lu of %u\n",
1176                 (unsigned long)ip_QueueLen(&arg->bundle->ncp.ipcp),
1177                 arg->bundle->cfg.ifqueue);
1178 
1179   prompt_Printf(arg->prompt, "\nDefaults:\n");
1180   prompt_Printf(arg->prompt, " Label:         %s\n", arg->bundle->cfg.label);
1181   prompt_Printf(arg->prompt, " Auth name:     %s\n",
1182                 arg->bundle->cfg.auth.name);
1183 
1184   prompt_Printf(arg->prompt, " Choked Timer:  %ds\n",
1185                 arg->bundle->cfg.choked.timeout);
1186 
1187 #ifndef NORADIUS
1188   radius_Show(&arg->bundle->radius, arg->prompt);
1189 #endif
1190 
1191   prompt_Printf(arg->prompt, " Idle Timer:    ");
1192   if (arg->bundle->cfg.idle.timeout) {
1193     prompt_Printf(arg->prompt, "%ds", arg->bundle->cfg.idle.timeout);
1194     if (arg->bundle->cfg.idle.min_timeout)
1195       prompt_Printf(arg->prompt, ", min %ds",
1196                     arg->bundle->cfg.idle.min_timeout);
1197     remaining = bundle_RemainingIdleTime(arg->bundle);
1198     if (remaining != -1)
1199       prompt_Printf(arg->prompt, " (%ds remaining)", remaining);
1200     prompt_Printf(arg->prompt, "\n");
1201   } else
1202     prompt_Printf(arg->prompt, "disabled\n");
1203   prompt_Printf(arg->prompt, " MTU:           ");
1204   if (arg->bundle->cfg.mtu)
1205     prompt_Printf(arg->prompt, "%d\n", arg->bundle->cfg.mtu);
1206   else
1207     prompt_Printf(arg->prompt, "unspecified\n");
1208 
1209   prompt_Printf(arg->prompt, " sendpipe:      ");
1210   if (arg->bundle->ncp.ipcp.cfg.sendpipe > 0)
1211     prompt_Printf(arg->prompt, "%-20ld", arg->bundle->ncp.ipcp.cfg.sendpipe);
1212   else
1213     prompt_Printf(arg->prompt, "unspecified         ");
1214   prompt_Printf(arg->prompt, " recvpipe:      ");
1215   if (arg->bundle->ncp.ipcp.cfg.recvpipe > 0)
1216     prompt_Printf(arg->prompt, "%ld\n", arg->bundle->ncp.ipcp.cfg.recvpipe);
1217   else
1218     prompt_Printf(arg->prompt, "unspecified\n");
1219 
1220   prompt_Printf(arg->prompt, " Sticky Routes: %-20.20s",
1221                 optval(arg->bundle, OPT_SROUTES));
1222   prompt_Printf(arg->prompt, " Filter Decap:  %s\n",
1223                 optval(arg->bundle, OPT_FILTERDECAP));
1224   prompt_Printf(arg->prompt, " ID check:      %-20.20s",
1225                 optval(arg->bundle, OPT_IDCHECK));
1226   prompt_Printf(arg->prompt, " Keep-Session:  %s\n",
1227                 optval(arg->bundle, OPT_KEEPSESSION));
1228   prompt_Printf(arg->prompt, " Loopback:      %-20.20s",
1229                 optval(arg->bundle, OPT_LOOPBACK));
1230   prompt_Printf(arg->prompt, " PasswdAuth:    %s\n",
1231                 optval(arg->bundle, OPT_PASSWDAUTH));
1232   prompt_Printf(arg->prompt, " Proxy:         %-20.20s",
1233                 optval(arg->bundle, OPT_PROXY));
1234   prompt_Printf(arg->prompt, " Proxyall:      %s\n",
1235                 optval(arg->bundle, OPT_PROXYALL));
1236   prompt_Printf(arg->prompt, " TCPMSS Fixup:  %-20.20s",
1237                 optval(arg->bundle, OPT_TCPMSSFIXUP));
1238   prompt_Printf(arg->prompt, " Throughput:    %s\n",
1239                 optval(arg->bundle, OPT_THROUGHPUT));
1240   prompt_Printf(arg->prompt, " Utmp Logging:  %-20.20s",
1241                 optval(arg->bundle, OPT_UTMP));
1242   prompt_Printf(arg->prompt, " Iface-Alias:   %s\n",
1243                 optval(arg->bundle, OPT_IFACEALIAS));
1244 
1245   return 0;
1246 }
1247 
1248 static void
1249 bundle_IdleTimeout(void *v)
1250 {
1251   struct bundle *bundle = (struct bundle *)v;
1252 
1253   log_Printf(LogPHASE, "Idle timer expired\n");
1254   bundle_StopIdleTimer(bundle);
1255   bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
1256 }
1257 
1258 /*
1259  *  Start Idle timer. If timeout is reached, we call bundle_Close() to
1260  *  close LCP and link.
1261  */
1262 void
1263 bundle_StartIdleTimer(struct bundle *bundle, unsigned secs)
1264 {
1265   timer_Stop(&bundle->idle.timer);
1266   if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) !=
1267       bundle->phys_type.open && bundle->cfg.idle.timeout) {
1268     time_t now = time(NULL);
1269 
1270     if (secs == 0)
1271       secs = bundle->cfg.idle.timeout;
1272 
1273     /* We want at least `secs' */
1274     if (bundle->cfg.idle.min_timeout > secs && bundle->upat) {
1275       int up = now - bundle->upat;
1276 
1277       if ((long long)bundle->cfg.idle.min_timeout - up > (long long)secs)
1278         /* Only increase from the current `remaining' value */
1279         secs = bundle->cfg.idle.min_timeout - up;
1280     }
1281     bundle->idle.timer.func = bundle_IdleTimeout;
1282     bundle->idle.timer.name = "idle";
1283     bundle->idle.timer.load = secs * SECTICKS;
1284     bundle->idle.timer.arg = bundle;
1285     timer_Start(&bundle->idle.timer);
1286     bundle->idle.done = now + secs;
1287   }
1288 }
1289 
1290 void
1291 bundle_SetIdleTimer(struct bundle *bundle, int timeout, int min_timeout)
1292 {
1293   bundle->cfg.idle.timeout = timeout;
1294   if (min_timeout >= 0)
1295     bundle->cfg.idle.min_timeout = min_timeout;
1296   if (bundle_LinkIsUp(bundle))
1297     bundle_StartIdleTimer(bundle, 0);
1298 }
1299 
1300 void
1301 bundle_StopIdleTimer(struct bundle *bundle)
1302 {
1303   timer_Stop(&bundle->idle.timer);
1304   bundle->idle.done = 0;
1305 }
1306 
1307 static int
1308 bundle_RemainingIdleTime(struct bundle *bundle)
1309 {
1310   if (bundle->idle.done)
1311     return bundle->idle.done - time(NULL);
1312   return -1;
1313 }
1314 
1315 int
1316 bundle_IsDead(struct bundle *bundle)
1317 {
1318   return !bundle->links || (bundle->phase == PHASE_DEAD && bundle->CleaningUp);
1319 }
1320 
1321 static struct datalink *
1322 bundle_DatalinkLinkout(struct bundle *bundle, struct datalink *dl)
1323 {
1324   struct datalink **dlp;
1325 
1326   for (dlp = &bundle->links; *dlp; dlp = &(*dlp)->next)
1327     if (*dlp == dl) {
1328       *dlp = dl->next;
1329       dl->next = NULL;
1330       bundle_LinksRemoved(bundle);
1331       return dl;
1332     }
1333 
1334   return NULL;
1335 }
1336 
1337 static void
1338 bundle_DatalinkLinkin(struct bundle *bundle, struct datalink *dl)
1339 {
1340   struct datalink **dlp = &bundle->links;
1341 
1342   while (*dlp)
1343     dlp = &(*dlp)->next;
1344 
1345   *dlp = dl;
1346   dl->next = NULL;
1347 
1348   bundle_LinkAdded(bundle, dl);
1349   mp_CheckAutoloadTimer(&bundle->ncp.mp);
1350 }
1351 
1352 void
1353 bundle_CleanDatalinks(struct bundle *bundle)
1354 {
1355   struct datalink **dlp = &bundle->links;
1356   int found = 0;
1357 
1358   while (*dlp)
1359     if ((*dlp)->state == DATALINK_CLOSED &&
1360         (*dlp)->physical->type &
1361         (PHYS_DIRECT|PHYS_BACKGROUND|PHYS_FOREGROUND)) {
1362       *dlp = datalink_Destroy(*dlp);
1363       found++;
1364     } else
1365       dlp = &(*dlp)->next;
1366 
1367   if (found)
1368     bundle_LinksRemoved(bundle);
1369 }
1370 
1371 int
1372 bundle_DatalinkClone(struct bundle *bundle, struct datalink *dl,
1373                      const char *name)
1374 {
1375   if (bundle2datalink(bundle, name)) {
1376     log_Printf(LogWARN, "Clone: %s: name already exists\n", name);
1377     return 0;
1378   }
1379 
1380   bundle_DatalinkLinkin(bundle, datalink_Clone(dl, name));
1381   return 1;
1382 }
1383 
1384 void
1385 bundle_DatalinkRemove(struct bundle *bundle, struct datalink *dl)
1386 {
1387   dl = bundle_DatalinkLinkout(bundle, dl);
1388   if (dl)
1389     datalink_Destroy(dl);
1390 }
1391 
1392 void
1393 bundle_SetLabel(struct bundle *bundle, const char *label)
1394 {
1395   if (label)
1396     strncpy(bundle->cfg.label, label, sizeof bundle->cfg.label - 1);
1397   else
1398     *bundle->cfg.label = '\0';
1399 }
1400 
1401 const char *
1402 bundle_GetLabel(struct bundle *bundle)
1403 {
1404   return *bundle->cfg.label ? bundle->cfg.label : NULL;
1405 }
1406 
1407 int
1408 bundle_LinkSize()
1409 {
1410   struct iovec iov[SCATTER_SEGMENTS];
1411   int niov, expect, f;
1412 
1413   iov[0].iov_len = strlen(Version) + 1;
1414   iov[0].iov_base = NULL;
1415   niov = 1;
1416   if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1417     log_Printf(LogERROR, "Cannot determine space required for link\n");
1418     return 0;
1419   }
1420 
1421   for (f = expect = 0; f < niov; f++)
1422     expect += iov[f].iov_len;
1423 
1424   return expect;
1425 }
1426 
1427 void
1428 bundle_ReceiveDatalink(struct bundle *bundle, int s)
1429 {
1430   char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int) * SEND_MAXFD];
1431   int niov, expect, f, *fd, nfd, onfd, got;
1432   struct iovec iov[SCATTER_SEGMENTS];
1433   struct cmsghdr *cmsg;
1434   struct msghdr msg;
1435   struct datalink *dl;
1436   pid_t pid;
1437 
1438   log_Printf(LogPHASE, "Receiving datalink\n");
1439 
1440   /*
1441    * Create our scatter/gather array - passing NULL gets the space
1442    * allocation requirement rather than actually flattening the
1443    * structures.
1444    */
1445   iov[0].iov_len = strlen(Version) + 1;
1446   iov[0].iov_base = NULL;
1447   niov = 1;
1448   if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1449     log_Printf(LogERROR, "Cannot determine space required for link\n");
1450     return;
1451   }
1452 
1453   /* Allocate the scatter/gather array for recvmsg() */
1454   for (f = expect = 0; f < niov; f++) {
1455     if ((iov[f].iov_base = malloc(iov[f].iov_len)) == NULL) {
1456       log_Printf(LogERROR, "Cannot allocate space to receive link\n");
1457       return;
1458     }
1459     if (f)
1460       expect += iov[f].iov_len;
1461   }
1462 
1463   /* Set up our message */
1464   cmsg = (struct cmsghdr *)cmsgbuf;
1465   cmsg->cmsg_len = sizeof cmsgbuf;
1466   cmsg->cmsg_level = SOL_SOCKET;
1467   cmsg->cmsg_type = 0;
1468 
1469   memset(&msg, '\0', sizeof msg);
1470   msg.msg_name = NULL;
1471   msg.msg_namelen = 0;
1472   msg.msg_iov = iov;
1473   msg.msg_iovlen = 1;		/* Only send the version at the first pass */
1474   msg.msg_control = cmsgbuf;
1475   msg.msg_controllen = sizeof cmsgbuf;
1476 
1477   log_Printf(LogDEBUG, "Expecting %u scatter/gather bytes\n",
1478              (unsigned)iov[0].iov_len);
1479 
1480   if ((got = recvmsg(s, &msg, MSG_WAITALL)) != iov[0].iov_len) {
1481     if (got == -1)
1482       log_Printf(LogERROR, "Failed recvmsg: %s\n", strerror(errno));
1483     else
1484       log_Printf(LogERROR, "Failed recvmsg: Got %d, not %u\n",
1485                  got, (unsigned)iov[0].iov_len);
1486     while (niov--)
1487       free(iov[niov].iov_base);
1488     return;
1489   }
1490 
1491   if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) {
1492     log_Printf(LogERROR, "Recvmsg: no descriptors received !\n");
1493     while (niov--)
1494       free(iov[niov].iov_base);
1495     return;
1496   }
1497 
1498   fd = (int *)(cmsg + 1);
1499   nfd = (cmsg->cmsg_len - sizeof *cmsg) / sizeof(int);
1500 
1501   if (nfd < 2) {
1502     log_Printf(LogERROR, "Recvmsg: %d descriptor%s received (too few) !\n",
1503                nfd, nfd == 1 ? "" : "s");
1504     while (nfd--)
1505       close(fd[nfd]);
1506     while (niov--)
1507       free(iov[niov].iov_base);
1508     return;
1509   }
1510 
1511   /*
1512    * We've successfully received two or more open file descriptors
1513    * through our socket, plus a version string.  Make sure it's the
1514    * correct version, and drop the connection if it's not.
1515    */
1516   if (strncmp(Version, iov[0].iov_base, iov[0].iov_len)) {
1517     log_Printf(LogWARN, "Cannot receive datalink, incorrect version"
1518                " (\"%.*s\", not \"%s\")\n", (int)iov[0].iov_len,
1519                (char *)iov[0].iov_base, Version);
1520     while (nfd--)
1521       close(fd[nfd]);
1522     while (niov--)
1523       free(iov[niov].iov_base);
1524     return;
1525   }
1526 
1527   /*
1528    * Everything looks good.  Send the other side our process id so that
1529    * they can transfer lock ownership, and wait for them to send the
1530    * actual link data.
1531    */
1532   pid = getpid();
1533   if ((got = write(fd[1], &pid, sizeof pid)) != sizeof pid) {
1534     if (got == -1)
1535       log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1536     else
1537       log_Printf(LogERROR, "Failed write: Got %d, not %d\n", got,
1538                  (int)(sizeof pid));
1539     while (nfd--)
1540       close(fd[nfd]);
1541     while (niov--)
1542       free(iov[niov].iov_base);
1543     return;
1544   }
1545 
1546   if ((got = readv(fd[1], iov + 1, niov - 1)) != expect) {
1547     if (got == -1)
1548       log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1549     else
1550       log_Printf(LogERROR, "Failed write: Got %d, not %d\n", got, expect);
1551     while (nfd--)
1552       close(fd[nfd]);
1553     while (niov--)
1554       free(iov[niov].iov_base);
1555     return;
1556   }
1557   close(fd[1]);
1558 
1559   onfd = nfd;	/* We've got this many in our array */
1560   nfd -= 2;	/* Don't include p->fd and our reply descriptor */
1561   niov = 1;	/* Skip the version id */
1562   dl = iov2datalink(bundle, iov, &niov, sizeof iov / sizeof *iov, fd[0],
1563                     fd + 2, &nfd);
1564   if (dl) {
1565 
1566     if (nfd) {
1567       log_Printf(LogERROR, "bundle_ReceiveDatalink: Failed to handle %d "
1568                  "auxiliary file descriptors (%d remain)\n", onfd, nfd);
1569       datalink_Destroy(dl);
1570       while (nfd--)
1571         close(fd[onfd--]);
1572       close(fd[0]);
1573     } else {
1574       bundle_DatalinkLinkin(bundle, dl);
1575       datalink_AuthOk(dl);
1576       bundle_CalculateBandwidth(dl->bundle);
1577     }
1578   } else {
1579     while (nfd--)
1580       close(fd[onfd--]);
1581     close(fd[0]);
1582     close(fd[1]);
1583   }
1584 
1585   free(iov[0].iov_base);
1586 }
1587 
1588 void
1589 bundle_SendDatalink(struct datalink *dl, int s, struct sockaddr_un *sun)
1590 {
1591   char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int) * SEND_MAXFD];
1592   const char *constlock;
1593   char *lock;
1594   struct cmsghdr *cmsg;
1595   struct msghdr msg;
1596   struct iovec iov[SCATTER_SEGMENTS];
1597   int niov, f, expect, newsid, fd[SEND_MAXFD], nfd, reply[2], got;
1598   pid_t newpid;
1599 
1600   log_Printf(LogPHASE, "Transmitting datalink %s\n", dl->name);
1601 
1602   /* Record the base device name for a lock transfer later */
1603   constlock = physical_LockedDevice(dl->physical);
1604   if (constlock) {
1605     lock = alloca(strlen(constlock) + 1);
1606     strcpy(lock, constlock);
1607   } else
1608     lock = NULL;
1609 
1610   bundle_LinkClosed(dl->bundle, dl);
1611   bundle_DatalinkLinkout(dl->bundle, dl);
1612 
1613   /* Build our scatter/gather array */
1614   iov[0].iov_len = strlen(Version) + 1;
1615   iov[0].iov_base = strdup(Version);
1616   niov = 1;
1617   nfd = 0;
1618 
1619   fd[0] = datalink2iov(dl, iov, &niov, SCATTER_SEGMENTS, fd + 2, &nfd);
1620 
1621   if (fd[0] != -1 && socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, reply) != -1) {
1622     /*
1623      * fd[1] is used to get the peer process id back, then to confirm that
1624      * we've transferred any device locks to that process id.
1625      */
1626     fd[1] = reply[1];
1627 
1628     nfd += 2;			/* Include fd[0] and fd[1] */
1629     memset(&msg, '\0', sizeof msg);
1630 
1631     msg.msg_name = NULL;
1632     msg.msg_namelen = 0;
1633     /*
1634      * Only send the version to start...  We used to send the whole lot, but
1635      * this caused problems with our RECVBUF size as a single link is about
1636      * 22k !  This way, we should bump into no limits.
1637      */
1638     msg.msg_iovlen = 1;
1639     msg.msg_iov = iov;
1640     msg.msg_control = cmsgbuf;
1641     msg.msg_controllen = sizeof *cmsg + sizeof(int) * nfd;
1642     msg.msg_flags = 0;
1643 
1644     cmsg = (struct cmsghdr *)cmsgbuf;
1645     cmsg->cmsg_len = msg.msg_controllen;
1646     cmsg->cmsg_level = SOL_SOCKET;
1647     cmsg->cmsg_type = SCM_RIGHTS;
1648 
1649     for (f = 0; f < nfd; f++)
1650       *((int *)(cmsg + 1) + f) = fd[f];
1651 
1652     for (f = 1, expect = 0; f < niov; f++)
1653       expect += iov[f].iov_len;
1654 
1655     if (setsockopt(reply[0], SOL_SOCKET, SO_SNDBUF, &expect, sizeof(int)) == -1)
1656       log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1657                  strerror(errno));
1658     if (setsockopt(reply[1], SOL_SOCKET, SO_RCVBUF, &expect, sizeof(int)) == -1)
1659       log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1660                  strerror(errno));
1661 
1662     log_Printf(LogDEBUG, "Sending %d descriptor%s and %u bytes in scatter"
1663                "/gather array\n", nfd, nfd == 1 ? "" : "s",
1664                (unsigned)iov[0].iov_len);
1665 
1666     if ((got = sendmsg(s, &msg, 0)) == -1)
1667       log_Printf(LogERROR, "Failed sendmsg: %s: %s\n",
1668                  sun->sun_path, strerror(errno));
1669     else if (got != iov[0].iov_len)
1670       log_Printf(LogERROR, "%s: Failed initial sendmsg: Only sent %d of %u\n",
1671                  sun->sun_path, got, (unsigned)iov[0].iov_len);
1672     else {
1673       /* We must get the ACK before closing the descriptor ! */
1674       int res;
1675 
1676       if ((got = read(reply[0], &newpid, sizeof newpid)) == sizeof newpid) {
1677         log_Printf(LogDEBUG, "Received confirmation from pid %d\n",
1678                    (int)newpid);
1679         if (lock && (res = ID0uu_lock_txfr(lock, newpid)) != UU_LOCK_OK)
1680             log_Printf(LogERROR, "uu_lock_txfr: %s\n", uu_lockerr(res));
1681 
1682         log_Printf(LogDEBUG, "Transmitting link (%d bytes)\n", expect);
1683         if ((got = writev(reply[0], iov + 1, niov - 1)) != expect) {
1684           if (got == -1)
1685             log_Printf(LogERROR, "%s: Failed writev: %s\n",
1686                        sun->sun_path, strerror(errno));
1687           else
1688             log_Printf(LogERROR, "%s: Failed writev: Wrote %d of %d\n",
1689                        sun->sun_path, got, expect);
1690         }
1691       } else if (got == -1)
1692         log_Printf(LogERROR, "%s: Failed socketpair read: %s\n",
1693                    sun->sun_path, strerror(errno));
1694       else
1695         log_Printf(LogERROR, "%s: Failed socketpair read: Got %d of %d\n",
1696                    sun->sun_path, got, (int)(sizeof newpid));
1697     }
1698 
1699     close(reply[0]);
1700     close(reply[1]);
1701 
1702     newsid = Enabled(dl->bundle, OPT_KEEPSESSION) ||
1703              tcgetpgrp(fd[0]) == getpgrp();
1704     while (nfd)
1705       close(fd[--nfd]);
1706     if (newsid)
1707       bundle_setsid(dl->bundle, got != -1);
1708   }
1709   close(s);
1710 
1711   while (niov--)
1712     free(iov[niov].iov_base);
1713 }
1714 
1715 int
1716 bundle_RenameDatalink(struct bundle *bundle, struct datalink *ndl,
1717                       const char *name)
1718 {
1719   struct datalink *dl;
1720 
1721   if (!strcasecmp(ndl->name, name))
1722     return 1;
1723 
1724   for (dl = bundle->links; dl; dl = dl->next)
1725     if (!strcasecmp(dl->name, name))
1726       return 0;
1727 
1728   datalink_Rename(ndl, name);
1729   return 1;
1730 }
1731 
1732 int
1733 bundle_SetMode(struct bundle *bundle, struct datalink *dl, int mode)
1734 {
1735   int omode;
1736 
1737   omode = dl->physical->type;
1738   if (omode == mode)
1739     return 1;
1740 
1741   if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO))
1742     /* First auto link */
1743     if (bundle->ncp.ipcp.peer_ip.s_addr == INADDR_ANY) {
1744       log_Printf(LogWARN, "You must `set ifaddr' or `open' before"
1745                  " changing mode to %s\n", mode2Nam(mode));
1746       return 0;
1747     }
1748 
1749   if (!datalink_SetMode(dl, mode))
1750     return 0;
1751 
1752   if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO) &&
1753       bundle->phase != PHASE_NETWORK)
1754     /* First auto link, we need an interface */
1755     ipcp_InterfaceUp(&bundle->ncp.ipcp);
1756 
1757   /* Regenerate phys_type and adjust idle timer */
1758   bundle_LinksRemoved(bundle);
1759 
1760   return 1;
1761 }
1762 
1763 void
1764 bundle_setsid(struct bundle *bundle, int holdsession)
1765 {
1766   /*
1767    * Lose the current session.  This means getting rid of our pid
1768    * too so that the tty device will really go away, and any getty
1769    * etc will be allowed to restart.
1770    */
1771   pid_t pid, orig;
1772   int fds[2];
1773   char done;
1774   struct datalink *dl;
1775 
1776   if (!holdsession && bundle_IsDead(bundle)) {
1777     /*
1778      * No need to lose our session after all... we're going away anyway
1779      *
1780      * We should really stop the timer and pause if holdsession is set and
1781      * the bundle's dead, but that leaves other resources lying about :-(
1782      */
1783     return;
1784   }
1785 
1786   orig = getpid();
1787   if (pipe(fds) == -1) {
1788     log_Printf(LogERROR, "pipe: %s\n", strerror(errno));
1789     return;
1790   }
1791   switch ((pid = fork())) {
1792     case -1:
1793       log_Printf(LogERROR, "fork: %s\n", strerror(errno));
1794       close(fds[0]);
1795       close(fds[1]);
1796       return;
1797     case 0:
1798       close(fds[1]);
1799       read(fds[0], &done, 1);		/* uu_locks are mine ! */
1800       close(fds[0]);
1801       if (pipe(fds) == -1) {
1802         log_Printf(LogERROR, "pipe(2): %s\n", strerror(errno));
1803         return;
1804       }
1805       switch ((pid = fork())) {
1806         case -1:
1807           log_Printf(LogERROR, "fork(2): %s\n", strerror(errno));
1808           close(fds[0]);
1809           close(fds[1]);
1810           return;
1811         case 0:
1812           close(fds[1]);
1813           bundle_LockTun(bundle);	/* update pid */
1814           read(fds[0], &done, 1);	/* uu_locks are mine ! */
1815           close(fds[0]);
1816           setsid();
1817           bundle_ChangedPID(bundle);
1818           log_Printf(LogDEBUG, "%d -> %d: %s session control\n",
1819                      (int)orig, (int)getpid(),
1820                      holdsession ? "Passed" : "Dropped");
1821           timer_InitService(0);		/* Start the Timer Service */
1822           break;
1823         default:
1824           close(fds[0]);
1825           /* Give away all our physical locks (to the final process) */
1826           for (dl = bundle->links; dl; dl = dl->next)
1827             if (dl->state != DATALINK_CLOSED)
1828               physical_ChangedPid(dl->physical, pid);
1829           write(fds[1], "!", 1);	/* done */
1830           close(fds[1]);
1831           _exit(0);
1832           break;
1833       }
1834       break;
1835     default:
1836       close(fds[0]);
1837       /* Give away all our physical locks (to the intermediate process) */
1838       for (dl = bundle->links; dl; dl = dl->next)
1839         if (dl->state != DATALINK_CLOSED)
1840           physical_ChangedPid(dl->physical, pid);
1841       write(fds[1], "!", 1);	/* done */
1842       close(fds[1]);
1843       if (holdsession) {
1844         int fd, status;
1845 
1846         timer_TermService();
1847         signal(SIGPIPE, SIG_DFL);
1848         signal(SIGALRM, SIG_DFL);
1849         signal(SIGHUP, SIG_DFL);
1850         signal(SIGTERM, SIG_DFL);
1851         signal(SIGINT, SIG_DFL);
1852         signal(SIGQUIT, SIG_DFL);
1853         for (fd = getdtablesize(); fd >= 0; fd--)
1854           close(fd);
1855         /*
1856          * Reap the intermediate process.  As we're not exiting but the
1857          * intermediate is, we don't want it to become defunct.
1858          */
1859         waitpid(pid, &status, 0);
1860         /* Tweak our process arguments.... */
1861         SetTitle("session owner");
1862 #ifndef NOSUID
1863         setuid(ID0realuid());
1864 #endif
1865         /*
1866          * Hang around for a HUP.  This should happen as soon as the
1867          * ppp that we passed our ctty descriptor to closes it.
1868          * NOTE: If this process dies, the passed descriptor becomes
1869          *       invalid and will give a select() error by setting one
1870          *       of the error fds, aborting the other ppp.  We don't
1871          *       want that to happen !
1872          */
1873         pause();
1874       }
1875       _exit(0);
1876       break;
1877   }
1878 }
1879 
1880 int
1881 bundle_HighestState(struct bundle *bundle)
1882 {
1883   struct datalink *dl;
1884   int result = DATALINK_CLOSED;
1885 
1886   for (dl = bundle->links; dl; dl = dl->next)
1887     if (result < dl->state)
1888       result = dl->state;
1889 
1890   return result;
1891 }
1892 
1893 int
1894 bundle_Exception(struct bundle *bundle, int fd)
1895 {
1896   struct datalink *dl;
1897 
1898   for (dl = bundle->links; dl; dl = dl->next)
1899     if (dl->physical->fd == fd) {
1900       datalink_Down(dl, CLOSE_NORMAL);
1901       return 1;
1902     }
1903 
1904   return 0;
1905 }
1906 
1907 void
1908 bundle_AdjustFilters(struct bundle *bundle, struct in_addr *my_ip,
1909                      struct in_addr *peer_ip)
1910 {
1911   filter_AdjustAddr(&bundle->filter.in, my_ip, peer_ip, NULL);
1912   filter_AdjustAddr(&bundle->filter.out, my_ip, peer_ip, NULL);
1913   filter_AdjustAddr(&bundle->filter.dial, my_ip, peer_ip, NULL);
1914   filter_AdjustAddr(&bundle->filter.alive, my_ip, peer_ip, NULL);
1915 }
1916 
1917 void
1918 bundle_AdjustDNS(struct bundle *bundle, struct in_addr dns[2])
1919 {
1920   filter_AdjustAddr(&bundle->filter.in, NULL, NULL, dns);
1921   filter_AdjustAddr(&bundle->filter.out, NULL, NULL, dns);
1922   filter_AdjustAddr(&bundle->filter.dial, NULL, NULL, dns);
1923   filter_AdjustAddr(&bundle->filter.alive, NULL, NULL, dns);
1924 }
1925 
1926 void
1927 bundle_CalculateBandwidth(struct bundle *bundle)
1928 {
1929   struct datalink *dl;
1930   int sp;
1931 
1932   bundle->bandwidth = 0;
1933   bundle->mtu = 0;
1934   for (dl = bundle->links; dl; dl = dl->next)
1935     if (dl->state == DATALINK_OPEN) {
1936       if ((sp = dl->mp.bandwidth) == 0 &&
1937           (sp = physical_GetSpeed(dl->physical)) == 0)
1938         log_Printf(LogDEBUG, "%s: %s: Cannot determine bandwidth\n",
1939                    dl->name, dl->physical->name.full);
1940       else
1941         bundle->bandwidth += sp;
1942       if (!bundle->ncp.mp.active) {
1943         bundle->mtu = dl->physical->link.lcp.his_mru;
1944         break;
1945       }
1946     }
1947 
1948   if(bundle->bandwidth == 0)
1949     bundle->bandwidth = 115200;		/* Shrug */
1950 
1951   if (bundle->ncp.mp.active)
1952     bundle->mtu = bundle->ncp.mp.peer_mrru;
1953   else if (!bundle->mtu)
1954     bundle->mtu = 1500;
1955 
1956 #ifndef NORADIUS
1957   if (bundle->radius.valid && bundle->radius.mtu &&
1958       bundle->radius.mtu < bundle->mtu) {
1959     log_Printf(LogLCP, "Reducing MTU to radius value %lu\n",
1960                bundle->radius.mtu);
1961     bundle->mtu = bundle->radius.mtu;
1962   }
1963 #endif
1964 
1965   tun_configure(bundle);
1966 }
1967 
1968 void
1969 bundle_AutoAdjust(struct bundle *bundle, int percent, int what)
1970 {
1971   struct datalink *dl, *choice, *otherlinkup;
1972 
1973   choice = otherlinkup = NULL;
1974   for (dl = bundle->links; dl; dl = dl->next)
1975     if (dl->physical->type == PHYS_AUTO) {
1976       if (dl->state == DATALINK_OPEN) {
1977         if (what == AUTO_DOWN) {
1978           if (choice)
1979             otherlinkup = choice;
1980           choice = dl;
1981         }
1982       } else if (dl->state == DATALINK_CLOSED) {
1983         if (what == AUTO_UP) {
1984           choice = dl;
1985           break;
1986         }
1987       } else {
1988         /* An auto link in an intermediate state - forget it for the moment */
1989         choice = NULL;
1990         break;
1991       }
1992     } else if (dl->state == DATALINK_OPEN && what == AUTO_DOWN)
1993       otherlinkup = dl;
1994 
1995   if (choice) {
1996     if (what == AUTO_UP) {
1997       log_Printf(LogPHASE, "%d%% saturation -> Opening link ``%s''\n",
1998                  percent, choice->name);
1999       datalink_Up(choice, 1, 1);
2000       mp_CheckAutoloadTimer(&bundle->ncp.mp);
2001     } else if (otherlinkup) {	/* Only bring the second-last link down */
2002       log_Printf(LogPHASE, "%d%% saturation -> Closing link ``%s''\n",
2003                  percent, choice->name);
2004       datalink_Close(choice, CLOSE_STAYDOWN);
2005       mp_CheckAutoloadTimer(&bundle->ncp.mp);
2006     }
2007   }
2008 }
2009 
2010 int
2011 bundle_WantAutoloadTimer(struct bundle *bundle)
2012 {
2013   struct datalink *dl;
2014   int autolink, opened;
2015 
2016   if (bundle->phase == PHASE_NETWORK) {
2017     for (autolink = opened = 0, dl = bundle->links; dl; dl = dl->next)
2018       if (dl->physical->type == PHYS_AUTO) {
2019         if (++autolink == 2 || (autolink == 1 && opened))
2020           /* Two auto links or one auto and one open in NETWORK phase */
2021           return 1;
2022       } else if (dl->state == DATALINK_OPEN) {
2023         opened++;
2024         if (autolink)
2025           /* One auto and one open link in NETWORK phase */
2026           return 1;
2027       }
2028   }
2029 
2030   return 0;
2031 }
2032 
2033 void
2034 bundle_ChangedPID(struct bundle *bundle)
2035 {
2036 #ifdef TUNSIFPID
2037   ioctl(bundle->dev.fd, TUNSIFPID, 0);
2038 #endif
2039 }
2040