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