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