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