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