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