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