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