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