xref: /freebsd/usr.sbin/ppp/bundle.c (revision 04c9749ff0148ec8f73b150cec8bc2c094a5d31a)
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.routing_seq = 0;
801   bundle.phase = PHASE_DEAD;
802   bundle.CleaningUp = 0;
803   bundle.NatEnabled = 0;
804 
805   bundle.fsm.LayerStart = bundle_LayerStart;
806   bundle.fsm.LayerUp = bundle_LayerUp;
807   bundle.fsm.LayerDown = bundle_LayerDown;
808   bundle.fsm.LayerFinish = bundle_LayerFinish;
809   bundle.fsm.object = &bundle;
810 
811   bundle.cfg.idle.timeout = NCP_IDLE_TIMEOUT;
812   bundle.cfg.idle.min_timeout = 0;
813   *bundle.cfg.auth.name = '\0';
814   *bundle.cfg.auth.key = '\0';
815   bundle.cfg.opt = OPT_SROUTES | OPT_IDCHECK | OPT_LOOPBACK |
816                    OPT_THROUGHPUT | OPT_UTMP;
817   *bundle.cfg.label = '\0';
818   bundle.cfg.mtu = DEF_MTU;
819   bundle.cfg.ifqueue = DEF_IFQUEUE;
820   bundle.cfg.choked.timeout = CHOKED_TIMEOUT;
821   bundle.phys_type.all = type;
822   bundle.phys_type.open = 0;
823   bundle.upat = 0;
824 
825   bundle.links = datalink_Create("deflink", &bundle, type);
826   if (bundle.links == NULL) {
827     log_Printf(LogALERT, "Cannot create data link: %s\n", strerror(errno));
828     iface_Destroy(bundle.iface);
829     bundle.iface = NULL;
830     close(bundle.dev.fd);
831     return NULL;
832   }
833 
834   bundle.desc.type = BUNDLE_DESCRIPTOR;
835   bundle.desc.UpdateSet = bundle_UpdateSet;
836   bundle.desc.IsSet = bundle_IsSet;
837   bundle.desc.Read = bundle_DescriptorRead;
838   bundle.desc.Write = bundle_DescriptorWrite;
839 
840   mp_Init(&bundle.ncp.mp, &bundle);
841 
842   /* Send over the first physical link by default */
843   ipcp_Init(&bundle.ncp.ipcp, &bundle, &bundle.links->physical->link,
844             &bundle.fsm);
845 
846   memset(&bundle.filter, '\0', sizeof bundle.filter);
847   bundle.filter.in.fragok = bundle.filter.in.logok = 1;
848   bundle.filter.in.name = "IN";
849   bundle.filter.out.fragok = bundle.filter.out.logok = 1;
850   bundle.filter.out.name = "OUT";
851   bundle.filter.dial.name = "DIAL";
852   bundle.filter.dial.logok = 1;
853   bundle.filter.alive.name = "ALIVE";
854   bundle.filter.alive.logok = 1;
855   {
856     int	i;
857     for (i = 0; i < MAXFILTERS; i++) {
858         bundle.filter.in.rule[i].f_action = A_NONE;
859         bundle.filter.out.rule[i].f_action = A_NONE;
860         bundle.filter.dial.rule[i].f_action = A_NONE;
861         bundle.filter.alive.rule[i].f_action = A_NONE;
862     }
863   }
864   memset(&bundle.idle.timer, '\0', sizeof bundle.idle.timer);
865   bundle.idle.done = 0;
866   bundle.notify.fd = -1;
867   memset(&bundle.choked.timer, '\0', sizeof bundle.choked.timer);
868 #ifndef NORADIUS
869   radius_Init(&bundle.radius);
870 #endif
871 
872   /* Clean out any leftover crud */
873   iface_Clear(bundle.iface, IFACE_CLEAR_ALL);
874 
875   bundle_LockTun(&bundle);
876 
877   return &bundle;
878 }
879 
880 static void
881 bundle_DownInterface(struct bundle *bundle)
882 {
883   route_IfDelete(bundle, 1);
884   iface_ClearFlags(bundle->iface, IFF_UP);
885 }
886 
887 void
888 bundle_Destroy(struct bundle *bundle)
889 {
890   struct datalink *dl;
891 
892   /*
893    * Clean up the interface.  We don't need to timer_Stop()s, mp_Down(),
894    * ipcp_CleanInterface() and bundle_DownInterface() unless we're getting
895    * out under exceptional conditions such as a descriptor exception.
896    */
897   timer_Stop(&bundle->idle.timer);
898   timer_Stop(&bundle->choked.timer);
899   mp_Down(&bundle->ncp.mp);
900   ipcp_CleanInterface(&bundle->ncp.ipcp);
901   bundle_DownInterface(bundle);
902 
903 #ifndef NORADIUS
904   /* Tell the radius server the bad news */
905   radius_Destroy(&bundle->radius);
906 #endif
907 
908   /* Again, these are all DATALINK_CLOSED unless we're abending */
909   dl = bundle->links;
910   while (dl)
911     dl = datalink_Destroy(dl);
912 
913   ipcp_Destroy(&bundle->ncp.ipcp);
914 
915   close(bundle->dev.fd);
916   bundle_UnlockTun(bundle);
917 
918   /* In case we never made PHASE_NETWORK */
919   bundle_Notify(bundle, EX_ERRDEAD);
920 
921   iface_Destroy(bundle->iface);
922   bundle->iface = NULL;
923 }
924 
925 struct rtmsg {
926   struct rt_msghdr m_rtm;
927   char m_space[64];
928 };
929 
930 int
931 bundle_SetRoute(struct bundle *bundle, int cmd, struct in_addr dst,
932                 struct in_addr gateway, struct in_addr mask, int bang, int ssh)
933 {
934   struct rtmsg rtmes;
935   int s, nb, wb;
936   char *cp;
937   const char *cmdstr;
938   struct sockaddr_in rtdata;
939   int result = 1;
940 
941   if (bang)
942     cmdstr = (cmd == RTM_ADD ? "Add!" : "Delete!");
943   else
944     cmdstr = (cmd == RTM_ADD ? "Add" : "Delete");
945   s = ID0socket(PF_ROUTE, SOCK_RAW, 0);
946   if (s < 0) {
947     log_Printf(LogERROR, "bundle_SetRoute: socket(): %s\n", strerror(errno));
948     return result;
949   }
950   memset(&rtmes, '\0', sizeof rtmes);
951   rtmes.m_rtm.rtm_version = RTM_VERSION;
952   rtmes.m_rtm.rtm_type = cmd;
953   rtmes.m_rtm.rtm_addrs = RTA_DST;
954   rtmes.m_rtm.rtm_seq = ++bundle->routing_seq;
955   rtmes.m_rtm.rtm_pid = getpid();
956   rtmes.m_rtm.rtm_flags = RTF_UP | RTF_GATEWAY | RTF_STATIC;
957 
958   if (cmd == RTM_ADD || cmd == RTM_CHANGE) {
959     if (bundle->ncp.ipcp.cfg.sendpipe > 0) {
960       rtmes.m_rtm.rtm_rmx.rmx_sendpipe = bundle->ncp.ipcp.cfg.sendpipe;
961       rtmes.m_rtm.rtm_inits |= RTV_SPIPE;
962     }
963     if (bundle->ncp.ipcp.cfg.recvpipe > 0) {
964       rtmes.m_rtm.rtm_rmx.rmx_recvpipe = bundle->ncp.ipcp.cfg.recvpipe;
965       rtmes.m_rtm.rtm_inits |= RTV_RPIPE;
966     }
967   }
968 
969   memset(&rtdata, '\0', sizeof rtdata);
970   rtdata.sin_len = sizeof rtdata;
971   rtdata.sin_family = AF_INET;
972   rtdata.sin_port = 0;
973   rtdata.sin_addr = dst;
974 
975   cp = rtmes.m_space;
976   memcpy(cp, &rtdata, rtdata.sin_len);
977   cp += rtdata.sin_len;
978   if (cmd == RTM_ADD) {
979     if (gateway.s_addr == INADDR_ANY) {
980       if (!ssh)
981         log_Printf(LogERROR, "bundle_SetRoute: Cannot add a route with"
982                    " destination 0.0.0.0\n");
983       close(s);
984       return result;
985     } else {
986       rtdata.sin_addr = gateway;
987       memcpy(cp, &rtdata, rtdata.sin_len);
988       cp += rtdata.sin_len;
989       rtmes.m_rtm.rtm_addrs |= RTA_GATEWAY;
990     }
991   }
992 
993   if (dst.s_addr == INADDR_ANY)
994     mask.s_addr = INADDR_ANY;
995 
996   if (cmd == RTM_ADD || dst.s_addr == INADDR_ANY) {
997     rtdata.sin_addr = mask;
998     memcpy(cp, &rtdata, rtdata.sin_len);
999     cp += rtdata.sin_len;
1000     rtmes.m_rtm.rtm_addrs |= RTA_NETMASK;
1001   }
1002 
1003   nb = cp - (char *) &rtmes;
1004   rtmes.m_rtm.rtm_msglen = nb;
1005   wb = ID0write(s, &rtmes, nb);
1006   if (wb < 0) {
1007     log_Printf(LogTCPIP, "bundle_SetRoute failure:\n");
1008     log_Printf(LogTCPIP, "bundle_SetRoute:  Cmd = %s\n", cmdstr);
1009     log_Printf(LogTCPIP, "bundle_SetRoute:  Dst = %s\n", inet_ntoa(dst));
1010     log_Printf(LogTCPIP, "bundle_SetRoute:  Gateway = %s\n",
1011                inet_ntoa(gateway));
1012     log_Printf(LogTCPIP, "bundle_SetRoute:  Mask = %s\n", inet_ntoa(mask));
1013 failed:
1014     if (cmd == RTM_ADD && (rtmes.m_rtm.rtm_errno == EEXIST ||
1015                            (rtmes.m_rtm.rtm_errno == 0 && errno == EEXIST))) {
1016       if (!bang) {
1017         log_Printf(LogWARN, "Add route failed: %s already exists\n",
1018 		  dst.s_addr == 0 ? "default" : inet_ntoa(dst));
1019         result = 0;	/* Don't add to our dynamic list */
1020       } else {
1021         rtmes.m_rtm.rtm_type = cmd = RTM_CHANGE;
1022         if ((wb = ID0write(s, &rtmes, nb)) < 0)
1023           goto failed;
1024       }
1025     } else if (cmd == RTM_DELETE &&
1026              (rtmes.m_rtm.rtm_errno == ESRCH ||
1027               (rtmes.m_rtm.rtm_errno == 0 && errno == ESRCH))) {
1028       if (!bang)
1029         log_Printf(LogWARN, "Del route failed: %s: Non-existent\n",
1030                   inet_ntoa(dst));
1031     } else if (rtmes.m_rtm.rtm_errno == 0) {
1032       if (!ssh || errno != ENETUNREACH)
1033         log_Printf(LogWARN, "%s route failed: %s: errno: %s\n", cmdstr,
1034                    inet_ntoa(dst), strerror(errno));
1035     } else
1036       log_Printf(LogWARN, "%s route failed: %s: %s\n",
1037 		 cmdstr, inet_ntoa(dst), strerror(rtmes.m_rtm.rtm_errno));
1038   }
1039   log_Printf(LogDEBUG, "wrote %d: cmd = %s, dst = %x, gateway = %x\n",
1040             wb, cmdstr, (unsigned)dst.s_addr, (unsigned)gateway.s_addr);
1041   close(s);
1042 
1043   return result;
1044 }
1045 
1046 void
1047 bundle_LinkClosed(struct bundle *bundle, struct datalink *dl)
1048 {
1049   /*
1050    * Our datalink has closed.
1051    * CleanDatalinks() (called from DoLoop()) will remove closed
1052    * BACKGROUND, FOREGROUND and DIRECT links.
1053    * If it's the last data link, enter phase DEAD.
1054    *
1055    * NOTE: dl may not be in our list (bundle_SendDatalink()) !
1056    */
1057 
1058   struct datalink *odl;
1059   int other_links;
1060 
1061   log_SetTtyCommandMode(dl);
1062 
1063   other_links = 0;
1064   for (odl = bundle->links; odl; odl = odl->next)
1065     if (odl != dl && odl->state != DATALINK_CLOSED)
1066       other_links++;
1067 
1068   if (!other_links) {
1069     if (dl->physical->type != PHYS_AUTO)	/* Not in -auto mode */
1070       bundle_DownInterface(bundle);
1071     fsm2initial(&bundle->ncp.ipcp.fsm);
1072     bundle_NewPhase(bundle, PHASE_DEAD);
1073     bundle_StopIdleTimer(bundle);
1074   }
1075 }
1076 
1077 void
1078 bundle_Open(struct bundle *bundle, const char *name, int mask, int force)
1079 {
1080   /*
1081    * Please open the given datalink, or all if name == NULL
1082    */
1083   struct datalink *dl;
1084 
1085   for (dl = bundle->links; dl; dl = dl->next)
1086     if (name == NULL || !strcasecmp(dl->name, name)) {
1087       if ((mask & dl->physical->type) &&
1088           (dl->state == DATALINK_CLOSED ||
1089            (force && dl->state == DATALINK_OPENING &&
1090             dl->dial.timer.state == TIMER_RUNNING) ||
1091            dl->state == DATALINK_READY)) {
1092         timer_Stop(&dl->dial.timer);	/* We're finished with this */
1093         datalink_Up(dl, 1, 1);
1094         if (mask & PHYS_AUTO)
1095           break;			/* Only one AUTO link at a time */
1096       }
1097       if (name != NULL)
1098         break;
1099     }
1100 }
1101 
1102 struct datalink *
1103 bundle2datalink(struct bundle *bundle, const char *name)
1104 {
1105   struct datalink *dl;
1106 
1107   if (name != NULL) {
1108     for (dl = bundle->links; dl; dl = dl->next)
1109       if (!strcasecmp(dl->name, name))
1110         return dl;
1111   } else if (bundle->links && !bundle->links->next)
1112     return bundle->links;
1113 
1114   return NULL;
1115 }
1116 
1117 int
1118 bundle_ShowLinks(struct cmdargs const *arg)
1119 {
1120   struct datalink *dl;
1121   struct pppThroughput *t;
1122   unsigned long long octets;
1123   int secs;
1124 
1125   for (dl = arg->bundle->links; dl; dl = dl->next) {
1126     octets = MAX(dl->physical->link.stats.total.in.OctetsPerSecond,
1127                  dl->physical->link.stats.total.out.OctetsPerSecond);
1128 
1129     prompt_Printf(arg->prompt, "Name: %s [%s, %s]",
1130                   dl->name, mode2Nam(dl->physical->type), datalink_State(dl));
1131     if (dl->physical->link.stats.total.rolling && dl->state == DATALINK_OPEN)
1132       prompt_Printf(arg->prompt, " bandwidth %d, %llu bps (%llu bytes/sec)",
1133                     dl->mp.bandwidth ? dl->mp.bandwidth :
1134                                        physical_GetSpeed(dl->physical),
1135                     octets * 8, octets);
1136     prompt_Printf(arg->prompt, "\n");
1137   }
1138 
1139   t = &arg->bundle->ncp.mp.link.stats.total;
1140   octets = MAX(t->in.OctetsPerSecond, t->out.OctetsPerSecond);
1141   secs = t->downtime ? 0 : throughput_uptime(t);
1142   if (secs > t->SamplePeriod)
1143     secs = t->SamplePeriod;
1144   if (secs)
1145     prompt_Printf(arg->prompt, "Currently averaging %llu bps (%llu bytes/sec)"
1146                   " over the last %d secs\n", octets * 8, octets, secs);
1147 
1148   return 0;
1149 }
1150 
1151 static const char *
1152 optval(struct bundle *bundle, int bit)
1153 {
1154   return (bundle->cfg.opt & bit) ? "enabled" : "disabled";
1155 }
1156 
1157 int
1158 bundle_ShowStatus(struct cmdargs const *arg)
1159 {
1160   int remaining;
1161 
1162   prompt_Printf(arg->prompt, "Phase %s\n", bundle_PhaseName(arg->bundle));
1163   prompt_Printf(arg->prompt, " Device:        %s\n", arg->bundle->dev.Name);
1164   prompt_Printf(arg->prompt, " Interface:     %s @ %lubps",
1165                 arg->bundle->iface->name, arg->bundle->bandwidth);
1166 
1167   if (arg->bundle->upat) {
1168     int secs = time(NULL) - arg->bundle->upat;
1169 
1170     prompt_Printf(arg->prompt, ", up time %d:%02d:%02d", secs / 3600,
1171                   (secs / 60) % 60, secs % 60);
1172   }
1173   prompt_Printf(arg->prompt, "\n Queued:        %lu of %u\n",
1174                 (unsigned long)ip_QueueLen(&arg->bundle->ncp.ipcp),
1175                 arg->bundle->cfg.ifqueue);
1176 
1177   prompt_Printf(arg->prompt, "\nDefaults:\n");
1178   prompt_Printf(arg->prompt, " Label:         %s\n", arg->bundle->cfg.label);
1179   prompt_Printf(arg->prompt, " Auth name:     %s\n",
1180                 arg->bundle->cfg.auth.name);
1181 
1182   prompt_Printf(arg->prompt, " Choked Timer:  %ds\n",
1183                 arg->bundle->cfg.choked.timeout);
1184 
1185 #ifndef NORADIUS
1186   radius_Show(&arg->bundle->radius, arg->prompt);
1187 #endif
1188 
1189   prompt_Printf(arg->prompt, " Idle Timer:    ");
1190   if (arg->bundle->cfg.idle.timeout) {
1191     prompt_Printf(arg->prompt, "%ds", arg->bundle->cfg.idle.timeout);
1192     if (arg->bundle->cfg.idle.min_timeout)
1193       prompt_Printf(arg->prompt, ", min %ds",
1194                     arg->bundle->cfg.idle.min_timeout);
1195     remaining = bundle_RemainingIdleTime(arg->bundle);
1196     if (remaining != -1)
1197       prompt_Printf(arg->prompt, " (%ds remaining)", remaining);
1198     prompt_Printf(arg->prompt, "\n");
1199   } else
1200     prompt_Printf(arg->prompt, "disabled\n");
1201   prompt_Printf(arg->prompt, " MTU:           ");
1202   if (arg->bundle->cfg.mtu)
1203     prompt_Printf(arg->prompt, "%d\n", arg->bundle->cfg.mtu);
1204   else
1205     prompt_Printf(arg->prompt, "unspecified\n");
1206 
1207   prompt_Printf(arg->prompt, " sendpipe:      ");
1208   if (arg->bundle->ncp.ipcp.cfg.sendpipe > 0)
1209     prompt_Printf(arg->prompt, "%-20ld", arg->bundle->ncp.ipcp.cfg.sendpipe);
1210   else
1211     prompt_Printf(arg->prompt, "unspecified         ");
1212   prompt_Printf(arg->prompt, " recvpipe:      ");
1213   if (arg->bundle->ncp.ipcp.cfg.recvpipe > 0)
1214     prompt_Printf(arg->prompt, "%ld\n", arg->bundle->ncp.ipcp.cfg.recvpipe);
1215   else
1216     prompt_Printf(arg->prompt, "unspecified\n");
1217 
1218   prompt_Printf(arg->prompt, " Sticky Routes: %-20.20s",
1219                 optval(arg->bundle, OPT_SROUTES));
1220   prompt_Printf(arg->prompt, " Filter Decap:  %s\n",
1221                 optval(arg->bundle, OPT_FILTERDECAP));
1222   prompt_Printf(arg->prompt, " ID check:      %-20.20s",
1223                 optval(arg->bundle, OPT_IDCHECK));
1224   prompt_Printf(arg->prompt, " Keep-Session:  %s\n",
1225                 optval(arg->bundle, OPT_KEEPSESSION));
1226   prompt_Printf(arg->prompt, " Loopback:      %-20.20s",
1227                 optval(arg->bundle, OPT_LOOPBACK));
1228   prompt_Printf(arg->prompt, " PasswdAuth:    %s\n",
1229                 optval(arg->bundle, OPT_PASSWDAUTH));
1230   prompt_Printf(arg->prompt, " Proxy:         %-20.20s",
1231                 optval(arg->bundle, OPT_PROXY));
1232   prompt_Printf(arg->prompt, " Proxyall:      %s\n",
1233                 optval(arg->bundle, OPT_PROXYALL));
1234   prompt_Printf(arg->prompt, " Throughput:    %-20.20s",
1235                 optval(arg->bundle, OPT_THROUGHPUT));
1236   prompt_Printf(arg->prompt, " Utmp Logging:  %s\n",
1237                 optval(arg->bundle, OPT_UTMP));
1238   prompt_Printf(arg->prompt, " Iface-Alias:   %s\n",
1239                 optval(arg->bundle, OPT_IFACEALIAS));
1240 
1241   return 0;
1242 }
1243 
1244 static void
1245 bundle_IdleTimeout(void *v)
1246 {
1247   struct bundle *bundle = (struct bundle *)v;
1248 
1249   log_Printf(LogPHASE, "Idle timer expired\n");
1250   bundle_StopIdleTimer(bundle);
1251   bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
1252 }
1253 
1254 /*
1255  *  Start Idle timer. If timeout is reached, we call bundle_Close() to
1256  *  close LCP and link.
1257  */
1258 void
1259 bundle_StartIdleTimer(struct bundle *bundle, unsigned secs)
1260 {
1261   timer_Stop(&bundle->idle.timer);
1262   if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) !=
1263       bundle->phys_type.open && bundle->cfg.idle.timeout) {
1264     time_t now = time(NULL);
1265 
1266     if (secs == 0)
1267       secs = bundle->cfg.idle.timeout;
1268 
1269     /* We want at least `secs' */
1270     if (bundle->cfg.idle.min_timeout > secs && bundle->upat) {
1271       int up = now - bundle->upat;
1272 
1273       if ((long long)bundle->cfg.idle.min_timeout - up > (long long)secs)
1274         /* Only increase from the current `remaining' value */
1275         secs = bundle->cfg.idle.min_timeout - up;
1276     }
1277     bundle->idle.timer.func = bundle_IdleTimeout;
1278     bundle->idle.timer.name = "idle";
1279     bundle->idle.timer.load = secs * SECTICKS;
1280     bundle->idle.timer.arg = bundle;
1281     timer_Start(&bundle->idle.timer);
1282     bundle->idle.done = now + secs;
1283   }
1284 }
1285 
1286 void
1287 bundle_SetIdleTimer(struct bundle *bundle, int timeout, int min_timeout)
1288 {
1289   bundle->cfg.idle.timeout = timeout;
1290   if (min_timeout >= 0)
1291     bundle->cfg.idle.min_timeout = min_timeout;
1292   if (bundle_LinkIsUp(bundle))
1293     bundle_StartIdleTimer(bundle, 0);
1294 }
1295 
1296 void
1297 bundle_StopIdleTimer(struct bundle *bundle)
1298 {
1299   timer_Stop(&bundle->idle.timer);
1300   bundle->idle.done = 0;
1301 }
1302 
1303 static int
1304 bundle_RemainingIdleTime(struct bundle *bundle)
1305 {
1306   if (bundle->idle.done)
1307     return bundle->idle.done - time(NULL);
1308   return -1;
1309 }
1310 
1311 int
1312 bundle_IsDead(struct bundle *bundle)
1313 {
1314   return !bundle->links || (bundle->phase == PHASE_DEAD && bundle->CleaningUp);
1315 }
1316 
1317 static struct datalink *
1318 bundle_DatalinkLinkout(struct bundle *bundle, struct datalink *dl)
1319 {
1320   struct datalink **dlp;
1321 
1322   for (dlp = &bundle->links; *dlp; dlp = &(*dlp)->next)
1323     if (*dlp == dl) {
1324       *dlp = dl->next;
1325       dl->next = NULL;
1326       bundle_LinksRemoved(bundle);
1327       return dl;
1328     }
1329 
1330   return NULL;
1331 }
1332 
1333 static void
1334 bundle_DatalinkLinkin(struct bundle *bundle, struct datalink *dl)
1335 {
1336   struct datalink **dlp = &bundle->links;
1337 
1338   while (*dlp)
1339     dlp = &(*dlp)->next;
1340 
1341   *dlp = dl;
1342   dl->next = NULL;
1343 
1344   bundle_LinkAdded(bundle, dl);
1345   mp_CheckAutoloadTimer(&bundle->ncp.mp);
1346 }
1347 
1348 void
1349 bundle_CleanDatalinks(struct bundle *bundle)
1350 {
1351   struct datalink **dlp = &bundle->links;
1352   int found = 0;
1353 
1354   while (*dlp)
1355     if ((*dlp)->state == DATALINK_CLOSED &&
1356         (*dlp)->physical->type &
1357         (PHYS_DIRECT|PHYS_BACKGROUND|PHYS_FOREGROUND)) {
1358       *dlp = datalink_Destroy(*dlp);
1359       found++;
1360     } else
1361       dlp = &(*dlp)->next;
1362 
1363   if (found)
1364     bundle_LinksRemoved(bundle);
1365 }
1366 
1367 int
1368 bundle_DatalinkClone(struct bundle *bundle, struct datalink *dl,
1369                      const char *name)
1370 {
1371   if (bundle2datalink(bundle, name)) {
1372     log_Printf(LogWARN, "Clone: %s: name already exists\n", name);
1373     return 0;
1374   }
1375 
1376   bundle_DatalinkLinkin(bundle, datalink_Clone(dl, name));
1377   return 1;
1378 }
1379 
1380 void
1381 bundle_DatalinkRemove(struct bundle *bundle, struct datalink *dl)
1382 {
1383   dl = bundle_DatalinkLinkout(bundle, dl);
1384   if (dl)
1385     datalink_Destroy(dl);
1386 }
1387 
1388 void
1389 bundle_SetLabel(struct bundle *bundle, const char *label)
1390 {
1391   if (label)
1392     strncpy(bundle->cfg.label, label, sizeof bundle->cfg.label - 1);
1393   else
1394     *bundle->cfg.label = '\0';
1395 }
1396 
1397 const char *
1398 bundle_GetLabel(struct bundle *bundle)
1399 {
1400   return *bundle->cfg.label ? bundle->cfg.label : NULL;
1401 }
1402 
1403 int
1404 bundle_LinkSize()
1405 {
1406   struct iovec iov[SCATTER_SEGMENTS];
1407   int niov, expect, f;
1408 
1409   iov[0].iov_len = strlen(Version) + 1;
1410   iov[0].iov_base = NULL;
1411   niov = 1;
1412   if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1413     log_Printf(LogERROR, "Cannot determine space required for link\n");
1414     return 0;
1415   }
1416 
1417   for (f = expect = 0; f < niov; f++)
1418     expect += iov[f].iov_len;
1419 
1420   return expect;
1421 }
1422 
1423 void
1424 bundle_ReceiveDatalink(struct bundle *bundle, int s)
1425 {
1426   char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int) * SEND_MAXFD];
1427   int niov, expect, f, *fd, nfd, onfd, got;
1428   struct iovec iov[SCATTER_SEGMENTS];
1429   struct cmsghdr *cmsg;
1430   struct msghdr msg;
1431   struct datalink *dl;
1432   pid_t pid;
1433 
1434   log_Printf(LogPHASE, "Receiving datalink\n");
1435 
1436   /*
1437    * Create our scatter/gather array - passing NULL gets the space
1438    * allocation requirement rather than actually flattening the
1439    * structures.
1440    */
1441   iov[0].iov_len = strlen(Version) + 1;
1442   iov[0].iov_base = NULL;
1443   niov = 1;
1444   if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1445     log_Printf(LogERROR, "Cannot determine space required for link\n");
1446     return;
1447   }
1448 
1449   /* Allocate the scatter/gather array for recvmsg() */
1450   for (f = expect = 0; f < niov; f++) {
1451     if ((iov[f].iov_base = malloc(iov[f].iov_len)) == NULL) {
1452       log_Printf(LogERROR, "Cannot allocate space to receive link\n");
1453       return;
1454     }
1455     if (f)
1456       expect += iov[f].iov_len;
1457   }
1458 
1459   /* Set up our message */
1460   cmsg = (struct cmsghdr *)cmsgbuf;
1461   cmsg->cmsg_len = sizeof cmsgbuf;
1462   cmsg->cmsg_level = SOL_SOCKET;
1463   cmsg->cmsg_type = 0;
1464 
1465   memset(&msg, '\0', sizeof msg);
1466   msg.msg_name = NULL;
1467   msg.msg_namelen = 0;
1468   msg.msg_iov = iov;
1469   msg.msg_iovlen = 1;		/* Only send the version at the first pass */
1470   msg.msg_control = cmsgbuf;
1471   msg.msg_controllen = sizeof cmsgbuf;
1472 
1473   log_Printf(LogDEBUG, "Expecting %u scatter/gather bytes\n",
1474              (unsigned)iov[0].iov_len);
1475 
1476   if ((got = recvmsg(s, &msg, MSG_WAITALL)) != iov[0].iov_len) {
1477     if (got == -1)
1478       log_Printf(LogERROR, "Failed recvmsg: %s\n", strerror(errno));
1479     else
1480       log_Printf(LogERROR, "Failed recvmsg: Got %d, not %u\n",
1481                  got, (unsigned)iov[0].iov_len);
1482     while (niov--)
1483       free(iov[niov].iov_base);
1484     return;
1485   }
1486 
1487   if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) {
1488     log_Printf(LogERROR, "Recvmsg: no descriptors received !\n");
1489     while (niov--)
1490       free(iov[niov].iov_base);
1491     return;
1492   }
1493 
1494   fd = (int *)(cmsg + 1);
1495   nfd = (cmsg->cmsg_len - sizeof *cmsg) / sizeof(int);
1496 
1497   if (nfd < 2) {
1498     log_Printf(LogERROR, "Recvmsg: %d descriptor%s received (too few) !\n",
1499                nfd, nfd == 1 ? "" : "s");
1500     while (nfd--)
1501       close(fd[nfd]);
1502     while (niov--)
1503       free(iov[niov].iov_base);
1504     return;
1505   }
1506 
1507   /*
1508    * We've successfully received two or more open file descriptors
1509    * through our socket, plus a version string.  Make sure it's the
1510    * correct version, and drop the connection if it's not.
1511    */
1512   if (strncmp(Version, iov[0].iov_base, iov[0].iov_len)) {
1513     log_Printf(LogWARN, "Cannot receive datalink, incorrect version"
1514                " (\"%.*s\", not \"%s\")\n", (int)iov[0].iov_len,
1515                (char *)iov[0].iov_base, Version);
1516     while (nfd--)
1517       close(fd[nfd]);
1518     while (niov--)
1519       free(iov[niov].iov_base);
1520     return;
1521   }
1522 
1523   /*
1524    * Everything looks good.  Send the other side our process id so that
1525    * they can transfer lock ownership, and wait for them to send the
1526    * actual link data.
1527    */
1528   pid = getpid();
1529   if ((got = write(fd[1], &pid, sizeof pid)) != sizeof pid) {
1530     if (got == -1)
1531       log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1532     else
1533       log_Printf(LogERROR, "Failed write: Got %d, not %d\n", got,
1534                  (int)(sizeof pid));
1535     while (nfd--)
1536       close(fd[nfd]);
1537     while (niov--)
1538       free(iov[niov].iov_base);
1539     return;
1540   }
1541 
1542   if ((got = readv(fd[1], iov + 1, niov - 1)) != expect) {
1543     if (got == -1)
1544       log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1545     else
1546       log_Printf(LogERROR, "Failed write: Got %d, not %d\n", got, expect);
1547     while (nfd--)
1548       close(fd[nfd]);
1549     while (niov--)
1550       free(iov[niov].iov_base);
1551     return;
1552   }
1553   close(fd[1]);
1554 
1555   onfd = nfd;	/* We've got this many in our array */
1556   nfd -= 2;	/* Don't include p->fd and our reply descriptor */
1557   niov = 1;	/* Skip the version id */
1558   dl = iov2datalink(bundle, iov, &niov, sizeof iov / sizeof *iov, fd[0],
1559                     fd + 2, &nfd);
1560   if (dl) {
1561 
1562     if (nfd) {
1563       log_Printf(LogERROR, "bundle_ReceiveDatalink: Failed to handle %d "
1564                  "auxiliary file descriptors (%d remain)\n", onfd, nfd);
1565       datalink_Destroy(dl);
1566       while (nfd--)
1567         close(fd[onfd--]);
1568       close(fd[0]);
1569     } else {
1570       bundle_DatalinkLinkin(bundle, dl);
1571       datalink_AuthOk(dl);
1572       bundle_CalculateBandwidth(dl->bundle);
1573     }
1574   } else {
1575     while (nfd--)
1576       close(fd[onfd--]);
1577     close(fd[0]);
1578     close(fd[1]);
1579   }
1580 
1581   free(iov[0].iov_base);
1582 }
1583 
1584 void
1585 bundle_SendDatalink(struct datalink *dl, int s, struct sockaddr_un *sun)
1586 {
1587   char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int) * SEND_MAXFD];
1588   const char *constlock;
1589   char *lock;
1590   struct cmsghdr *cmsg;
1591   struct msghdr msg;
1592   struct iovec iov[SCATTER_SEGMENTS];
1593   int niov, f, expect, newsid, fd[SEND_MAXFD], nfd, reply[2], got;
1594   pid_t newpid;
1595 
1596   log_Printf(LogPHASE, "Transmitting datalink %s\n", dl->name);
1597 
1598   /* Record the base device name for a lock transfer later */
1599   constlock = physical_LockedDevice(dl->physical);
1600   if (constlock) {
1601     lock = alloca(strlen(constlock) + 1);
1602     strcpy(lock, constlock);
1603   } else
1604     lock = NULL;
1605 
1606   bundle_LinkClosed(dl->bundle, dl);
1607   bundle_DatalinkLinkout(dl->bundle, dl);
1608 
1609   /* Build our scatter/gather array */
1610   iov[0].iov_len = strlen(Version) + 1;
1611   iov[0].iov_base = strdup(Version);
1612   niov = 1;
1613   nfd = 0;
1614 
1615   fd[0] = datalink2iov(dl, iov, &niov, SCATTER_SEGMENTS, fd + 2, &nfd);
1616 
1617   if (fd[0] != -1 && socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, reply) != -1) {
1618     /*
1619      * fd[1] is used to get the peer process id back, then to confirm that
1620      * we've transferred any device locks to that process id.
1621      */
1622     fd[1] = reply[1];
1623 
1624     nfd += 2;			/* Include fd[0] and fd[1] */
1625     memset(&msg, '\0', sizeof msg);
1626 
1627     msg.msg_name = NULL;
1628     msg.msg_namelen = 0;
1629     /*
1630      * Only send the version to start...  We used to send the whole lot, but
1631      * this caused problems with our RECVBUF size as a single link is about
1632      * 22k !  This way, we should bump into no limits.
1633      */
1634     msg.msg_iovlen = 1;
1635     msg.msg_iov = iov;
1636     msg.msg_control = cmsgbuf;
1637     msg.msg_controllen = sizeof *cmsg + sizeof(int) * nfd;
1638     msg.msg_flags = 0;
1639 
1640     cmsg = (struct cmsghdr *)cmsgbuf;
1641     cmsg->cmsg_len = msg.msg_controllen;
1642     cmsg->cmsg_level = SOL_SOCKET;
1643     cmsg->cmsg_type = SCM_RIGHTS;
1644 
1645     for (f = 0; f < nfd; f++)
1646       *((int *)(cmsg + 1) + f) = fd[f];
1647 
1648     for (f = 1, expect = 0; f < niov; f++)
1649       expect += iov[f].iov_len;
1650 
1651     if (setsockopt(reply[0], SOL_SOCKET, SO_SNDBUF, &expect, sizeof(int)) == -1)
1652       log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1653                  strerror(errno));
1654     if (setsockopt(reply[1], SOL_SOCKET, SO_RCVBUF, &expect, sizeof(int)) == -1)
1655       log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1656                  strerror(errno));
1657 
1658     log_Printf(LogDEBUG, "Sending %d descriptor%s and %u bytes in scatter"
1659                "/gather array\n", nfd, nfd == 1 ? "" : "s",
1660                (unsigned)iov[0].iov_len);
1661 
1662     if ((got = sendmsg(s, &msg, 0)) == -1)
1663       log_Printf(LogERROR, "Failed sendmsg: %s: %s\n",
1664                  sun->sun_path, strerror(errno));
1665     else if (got != iov[0].iov_len)
1666       log_Printf(LogERROR, "%s: Failed initial sendmsg: Only sent %d of %u\n",
1667                  sun->sun_path, got, (unsigned)iov[0].iov_len);
1668     else {
1669       /* We must get the ACK before closing the descriptor ! */
1670       int res;
1671 
1672       if ((got = read(reply[0], &newpid, sizeof newpid)) == sizeof newpid) {
1673         log_Printf(LogDEBUG, "Received confirmation from pid %d\n",
1674                    (int)newpid);
1675         if (lock && (res = ID0uu_lock_txfr(lock, newpid)) != UU_LOCK_OK)
1676             log_Printf(LogERROR, "uu_lock_txfr: %s\n", uu_lockerr(res));
1677 
1678         log_Printf(LogDEBUG, "Transmitting link (%d bytes)\n", expect);
1679         if ((got = writev(reply[0], iov + 1, niov - 1)) != expect) {
1680           if (got == -1)
1681             log_Printf(LogERROR, "%s: Failed writev: %s\n",
1682                        sun->sun_path, strerror(errno));
1683           else
1684             log_Printf(LogERROR, "%s: Failed writev: Wrote %d of %d\n",
1685                        sun->sun_path, got, expect);
1686         }
1687       } else if (got == -1)
1688         log_Printf(LogERROR, "%s: Failed socketpair read: %s\n",
1689                    sun->sun_path, strerror(errno));
1690       else
1691         log_Printf(LogERROR, "%s: Failed socketpair read: Got %d of %d\n",
1692                    sun->sun_path, got, (int)(sizeof newpid));
1693     }
1694 
1695     close(reply[0]);
1696     close(reply[1]);
1697 
1698     newsid = Enabled(dl->bundle, OPT_KEEPSESSION) ||
1699              tcgetpgrp(fd[0]) == getpgrp();
1700     while (nfd)
1701       close(fd[--nfd]);
1702     if (newsid)
1703       bundle_setsid(dl->bundle, got != -1);
1704   }
1705   close(s);
1706 
1707   while (niov--)
1708     free(iov[niov].iov_base);
1709 }
1710 
1711 int
1712 bundle_RenameDatalink(struct bundle *bundle, struct datalink *ndl,
1713                       const char *name)
1714 {
1715   struct datalink *dl;
1716 
1717   if (!strcasecmp(ndl->name, name))
1718     return 1;
1719 
1720   for (dl = bundle->links; dl; dl = dl->next)
1721     if (!strcasecmp(dl->name, name))
1722       return 0;
1723 
1724   datalink_Rename(ndl, name);
1725   return 1;
1726 }
1727 
1728 int
1729 bundle_SetMode(struct bundle *bundle, struct datalink *dl, int mode)
1730 {
1731   int omode;
1732 
1733   omode = dl->physical->type;
1734   if (omode == mode)
1735     return 1;
1736 
1737   if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO))
1738     /* First auto link */
1739     if (bundle->ncp.ipcp.peer_ip.s_addr == INADDR_ANY) {
1740       log_Printf(LogWARN, "You must `set ifaddr' or `open' before"
1741                  " changing mode to %s\n", mode2Nam(mode));
1742       return 0;
1743     }
1744 
1745   if (!datalink_SetMode(dl, mode))
1746     return 0;
1747 
1748   if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO) &&
1749       bundle->phase != PHASE_NETWORK)
1750     /* First auto link, we need an interface */
1751     ipcp_InterfaceUp(&bundle->ncp.ipcp);
1752 
1753   /* Regenerate phys_type and adjust idle timer */
1754   bundle_LinksRemoved(bundle);
1755 
1756   return 1;
1757 }
1758 
1759 void
1760 bundle_setsid(struct bundle *bundle, int holdsession)
1761 {
1762   /*
1763    * Lose the current session.  This means getting rid of our pid
1764    * too so that the tty device will really go away, and any getty
1765    * etc will be allowed to restart.
1766    */
1767   pid_t pid, orig;
1768   int fds[2];
1769   char done;
1770   struct datalink *dl;
1771 
1772   if (!holdsession && bundle_IsDead(bundle)) {
1773     /*
1774      * No need to lose our session after all... we're going away anyway
1775      *
1776      * We should really stop the timer and pause if holdsession is set and
1777      * the bundle's dead, but that leaves other resources lying about :-(
1778      */
1779     return;
1780   }
1781 
1782   orig = getpid();
1783   if (pipe(fds) == -1) {
1784     log_Printf(LogERROR, "pipe: %s\n", strerror(errno));
1785     return;
1786   }
1787   switch ((pid = fork())) {
1788     case -1:
1789       log_Printf(LogERROR, "fork: %s\n", strerror(errno));
1790       close(fds[0]);
1791       close(fds[1]);
1792       return;
1793     case 0:
1794       close(fds[1]);
1795       read(fds[0], &done, 1);		/* uu_locks are mine ! */
1796       close(fds[0]);
1797       if (pipe(fds) == -1) {
1798         log_Printf(LogERROR, "pipe(2): %s\n", strerror(errno));
1799         return;
1800       }
1801       switch ((pid = fork())) {
1802         case -1:
1803           log_Printf(LogERROR, "fork(2): %s\n", strerror(errno));
1804           close(fds[0]);
1805           close(fds[1]);
1806           return;
1807         case 0:
1808           close(fds[1]);
1809           bundle_LockTun(bundle);	/* update pid */
1810           read(fds[0], &done, 1);	/* uu_locks are mine ! */
1811           close(fds[0]);
1812           setsid();
1813           bundle_ChangedPID(bundle);
1814           log_Printf(LogDEBUG, "%d -> %d: %s session control\n",
1815                      (int)orig, (int)getpid(),
1816                      holdsession ? "Passed" : "Dropped");
1817           timer_InitService(0);		/* Start the Timer Service */
1818           break;
1819         default:
1820           close(fds[0]);
1821           /* Give away all our physical locks (to the final process) */
1822           for (dl = bundle->links; dl; dl = dl->next)
1823             if (dl->state != DATALINK_CLOSED)
1824               physical_ChangedPid(dl->physical, pid);
1825           write(fds[1], "!", 1);	/* done */
1826           close(fds[1]);
1827           _exit(0);
1828           break;
1829       }
1830       break;
1831     default:
1832       close(fds[0]);
1833       /* Give away all our physical locks (to the intermediate process) */
1834       for (dl = bundle->links; dl; dl = dl->next)
1835         if (dl->state != DATALINK_CLOSED)
1836           physical_ChangedPid(dl->physical, pid);
1837       write(fds[1], "!", 1);	/* done */
1838       close(fds[1]);
1839       if (holdsession) {
1840         int fd, status;
1841 
1842         timer_TermService();
1843         signal(SIGPIPE, SIG_DFL);
1844         signal(SIGALRM, SIG_DFL);
1845         signal(SIGHUP, SIG_DFL);
1846         signal(SIGTERM, SIG_DFL);
1847         signal(SIGINT, SIG_DFL);
1848         signal(SIGQUIT, SIG_DFL);
1849         for (fd = getdtablesize(); fd >= 0; fd--)
1850           close(fd);
1851         /*
1852          * Reap the intermediate process.  As we're not exiting but the
1853          * intermediate is, we don't want it to become defunct.
1854          */
1855         waitpid(pid, &status, 0);
1856         /* Tweak our process arguments.... */
1857         SetTitle("session owner");
1858 #ifndef NOSUID
1859         setuid(ID0realuid());
1860 #endif
1861         /*
1862          * Hang around for a HUP.  This should happen as soon as the
1863          * ppp that we passed our ctty descriptor to closes it.
1864          * NOTE: If this process dies, the passed descriptor becomes
1865          *       invalid and will give a select() error by setting one
1866          *       of the error fds, aborting the other ppp.  We don't
1867          *       want that to happen !
1868          */
1869         pause();
1870       }
1871       _exit(0);
1872       break;
1873   }
1874 }
1875 
1876 int
1877 bundle_HighestState(struct bundle *bundle)
1878 {
1879   struct datalink *dl;
1880   int result = DATALINK_CLOSED;
1881 
1882   for (dl = bundle->links; dl; dl = dl->next)
1883     if (result < dl->state)
1884       result = dl->state;
1885 
1886   return result;
1887 }
1888 
1889 int
1890 bundle_Exception(struct bundle *bundle, int fd)
1891 {
1892   struct datalink *dl;
1893 
1894   for (dl = bundle->links; dl; dl = dl->next)
1895     if (dl->physical->fd == fd) {
1896       datalink_Down(dl, CLOSE_NORMAL);
1897       return 1;
1898     }
1899 
1900   return 0;
1901 }
1902 
1903 void
1904 bundle_AdjustFilters(struct bundle *bundle, struct in_addr *my_ip,
1905                      struct in_addr *peer_ip)
1906 {
1907   filter_AdjustAddr(&bundle->filter.in, my_ip, peer_ip, NULL);
1908   filter_AdjustAddr(&bundle->filter.out, my_ip, peer_ip, NULL);
1909   filter_AdjustAddr(&bundle->filter.dial, my_ip, peer_ip, NULL);
1910   filter_AdjustAddr(&bundle->filter.alive, my_ip, peer_ip, NULL);
1911 }
1912 
1913 void
1914 bundle_AdjustDNS(struct bundle *bundle, struct in_addr dns[2])
1915 {
1916   filter_AdjustAddr(&bundle->filter.in, NULL, NULL, dns);
1917   filter_AdjustAddr(&bundle->filter.out, NULL, NULL, dns);
1918   filter_AdjustAddr(&bundle->filter.dial, NULL, NULL, dns);
1919   filter_AdjustAddr(&bundle->filter.alive, NULL, NULL, dns);
1920 }
1921 
1922 void
1923 bundle_CalculateBandwidth(struct bundle *bundle)
1924 {
1925   struct datalink *dl;
1926   int mtu, sp;
1927 
1928   bundle->bandwidth = 0;
1929   mtu = 0;
1930   for (dl = bundle->links; dl; dl = dl->next)
1931     if (dl->state == DATALINK_OPEN) {
1932       if ((sp = dl->mp.bandwidth) == 0 &&
1933           (sp = physical_GetSpeed(dl->physical)) == 0)
1934         log_Printf(LogDEBUG, "%s: %s: Cannot determine bandwidth\n",
1935                    dl->name, dl->physical->name.full);
1936       else
1937         bundle->bandwidth += sp;
1938       if (!bundle->ncp.mp.active) {
1939         mtu = dl->physical->link.lcp.his_mru;
1940         break;
1941       }
1942     }
1943 
1944   if(bundle->bandwidth == 0)
1945     bundle->bandwidth = 115200;		/* Shrug */
1946 
1947   if (bundle->ncp.mp.active)
1948     mtu = bundle->ncp.mp.peer_mrru;
1949   else if (!mtu)
1950     mtu = 1500;
1951 
1952 #ifndef NORADIUS
1953   if (bundle->radius.valid && bundle->radius.mtu && bundle->radius.mtu < mtu) {
1954     log_Printf(LogLCP, "Reducing MTU to radius value %lu\n",
1955                bundle->radius.mtu);
1956     mtu = bundle->radius.mtu;
1957   }
1958 #endif
1959 
1960   tun_configure(bundle, mtu);
1961 }
1962 
1963 void
1964 bundle_AutoAdjust(struct bundle *bundle, int percent, int what)
1965 {
1966   struct datalink *dl, *choice, *otherlinkup;
1967 
1968   choice = otherlinkup = NULL;
1969   for (dl = bundle->links; dl; dl = dl->next)
1970     if (dl->physical->type == PHYS_AUTO) {
1971       if (dl->state == DATALINK_OPEN) {
1972         if (what == AUTO_DOWN) {
1973           if (choice)
1974             otherlinkup = choice;
1975           choice = dl;
1976         }
1977       } else if (dl->state == DATALINK_CLOSED) {
1978         if (what == AUTO_UP) {
1979           choice = dl;
1980           break;
1981         }
1982       } else {
1983         /* An auto link in an intermediate state - forget it for the moment */
1984         choice = NULL;
1985         break;
1986       }
1987     } else if (dl->state == DATALINK_OPEN && what == AUTO_DOWN)
1988       otherlinkup = dl;
1989 
1990   if (choice) {
1991     if (what == AUTO_UP) {
1992       log_Printf(LogPHASE, "%d%% saturation -> Opening link ``%s''\n",
1993                  percent, choice->name);
1994       datalink_Up(choice, 1, 1);
1995       mp_CheckAutoloadTimer(&bundle->ncp.mp);
1996     } else if (otherlinkup) {	/* Only bring the second-last link down */
1997       log_Printf(LogPHASE, "%d%% saturation -> Closing link ``%s''\n",
1998                  percent, choice->name);
1999       datalink_Close(choice, CLOSE_STAYDOWN);
2000       mp_CheckAutoloadTimer(&bundle->ncp.mp);
2001     }
2002   }
2003 }
2004 
2005 int
2006 bundle_WantAutoloadTimer(struct bundle *bundle)
2007 {
2008   struct datalink *dl;
2009   int autolink, opened;
2010 
2011   if (bundle->phase == PHASE_NETWORK) {
2012     for (autolink = opened = 0, dl = bundle->links; dl; dl = dl->next)
2013       if (dl->physical->type == PHYS_AUTO) {
2014         if (++autolink == 2 || (autolink == 1 && opened))
2015           /* Two auto links or one auto and one open in NETWORK phase */
2016           return 1;
2017       } else if (dl->state == DATALINK_OPEN) {
2018         opened++;
2019         if (autolink)
2020           /* One auto and one open link in NETWORK phase */
2021           return 1;
2022       }
2023   }
2024 
2025   return 0;
2026 }
2027 
2028 void
2029 bundle_ChangedPID(struct bundle *bundle)
2030 {
2031 #ifdef TUNSIFPID
2032   ioctl(bundle->dev.fd, TUNSIFPID, 0);
2033 #endif
2034 }
2035