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