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