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