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