bundle.c revision 85991
134192Sjdp/*-
234192Sjdp * Copyright (c) 1998 Brian Somers <brian@Awfulhak.org>
334192Sjdp * All rights reserved.
434192Sjdp *
534192Sjdp * Redistribution and use in source and binary forms, with or without
634192Sjdp * modification, are permitted provided that the following conditions
734192Sjdp * are met:
834192Sjdp * 1. Redistributions of source code must retain the above copyright
934192Sjdp *    notice, this list of conditions and the following disclaimer.
1034192Sjdp * 2. Redistributions in binary form must reproduce the above copyright
1134192Sjdp *    notice, this list of conditions and the following disclaimer in the
1234192Sjdp *    documentation and/or other materials provided with the distribution.
1334192Sjdp *
1434192Sjdp * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1534192Sjdp * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1634192Sjdp * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1734192Sjdp * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
1834192Sjdp * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1934192Sjdp * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2034192Sjdp * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2134192Sjdp * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2234192Sjdp * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2334192Sjdp * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2434192Sjdp * SUCH DAMAGE.
2534192Sjdp *
2634192Sjdp * $FreeBSD: head/usr.sbin/ppp/bundle.c 85991 2001-11-03 21:45:32Z brian $
2734192Sjdp */
2834192Sjdp
2934192Sjdp#include <sys/param.h>
3034192Sjdp#include <sys/socket.h>
3134192Sjdp#include <netinet/in.h>
3234192Sjdp#include <net/if.h>
3334192Sjdp#include <net/if_tun.h>		/* For TUNS* ioctls */
3434192Sjdp#include <net/route.h>
3534192Sjdp#include <netinet/in_systm.h>
3650476Speter#include <netinet/ip.h>
3734192Sjdp#include <sys/un.h>
3834192Sjdp
3934192Sjdp#include <errno.h>
4034192Sjdp#include <fcntl.h>
4134192Sjdp#ifdef __OpenBSD__
4234192Sjdp#include <util.h>
4334192Sjdp#else
4434192Sjdp#include <libutil.h>
4534192Sjdp#endif
4634192Sjdp#include <paths.h>
4734192Sjdp#include <stdio.h>
4834192Sjdp#include <stdlib.h>
4934192Sjdp#include <string.h>
5034192Sjdp#include <sys/uio.h>
5134192Sjdp#include <sys/wait.h>
5269793Sobrien#if defined(__FreeBSD__) && !defined(NOKLDLOAD)
53110803Skan#ifdef NOSUID
54119255Simp#include <sys/linker.h>
55110803Skan#endif
5634192Sjdp#include <sys/module.h>
5734192Sjdp#endif
5834192Sjdp#include <termios.h>
5934192Sjdp#include <unistd.h>
6034192Sjdp
6134192Sjdp#include "layer.h"
6234192Sjdp#include "defs.h"
6334192Sjdp#include "command.h"
6434192Sjdp#include "mbuf.h"
6534192Sjdp#include "log.h"
6634192Sjdp#include "id.h"
6734192Sjdp#include "timer.h"
6834192Sjdp#include "fsm.h"
6934192Sjdp#include "iplist.h"
7034192Sjdp#include "lqr.h"
7134192Sjdp#include "hdlc.h"
7234192Sjdp#include "throughput.h"
7334192Sjdp#include "slcompress.h"
7434192Sjdp#include "ncpaddr.h"
7534192Sjdp#include "ip.h"
7634192Sjdp#include "ipcp.h"
7734192Sjdp#include "filter.h"
7834192Sjdp#include "descriptor.h"
7934192Sjdp#include "route.h"
8034192Sjdp#include "lcp.h"
8134192Sjdp#include "ccp.h"
8234192Sjdp#include "link.h"
8334192Sjdp#include "mp.h"
8434192Sjdp#ifndef NORADIUS
8534192Sjdp#include "radius.h"
8634192Sjdp#endif
8734192Sjdp#include "ipv6cp.h"
8834192Sjdp#include "ncp.h"
8934192Sjdp#include "bundle.h"
9034192Sjdp#include "async.h"
9134192Sjdp#include "physical.h"
9234192Sjdp#include "auth.h"
9334192Sjdp#include "proto.h"
9434192Sjdp#include "chap.h"
9534192Sjdp#include "tun.h"
9634192Sjdp#include "prompt.h"
9734192Sjdp#include "chat.h"
9834192Sjdp#include "cbcp.h"
9934192Sjdp#include "datalink.h"
10034192Sjdp#include "iface.h"
10134192Sjdp#include "server.h"
10234192Sjdp#include "probe.h"
10334192Sjdp#ifdef HAVE_DES
10434192Sjdp#include "mppe.h"
10534192Sjdp#endif
10634192Sjdp
10734192Sjdp#define SCATTER_SEGMENTS 7  /* version, datalink, name, physical,
10834192Sjdp                               throughput, throughput, device       */
10934192Sjdp
11034192Sjdp#define SEND_MAXFD 3        /* Max file descriptors passed through
11134192Sjdp                               the local domain socket              */
11234192Sjdp
11334192Sjdpstatic int bundle_RemainingIdleTime(struct bundle *);
11434192Sjdp
11534192Sjdpstatic const char * const PhaseNames[] = {
11634192Sjdp  "Dead", "Establish", "Authenticate", "Network", "Terminate"
11734192Sjdp};
11834192Sjdp
11934192Sjdpconst char *
12034192Sjdpbundle_PhaseName(struct bundle *bundle)
12134192Sjdp{
12234192Sjdp  return bundle->phase <= PHASE_TERMINATE ?
12334192Sjdp    PhaseNames[bundle->phase] : "unknown";
12434192Sjdp}
12534192Sjdp
12634192Sjdpvoid
12734192Sjdpbundle_NewPhase(struct bundle *bundle, u_int new)
12834192Sjdp{
12934192Sjdp  if (new == bundle->phase)
13034192Sjdp    return;
13134192Sjdp
13234192Sjdp  if (new <= PHASE_TERMINATE)
13334192Sjdp    log_Printf(LogPHASE, "bundle: %s\n", PhaseNames[new]);
13434192Sjdp
13534192Sjdp  switch (new) {
13634192Sjdp  case PHASE_DEAD:
13734192Sjdp    bundle->phase = new;
13834192Sjdp#ifdef HAVE_DES
13934192Sjdp    MPPE_MasterKeyValid = 0;
14034192Sjdp#endif
14134192Sjdp    log_DisplayPrompts();
14234192Sjdp    break;
14334192Sjdp
14434192Sjdp  case PHASE_ESTABLISH:
14534192Sjdp    bundle->phase = new;
14634192Sjdp    break;
14734192Sjdp
14834192Sjdp  case PHASE_AUTHENTICATE:
14934192Sjdp    bundle->phase = new;
15034192Sjdp    log_DisplayPrompts();
15134192Sjdp    break;
152110801Skan
15334192Sjdp  case PHASE_NETWORK:
15434192Sjdp    if (ncp_fsmStart(&bundle->ncp, bundle)) {
15534192Sjdp      bundle->phase = new;
15634192Sjdp      log_DisplayPrompts();
15734192Sjdp    } else {
15834192Sjdp      log_Printf(LogPHASE, "bundle: All NCPs are disabled\n");
15934192Sjdp      bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
16038816Sdfr    }
16138816Sdfr    break;
16234192Sjdp
16334192Sjdp  case PHASE_TERMINATE:
16434192Sjdp    bundle->phase = new;
16534192Sjdp    mp_Down(&bundle->ncp.mp);
16634192Sjdp    log_DisplayPrompts();
16734192Sjdp    break;
16834192Sjdp  }
16934192Sjdp}
17034192Sjdp
17134192Sjdpstatic void
17234192Sjdpbundle_LayerStart(void *v, struct fsm *fp)
17338816Sdfr{
17434192Sjdp  /* The given FSM is about to start up ! */
17534192Sjdp}
17634192Sjdp
17734192Sjdp
17834192Sjdpvoid
17934192Sjdpbundle_Notify(struct bundle *bundle, char c)
18034192Sjdp{
181114625Sobrien  if (bundle->notify.fd != -1) {
18234192Sjdp    int ret;
18334192Sjdp
18434192Sjdp    ret = write(bundle->notify.fd, &c, 1);
18534192Sjdp    if (c != EX_REDIAL && c != EX_RECONNECT) {
18634192Sjdp      if (ret == 1)
18734192Sjdp        log_Printf(LogCHAT, "Parent notified of %s\n",
18834192Sjdp                   c == EX_NORMAL ? "success" : "failure");
18934192Sjdp      else
19034192Sjdp        log_Printf(LogERROR, "Failed to notify parent of success\n");
19134192Sjdp      close(bundle->notify.fd);
192114625Sobrien      bundle->notify.fd = -1;
19334192Sjdp    } else if (ret == 1)
19434192Sjdp      log_Printf(LogCHAT, "Parent notified of %s\n", ex_desc(c));
19534192Sjdp    else
19634192Sjdp      log_Printf(LogERROR, "Failed to notify parent of %s\n", ex_desc(c));
19734192Sjdp  }
19834192Sjdp}
19934192Sjdp
20034192Sjdpstatic void
20134192Sjdpbundle_ClearQueues(void *v)
20234192Sjdp{
20334192Sjdp  struct bundle *bundle = (struct bundle *)v;
20434192Sjdp  struct datalink *dl;
20534192Sjdp
20634192Sjdp  log_Printf(LogPHASE, "Clearing choked output queue\n");
20734192Sjdp  timer_Stop(&bundle->choked.timer);
20834192Sjdp
20934192Sjdp  /*
21034192Sjdp   * Emergency time:
21134192Sjdp   *
21234192Sjdp   * We've had a full queue for PACKET_DEL_SECS seconds without being
21334192Sjdp   * able to get rid of any of the packets.  We've probably given up
21434192Sjdp   * on the redials at this point, and the queued data has almost
21534192Sjdp   * definitely been timed out by the layer above.  As this is preventing
21634192Sjdp   * us from reading the TUN_NAME device (we don't want to buffer stuff
21734192Sjdp   * indefinitely), we may as well nuke this data and start with a clean
21834192Sjdp   * slate !
21934192Sjdp   *
22034192Sjdp   * Unfortunately, this has the side effect of shafting any compression
22134192Sjdp   * dictionaries in use (causing the relevant RESET_REQ/RESET_ACK).
22234192Sjdp   */
22334192Sjdp
22434192Sjdp  ncp_DeleteQueues(&bundle->ncp);
22534192Sjdp  for (dl = bundle->links; dl; dl = dl->next)
22634192Sjdp    physical_DeleteQueue(dl->physical);
22734192Sjdp}
22834192Sjdp
22934192Sjdpstatic void
23034192Sjdpbundle_LinkAdded(struct bundle *bundle, struct datalink *dl)
23134192Sjdp{
23234192Sjdp  bundle->phys_type.all |= dl->physical->type;
23334192Sjdp  if (dl->state == DATALINK_OPEN)
23434192Sjdp    bundle->phys_type.open |= dl->physical->type;
23534192Sjdp
23634192Sjdp  if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
23734192Sjdp      != bundle->phys_type.open && bundle->idle.timer.state == TIMER_STOPPED)
23834192Sjdp    /* We may need to start our idle timer */
23934192Sjdp    bundle_StartIdleTimer(bundle, 0);
24034192Sjdp}
24134192Sjdp
24234192Sjdpvoid
24334192Sjdpbundle_LinksRemoved(struct bundle *bundle)
24434192Sjdp{
24534192Sjdp  struct datalink *dl;
24634192Sjdp
24734192Sjdp  bundle->phys_type.all = bundle->phys_type.open = 0;
24834192Sjdp  for (dl = bundle->links; dl; dl = dl->next)
24934192Sjdp    bundle_LinkAdded(bundle, dl);
25034192Sjdp
25134192Sjdp  bundle_CalculateBandwidth(bundle);
25234192Sjdp  mp_CheckAutoloadTimer(&bundle->ncp.mp);
25334192Sjdp
25434192Sjdp  if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
25534192Sjdp      == bundle->phys_type.open)
25634192Sjdp    bundle_StopIdleTimer(bundle);
25734192Sjdp}
25834192Sjdp
25934192Sjdpstatic void
26034192Sjdpbundle_LayerUp(void *v, struct fsm *fp)
26134192Sjdp{
26234192Sjdp  /*
26334192Sjdp   * The given fsm is now up
26434192Sjdp   * If it's an LCP, adjust our phys_mode.open value and check the
26534192Sjdp   * autoload timer.
26634192Sjdp   * If it's the first NCP, calculate our bandwidth
26734192Sjdp   * If it's the first NCP, set our ``upat'' time
26834192Sjdp   * If it's the first NCP, start the idle timer.
26934192Sjdp   * If it's an NCP, tell our -background parent to go away.
27034192Sjdp   * If it's the first NCP, start the autoload timer
27134192Sjdp   */
27234192Sjdp  struct bundle *bundle = (struct bundle *)v;
27334192Sjdp
27434192Sjdp  if (fp->proto == PROTO_LCP) {
27534192Sjdp    struct physical *p = link2physical(fp->link);
27634192Sjdp
27734192Sjdp    bundle_LinkAdded(bundle, p->dl);
27834192Sjdp    mp_CheckAutoloadTimer(&bundle->ncp.mp);
27934192Sjdp  } else if (isncp(fp->proto)) {
28034192Sjdp    if (ncp_LayersOpen(&fp->bundle->ncp) == 1) {
28134192Sjdp      bundle_CalculateBandwidth(fp->bundle);
28234192Sjdp      time(&bundle->upat);
28334192Sjdp      bundle_StartIdleTimer(bundle, 0);
28434192Sjdp      mp_CheckAutoloadTimer(&fp->bundle->ncp.mp);
28534192Sjdp    }
28634192Sjdp    bundle_Notify(bundle, EX_NORMAL);
28734192Sjdp  } else if (fp->proto == PROTO_CCP)
28834192Sjdp    bundle_CalculateBandwidth(fp->bundle);	/* Against ccp_MTUOverhead */
28934192Sjdp}
29034192Sjdp
29134192Sjdpstatic void
29234192Sjdpbundle_LayerDown(void *v, struct fsm *fp)
29334192Sjdp{
29434192Sjdp  /*
29534192Sjdp   * The given FSM has been told to come down.
29634192Sjdp   * If it's our last NCP, stop the idle timer.
29734192Sjdp   * If it's our last NCP, clear our ``upat'' value.
29834192Sjdp   * If it's our last NCP, stop the autoload timer
29934192Sjdp   * If it's an LCP, adjust our phys_type.open value and any timers.
30034192Sjdp   * If it's an LCP and we're in multilink mode, adjust our tun
30134192Sjdp   * If it's the last LCP, down all NCPs
30234192Sjdp   * speed and make sure our minimum sequence number is adjusted.
30334192Sjdp   */
30434192Sjdp
30534192Sjdp  struct bundle *bundle = (struct bundle *)v;
30634192Sjdp
30734192Sjdp  if (isncp(fp->proto)) {
30834192Sjdp    if (ncp_LayersOpen(&fp->bundle->ncp) == 0) {
30934192Sjdp      bundle_StopIdleTimer(bundle);
31034192Sjdp      bundle->upat = 0;
31134192Sjdp      mp_StopAutoloadTimer(&bundle->ncp.mp);
31234192Sjdp    }
31334192Sjdp  } else if (fp->proto == PROTO_LCP) {
31434192Sjdp    struct datalink *dl;
31534192Sjdp    struct datalink *lost;
31634192Sjdp    int others_active;
31734192Sjdp
31834192Sjdp    bundle_LinksRemoved(bundle);  /* adjust timers & phys_type values */
31934192Sjdp
32034192Sjdp    lost = NULL;
32134192Sjdp    others_active = 0;
32234192Sjdp    for (dl = bundle->links; dl; dl = dl->next) {
32334192Sjdp      if (fp == &dl->physical->link.lcp.fsm)
32434192Sjdp        lost = dl;
32534192Sjdp      else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
32634192Sjdp        others_active++;
32734192Sjdp    }
32834192Sjdp
32934192Sjdp    if (bundle->ncp.mp.active) {
33034192Sjdp      bundle_CalculateBandwidth(bundle);
33134192Sjdp
33234192Sjdp      if (lost)
33334192Sjdp        mp_LinkLost(&bundle->ncp.mp, lost);
33434192Sjdp      else
33534192Sjdp        log_Printf(LogALERT, "Oops, lost an unrecognised datalink (%s) !\n",
33634192Sjdp                   fp->link->name);
33734192Sjdp    }
33834192Sjdp
33934192Sjdp    if (!others_active)
34034192Sjdp      /* Down the NCPs.  We don't expect to get fsm_Close()d ourself ! */
34134192Sjdp      ncp2initial(&bundle->ncp);
34234192Sjdp  }
34334192Sjdp}
34434192Sjdp
34534192Sjdpstatic void
34634192Sjdpbundle_LayerFinish(void *v, struct fsm *fp)
34734192Sjdp{
34834192Sjdp  /* The given fsm is now down (fp cannot be NULL)
34934192Sjdp   *
35034192Sjdp   * If it's the last NCP, fsm_Close all LCPs
35134192Sjdp   */
35234192Sjdp
35334192Sjdp  struct bundle *bundle = (struct bundle *)v;
35434192Sjdp  struct datalink *dl;
35534192Sjdp
35634192Sjdp  if (isncp(fp->proto) && !ncp_LayersUnfinished(&bundle->ncp)) {
35734192Sjdp    if (bundle_Phase(bundle) != PHASE_DEAD)
35834192Sjdp      bundle_NewPhase(bundle, PHASE_TERMINATE);
35934192Sjdp    for (dl = bundle->links; dl; dl = dl->next)
36034192Sjdp      if (dl->state == DATALINK_OPEN)
36134192Sjdp        datalink_Close(dl, CLOSE_STAYDOWN);
36234192Sjdp    fsm2initial(fp);
36334192Sjdp  }
36434192Sjdp}
365114625Sobrien
36634192Sjdpvoid
36734192Sjdpbundle_Close(struct bundle *bundle, const char *name, int how)
36834192Sjdp{
36934192Sjdp  /*
37034192Sjdp   * Please close the given datalink.
37134192Sjdp   * If name == NULL or name is the last datalink, fsm_Close all NCPs
37234192Sjdp   * (except our MP)
37334192Sjdp   * If it isn't the last datalink, just Close that datalink.
37434192Sjdp   */
37534192Sjdp
37634192Sjdp  struct datalink *dl, *this_dl;
37734192Sjdp  int others_active;
378114625Sobrien
37934192Sjdp  others_active = 0;
38034192Sjdp  this_dl = NULL;
38134192Sjdp
38234192Sjdp  for (dl = bundle->links; dl; dl = dl->next) {
38334192Sjdp    if (name && !strcasecmp(name, dl->name))
38434192Sjdp      this_dl = dl;
38534192Sjdp    if (name == NULL || this_dl == dl) {
38634192Sjdp      switch (how) {
38734192Sjdp        case CLOSE_LCP:
38834192Sjdp          datalink_DontHangup(dl);
38934192Sjdp          break;
39034192Sjdp        case CLOSE_STAYDOWN:
39134192Sjdp          datalink_StayDown(dl);
39234192Sjdp          break;
39334192Sjdp      }
39434192Sjdp    } else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
39534192Sjdp      others_active++;
39634192Sjdp  }
39734192Sjdp
39834192Sjdp  if (name && this_dl == NULL) {
39934192Sjdp    log_Printf(LogWARN, "%s: Invalid datalink name\n", name);
40034192Sjdp    return;
40134192Sjdp  }
40234192Sjdp
40334192Sjdp  if (!others_active) {
40434192Sjdp    bundle_StopIdleTimer(bundle);
40534192Sjdp    if (ncp_LayersUnfinished(&bundle->ncp))
40634192Sjdp      ncp_Close(&bundle->ncp);
40734192Sjdp    else {
40834192Sjdp      ncp2initial(&bundle->ncp);
40934192Sjdp      for (dl = bundle->links; dl; dl = dl->next)
41034192Sjdp        datalink_Close(dl, how);
41134192Sjdp    }
41234192Sjdp  } else if (this_dl && this_dl->state != DATALINK_CLOSED &&
41334192Sjdp             this_dl->state != DATALINK_HANGUP)
41434192Sjdp    datalink_Close(this_dl, how);
41534192Sjdp}
41634192Sjdp
41734192Sjdpvoid
41834192Sjdpbundle_Down(struct bundle *bundle, int how)
41934192Sjdp{
42034192Sjdp  struct datalink *dl;
42134192Sjdp
42234192Sjdp  for (dl = bundle->links; dl; dl = dl->next)
42334192Sjdp    datalink_Down(dl, how);
42434192Sjdp}
42534192Sjdp
42634192Sjdpstatic int
42734192Sjdpbundle_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
42834192Sjdp{
42934192Sjdp  struct bundle *bundle = descriptor2bundle(d);
43034192Sjdp  struct datalink *dl;
43134192Sjdp  int result, nlinks;
43234192Sjdp  u_short ifqueue;
43334192Sjdp  size_t queued;
43434192Sjdp
43534192Sjdp  result = 0;
43634192Sjdp
43734192Sjdp  /* If there are aren't many packets queued, look for some more. */
43834192Sjdp  for (nlinks = 0, dl = bundle->links; dl; dl = dl->next)
43934192Sjdp    nlinks++;
44034192Sjdp
44134192Sjdp  if (nlinks) {
44234192Sjdp    queued = r ? ncp_FillPhysicalQueues(&bundle->ncp, bundle) :
44334192Sjdp                 ncp_QueueLen(&bundle->ncp);
44434192Sjdp
44534192Sjdp    if (r && (bundle->phase == PHASE_NETWORK ||
44634192Sjdp              bundle->phys_type.all & PHYS_AUTO)) {
44734192Sjdp      /* enough surplus so that we can tell if we're getting swamped */
44834192Sjdp      ifqueue = nlinks > bundle->cfg.ifqueue ? nlinks : bundle->cfg.ifqueue;
44934192Sjdp      if (queued < ifqueue) {
45034192Sjdp        /* Not enough - select() for more */
45134192Sjdp        if (bundle->choked.timer.state == TIMER_RUNNING)
45234192Sjdp          timer_Stop(&bundle->choked.timer);	/* Not needed any more */
45334192Sjdp        FD_SET(bundle->dev.fd, r);
45434192Sjdp        if (*n < bundle->dev.fd + 1)
45534192Sjdp          *n = bundle->dev.fd + 1;
45634192Sjdp        log_Printf(LogTIMER, "%s: fdset(r) %d\n", TUN_NAME, bundle->dev.fd);
45734192Sjdp        result++;
45834192Sjdp      } else if (bundle->choked.timer.state == TIMER_STOPPED) {
45934192Sjdp        bundle->choked.timer.func = bundle_ClearQueues;
46069793Sobrien        bundle->choked.timer.name = "output choke";
46134192Sjdp        bundle->choked.timer.load = bundle->cfg.choked.timeout * SECTICKS;
46269793Sobrien        bundle->choked.timer.arg = bundle;
46334192Sjdp        timer_Start(&bundle->choked.timer);
46434192Sjdp      }
46534192Sjdp    }
46634192Sjdp  }
46738816Sdfr
46834192Sjdp#ifndef NORADIUS
46934192Sjdp  result += descriptor_UpdateSet(&bundle->radius.desc, r, w, e, n);
47034192Sjdp#endif
47134192Sjdp
47238816Sdfr  /* Which links need a select() ? */
47334192Sjdp  for (dl = bundle->links; dl; dl = dl->next)
47434192Sjdp    result += descriptor_UpdateSet(&dl->desc, r, w, e, n);
47534192Sjdp
47634192Sjdp  /*
47734192Sjdp   * This *MUST* be called after the datalink UpdateSet()s as it
47834192Sjdp   * might be ``holding'' one of the datalinks (death-row) and
47934192Sjdp   * wants to be able to de-select() it from the descriptor set.
48034192Sjdp   */
48134192Sjdp  result += descriptor_UpdateSet(&bundle->ncp.mp.server.desc, r, w, e, n);
48234192Sjdp
48334192Sjdp  return result;
48434192Sjdp}
48534192Sjdp
48634192Sjdpstatic int
48734192Sjdpbundle_IsSet(struct fdescriptor *d, const fd_set *fdset)
488110801Skan{
489110801Skan  struct bundle *bundle = descriptor2bundle(d);
490110801Skan  struct datalink *dl;
491110801Skan
492110801Skan  for (dl = bundle->links; dl; dl = dl->next)
493110801Skan    if (descriptor_IsSet(&dl->desc, fdset))
494110801Skan      return 1;
495110801Skan
496110801Skan#ifndef NORADIUS
497110801Skan  if (descriptor_IsSet(&bundle->radius.desc, fdset))
498110801Skan    return 1;
499110801Skan#endif
500110801Skan
501110801Skan  if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
502110801Skan    return 1;
503
504  return FD_ISSET(bundle->dev.fd, fdset);
505}
506
507static void
508bundle_DescriptorRead(struct fdescriptor *d, struct bundle *bundle,
509                      const fd_set *fdset)
510{
511  struct datalink *dl;
512  unsigned secs;
513  u_int32_t af;
514
515  if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
516    descriptor_Read(&bundle->ncp.mp.server.desc, bundle, fdset);
517
518  for (dl = bundle->links; dl; dl = dl->next)
519    if (descriptor_IsSet(&dl->desc, fdset))
520      descriptor_Read(&dl->desc, bundle, fdset);
521
522#ifndef NORADIUS
523  if (descriptor_IsSet(&bundle->radius.desc, fdset))
524    descriptor_Read(&bundle->radius.desc, bundle, fdset);
525#endif
526
527  if (FD_ISSET(bundle->dev.fd, fdset)) {
528    struct tun_data tun;
529    int n, pri;
530    char *data;
531    size_t sz;
532
533    if (bundle->dev.header) {
534      data = (char *)&tun;
535      sz = sizeof tun;
536    } else {
537      data = tun.data;
538      sz = sizeof tun.data;
539    }
540
541    /* something to read from tun */
542
543    n = read(bundle->dev.fd, data, sz);
544    if (n < 0) {
545      log_Printf(LogWARN, "%s: read: %s\n", bundle->dev.Name, strerror(errno));
546      return;
547    }
548
549    if (bundle->dev.header) {
550      n -= sz - sizeof tun.data;
551      if (n <= 0) {
552        log_Printf(LogERROR, "%s: read: Got only %d bytes of data !\n",
553                   bundle->dev.Name, n);
554        return;
555      }
556      af = ntohl(tun.header.family);
557#ifndef NOINET6
558      if (af != AF_INET && af != AF_INET6)
559#else
560      if (af != AF_INET)
561#endif
562        /* XXX: Should be maintaining drop/family counts ! */
563        return;
564    } else
565      af = AF_INET;
566
567    if (af == AF_INET && ((struct ip *)tun.data)->ip_dst.s_addr ==
568        bundle->ncp.ipcp.my_ip.s_addr) {
569      /* we've been asked to send something addressed *to* us :( */
570      if (Enabled(bundle, OPT_LOOPBACK)) {
571        pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.in,
572                          NULL, NULL);
573        if (pri >= 0) {
574          n += sz - sizeof tun.data;
575          write(bundle->dev.fd, data, n);
576          log_Printf(LogDEBUG, "Looped back packet addressed to myself\n");
577        }
578        return;
579      } else
580        log_Printf(LogDEBUG, "Oops - forwarding packet addressed to myself\n");
581    }
582
583    /*
584     * Process on-demand dialup. Output packets are queued within the tunnel
585     * device until the appropriate NCP is opened.
586     */
587
588    if (bundle_Phase(bundle) == PHASE_DEAD) {
589      /*
590       * Note, we must be in AUTO mode :-/ otherwise our interface should
591       * *not* be UP and we can't receive data
592       */
593      pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.dial,
594                        NULL, NULL);
595      if (pri >= 0)
596        bundle_Open(bundle, NULL, PHYS_AUTO, 0);
597      else
598        /*
599         * Drop the packet.  If we were to queue it, we'd just end up with
600         * a pile of timed-out data in our output queue by the time we get
601         * around to actually dialing.  We'd also prematurely reach the
602         * threshold at which we stop select()ing to read() the tun
603         * device - breaking auto-dial.
604         */
605        return;
606    }
607
608    secs = 0;
609    pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.out,
610                      NULL, &secs);
611    if (pri >= 0) {
612      /* Prepend the number of seconds timeout given in the filter */
613      tun.header.timeout = secs;
614      ncp_Enqueue(&bundle->ncp, af, pri, (char *)&tun, n + sizeof tun.header);
615    }
616  }
617}
618
619static int
620bundle_DescriptorWrite(struct fdescriptor *d, struct bundle *bundle,
621                       const fd_set *fdset)
622{
623  struct datalink *dl;
624  int result = 0;
625
626  /* This is not actually necessary as struct mpserver doesn't Write() */
627  if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
628    descriptor_Write(&bundle->ncp.mp.server.desc, bundle, fdset);
629
630  for (dl = bundle->links; dl; dl = dl->next)
631    if (descriptor_IsSet(&dl->desc, fdset))
632      result += descriptor_Write(&dl->desc, bundle, fdset);
633
634  return result;
635}
636
637void
638bundle_LockTun(struct bundle *bundle)
639{
640  FILE *lockfile;
641  char pidfile[PATH_MAX];
642
643  snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
644  lockfile = ID0fopen(pidfile, "w");
645  if (lockfile != NULL) {
646    fprintf(lockfile, "%d\n", (int)getpid());
647    fclose(lockfile);
648  }
649#ifndef RELEASE_CRUNCH
650  else
651    log_Printf(LogERROR, "Warning: Can't create %s: %s\n",
652               pidfile, strerror(errno));
653#endif
654}
655
656static void
657bundle_UnlockTun(struct bundle *bundle)
658{
659  char pidfile[PATH_MAX];
660
661  snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
662  ID0unlink(pidfile);
663}
664
665struct bundle *
666bundle_Create(const char *prefix, int type, int unit)
667{
668  static struct bundle bundle;		/* there can be only one */
669  int enoentcount, err, minunit, maxunit;
670  const char *ifname;
671#if defined(__FreeBSD__) && !defined(NOKLDLOAD)
672  int kldtried;
673#endif
674#if defined(TUNSIFMODE) || defined(TUNSLMODE) || defined(TUNSIFHEAD)
675  int iff;
676#endif
677
678  if (bundle.iface != NULL) {	/* Already allocated ! */
679    log_Printf(LogALERT, "bundle_Create:  There's only one BUNDLE !\n");
680    return NULL;
681  }
682
683  if (unit == -1) {
684    minunit = 0;
685    maxunit = -1;
686  } else {
687    minunit = unit;
688    maxunit = unit + 1;
689  }
690  err = ENOENT;
691  enoentcount = 0;
692#if defined(__FreeBSD__) && !defined(NOKLDLOAD)
693  kldtried = 0;
694#endif
695  for (bundle.unit = minunit; bundle.unit != maxunit; bundle.unit++) {
696    snprintf(bundle.dev.Name, sizeof bundle.dev.Name, "%s%d",
697             prefix, bundle.unit);
698    bundle.dev.fd = ID0open(bundle.dev.Name, O_RDWR);
699    if (bundle.dev.fd >= 0)
700      break;
701    else if (errno == ENXIO || errno == ENOENT) {
702#if defined(__FreeBSD__) && !defined(NOKLDLOAD)
703      if (bundle.unit == minunit && !kldtried++) {
704        /*
705	 * Attempt to load the tunnel interface KLD if it isn't loaded
706	 * already.
707         */
708        if (modfind("if_tun") == -1) {
709          if (ID0kldload("if_tun") != -1) {
710            bundle.unit--;
711            continue;
712          }
713          log_Printf(LogWARN, "kldload: if_tun: %s\n", strerror(errno));
714        }
715      }
716#endif
717      if (errno != ENOENT || ++enoentcount > 2) {
718        err = errno;
719	break;
720      }
721    } else
722      err = errno;
723  }
724
725  if (bundle.dev.fd < 0) {
726    if (unit == -1)
727      log_Printf(LogWARN, "No available tunnel devices found (%s)\n",
728                strerror(err));
729    else
730      log_Printf(LogWARN, "%s%d: %s\n", prefix, unit, strerror(err));
731    return NULL;
732  }
733
734  log_SetTun(bundle.unit);
735
736  ifname = strrchr(bundle.dev.Name, '/');
737  if (ifname == NULL)
738    ifname = bundle.dev.Name;
739  else
740    ifname++;
741
742  bundle.iface = iface_Create(ifname);
743  if (bundle.iface == NULL) {
744    close(bundle.dev.fd);
745    return NULL;
746  }
747
748#ifdef TUNSIFMODE
749  /* Make sure we're POINTOPOINT & IFF_MULTICAST */
750  iff = IFF_POINTOPOINT | IFF_MULTICAST;
751  if (ID0ioctl(bundle.dev.fd, TUNSIFMODE, &iff) < 0)
752    log_Printf(LogERROR, "bundle_Create: ioctl(TUNSIFMODE): %s\n",
753	       strerror(errno));
754#endif
755
756#ifdef TUNSLMODE
757  /* Make sure we're not prepending sockaddrs */
758  iff = 0;
759  if (ID0ioctl(bundle.dev.fd, TUNSLMODE, &iff) < 0)
760    log_Printf(LogERROR, "bundle_Create: ioctl(TUNSLMODE): %s\n",
761	       strerror(errno));
762#endif
763
764#ifdef TUNSIFHEAD
765  /* We want the address family please ! */
766  iff = 1;
767  if (ID0ioctl(bundle.dev.fd, TUNSIFHEAD, &iff) < 0) {
768    log_Printf(LogERROR, "bundle_Create: ioctl(TUNSIFHEAD): %s\n",
769	       strerror(errno));
770    bundle.dev.header = 0;
771  } else
772    bundle.dev.header = 1;
773#else
774#ifdef __OpenBSD__
775  /* Always present for OpenBSD */
776  bundle.dev.header = 1;
777#else
778  /*
779   * If TUNSIFHEAD isn't available and we're not OpenBSD, assume
780   * everything's AF_INET (hopefully the tun device won't pass us
781   * anything else !).
782   */
783  bundle.dev.header = 0;
784#endif
785#endif
786
787  log_Printf(LogPHASE, "Using interface: %s\n", ifname);
788
789  bundle.bandwidth = 0;
790  bundle.routing_seq = 0;
791  bundle.phase = PHASE_DEAD;
792  bundle.CleaningUp = 0;
793  bundle.NatEnabled = 0;
794
795  bundle.fsm.LayerStart = bundle_LayerStart;
796  bundle.fsm.LayerUp = bundle_LayerUp;
797  bundle.fsm.LayerDown = bundle_LayerDown;
798  bundle.fsm.LayerFinish = bundle_LayerFinish;
799  bundle.fsm.object = &bundle;
800
801  bundle.cfg.idle.timeout = NCP_IDLE_TIMEOUT;
802  bundle.cfg.idle.min_timeout = 0;
803  *bundle.cfg.auth.name = '\0';
804  *bundle.cfg.auth.key = '\0';
805  bundle.cfg.opt = OPT_IDCHECK | OPT_LOOPBACK | OPT_SROUTES | OPT_TCPMSSFIXUP |
806                   OPT_THROUGHPUT | OPT_UTMP;
807#ifndef NOINET6
808  bundle.cfg.opt |= OPT_IPCP;
809  if (probe.ipv6_available)
810    bundle.cfg.opt |= OPT_IPV6CP;
811#endif
812  *bundle.cfg.label = '\0';
813  bundle.cfg.ifqueue = DEF_IFQUEUE;
814  bundle.cfg.choked.timeout = CHOKED_TIMEOUT;
815  bundle.phys_type.all = type;
816  bundle.phys_type.open = 0;
817  bundle.upat = 0;
818
819  bundle.links = datalink_Create("deflink", &bundle, type);
820  if (bundle.links == NULL) {
821    log_Printf(LogALERT, "Cannot create data link: %s\n", strerror(errno));
822    iface_Destroy(bundle.iface);
823    bundle.iface = NULL;
824    close(bundle.dev.fd);
825    return NULL;
826  }
827
828  bundle.desc.type = BUNDLE_DESCRIPTOR;
829  bundle.desc.UpdateSet = bundle_UpdateSet;
830  bundle.desc.IsSet = bundle_IsSet;
831  bundle.desc.Read = bundle_DescriptorRead;
832  bundle.desc.Write = bundle_DescriptorWrite;
833
834  ncp_Init(&bundle.ncp, &bundle);
835
836  memset(&bundle.filter, '\0', sizeof bundle.filter);
837  bundle.filter.in.fragok = bundle.filter.in.logok = 1;
838  bundle.filter.in.name = "IN";
839  bundle.filter.out.fragok = bundle.filter.out.logok = 1;
840  bundle.filter.out.name = "OUT";
841  bundle.filter.dial.name = "DIAL";
842  bundle.filter.dial.logok = 1;
843  bundle.filter.alive.name = "ALIVE";
844  bundle.filter.alive.logok = 1;
845  {
846    int	i;
847    for (i = 0; i < MAXFILTERS; i++) {
848        bundle.filter.in.rule[i].f_action = A_NONE;
849        bundle.filter.out.rule[i].f_action = A_NONE;
850        bundle.filter.dial.rule[i].f_action = A_NONE;
851        bundle.filter.alive.rule[i].f_action = A_NONE;
852    }
853  }
854  memset(&bundle.idle.timer, '\0', sizeof bundle.idle.timer);
855  bundle.idle.done = 0;
856  bundle.notify.fd = -1;
857  memset(&bundle.choked.timer, '\0', sizeof bundle.choked.timer);
858#ifndef NORADIUS
859  radius_Init(&bundle.radius);
860#endif
861
862  /* Clean out any leftover crud */
863  iface_Clear(bundle.iface, &bundle.ncp, 0, IFACE_CLEAR_ALL);
864
865  bundle_LockTun(&bundle);
866
867  return &bundle;
868}
869
870static void
871bundle_DownInterface(struct bundle *bundle)
872{
873  route_IfDelete(bundle, 1);
874  iface_ClearFlags(bundle->iface->name, IFF_UP);
875}
876
877void
878bundle_Destroy(struct bundle *bundle)
879{
880  struct datalink *dl;
881
882  /*
883   * Clean up the interface.  We don't really need to do the timer_Stop()s,
884   * mp_Down(), iface_Clear() and bundle_DownInterface() unless we're getting
885   * out under exceptional conditions such as a descriptor exception.
886   */
887  timer_Stop(&bundle->idle.timer);
888  timer_Stop(&bundle->choked.timer);
889  mp_Down(&bundle->ncp.mp);
890  iface_Clear(bundle->iface, &bundle->ncp, 0, IFACE_CLEAR_ALL);
891  bundle_DownInterface(bundle);
892
893#ifndef NORADIUS
894  /* Tell the radius server the bad news */
895  radius_Destroy(&bundle->radius);
896#endif
897
898  /* Again, these are all DATALINK_CLOSED unless we're abending */
899  dl = bundle->links;
900  while (dl)
901    dl = datalink_Destroy(dl);
902
903  ncp_Destroy(&bundle->ncp);
904
905  close(bundle->dev.fd);
906  bundle_UnlockTun(bundle);
907
908  /* In case we never made PHASE_NETWORK */
909  bundle_Notify(bundle, EX_ERRDEAD);
910
911  iface_Destroy(bundle->iface);
912  bundle->iface = NULL;
913}
914
915void
916bundle_LinkClosed(struct bundle *bundle, struct datalink *dl)
917{
918  /*
919   * Our datalink has closed.
920   * CleanDatalinks() (called from DoLoop()) will remove closed
921   * BACKGROUND, FOREGROUND and DIRECT links.
922   * If it's the last data link, enter phase DEAD.
923   *
924   * NOTE: dl may not be in our list (bundle_SendDatalink()) !
925   */
926
927  struct datalink *odl;
928  int other_links;
929
930  log_SetTtyCommandMode(dl);
931
932  other_links = 0;
933  for (odl = bundle->links; odl; odl = odl->next)
934    if (odl != dl && odl->state != DATALINK_CLOSED)
935      other_links++;
936
937  if (!other_links) {
938    if (dl->physical->type != PHYS_AUTO)	/* Not in -auto mode */
939      bundle_DownInterface(bundle);
940    ncp2initial(&bundle->ncp);
941    bundle_NewPhase(bundle, PHASE_DEAD);
942    bundle_StopIdleTimer(bundle);
943  }
944}
945
946void
947bundle_Open(struct bundle *bundle, const char *name, int mask, int force)
948{
949  /*
950   * Please open the given datalink, or all if name == NULL
951   */
952  struct datalink *dl;
953
954  for (dl = bundle->links; dl; dl = dl->next)
955    if (name == NULL || !strcasecmp(dl->name, name)) {
956      if ((mask & dl->physical->type) &&
957          (dl->state == DATALINK_CLOSED ||
958           (force && dl->state == DATALINK_OPENING &&
959            dl->dial.timer.state == TIMER_RUNNING) ||
960           dl->state == DATALINK_READY)) {
961        timer_Stop(&dl->dial.timer);	/* We're finished with this */
962        datalink_Up(dl, 1, 1);
963        if (mask & PHYS_AUTO)
964          break;			/* Only one AUTO link at a time */
965      }
966      if (name != NULL)
967        break;
968    }
969}
970
971struct datalink *
972bundle2datalink(struct bundle *bundle, const char *name)
973{
974  struct datalink *dl;
975
976  if (name != NULL) {
977    for (dl = bundle->links; dl; dl = dl->next)
978      if (!strcasecmp(dl->name, name))
979        return dl;
980  } else if (bundle->links && !bundle->links->next)
981    return bundle->links;
982
983  return NULL;
984}
985
986int
987bundle_ShowLinks(struct cmdargs const *arg)
988{
989  struct datalink *dl;
990  struct pppThroughput *t;
991  unsigned long long octets;
992  int secs;
993
994  for (dl = arg->bundle->links; dl; dl = dl->next) {
995    octets = MAX(dl->physical->link.stats.total.in.OctetsPerSecond,
996                 dl->physical->link.stats.total.out.OctetsPerSecond);
997
998    prompt_Printf(arg->prompt, "Name: %s [%s, %s]",
999                  dl->name, mode2Nam(dl->physical->type), datalink_State(dl));
1000    if (dl->physical->link.stats.total.rolling && dl->state == DATALINK_OPEN)
1001      prompt_Printf(arg->prompt, " bandwidth %d, %llu bps (%llu bytes/sec)",
1002                    dl->mp.bandwidth ? dl->mp.bandwidth :
1003                                       physical_GetSpeed(dl->physical),
1004                    octets * 8, octets);
1005    prompt_Printf(arg->prompt, "\n");
1006  }
1007
1008  t = &arg->bundle->ncp.mp.link.stats.total;
1009  octets = MAX(t->in.OctetsPerSecond, t->out.OctetsPerSecond);
1010  secs = t->downtime ? 0 : throughput_uptime(t);
1011  if (secs > t->SamplePeriod)
1012    secs = t->SamplePeriod;
1013  if (secs)
1014    prompt_Printf(arg->prompt, "Currently averaging %llu bps (%llu bytes/sec)"
1015                  " over the last %d secs\n", octets * 8, octets, secs);
1016
1017  return 0;
1018}
1019
1020static const char *
1021optval(struct bundle *bundle, int bit)
1022{
1023  return (bundle->cfg.opt & bit) ? "enabled" : "disabled";
1024}
1025
1026int
1027bundle_ShowStatus(struct cmdargs const *arg)
1028{
1029  int remaining;
1030
1031  prompt_Printf(arg->prompt, "Phase %s\n", bundle_PhaseName(arg->bundle));
1032  prompt_Printf(arg->prompt, " Device:        %s\n", arg->bundle->dev.Name);
1033  prompt_Printf(arg->prompt, " Interface:     %s @ %lubps",
1034                arg->bundle->iface->name, arg->bundle->bandwidth);
1035
1036  if (arg->bundle->upat) {
1037    int secs = bundle_Uptime(arg->bundle);
1038
1039    prompt_Printf(arg->prompt, ", up time %d:%02d:%02d", secs / 3600,
1040                  (secs / 60) % 60, secs % 60);
1041  }
1042  prompt_Printf(arg->prompt, "\n Queued:        %lu of %u\n",
1043                (unsigned long)ncp_QueueLen(&arg->bundle->ncp),
1044                arg->bundle->cfg.ifqueue);
1045
1046  prompt_Printf(arg->prompt, "\nDefaults:\n");
1047  prompt_Printf(arg->prompt, " Label:             %s\n",
1048                arg->bundle->cfg.label);
1049  prompt_Printf(arg->prompt, " Auth name:         %s\n",
1050                arg->bundle->cfg.auth.name);
1051  prompt_Printf(arg->prompt, " Diagnostic socket: ");
1052  if (*server.cfg.sockname != '\0') {
1053    prompt_Printf(arg->prompt, "%s", server.cfg.sockname);
1054    if (server.cfg.mask != (mode_t)-1)
1055      prompt_Printf(arg->prompt, ", mask 0%03o", (int)server.cfg.mask);
1056    prompt_Printf(arg->prompt, "%s\n", server.fd == -1 ? " (not open)" : "");
1057  } else if (server.cfg.port != 0)
1058    prompt_Printf(arg->prompt, "TCP port %d%s\n", server.cfg.port,
1059                  server.fd == -1 ? " (not open)" : "");
1060  else
1061    prompt_Printf(arg->prompt, "none\n");
1062
1063  prompt_Printf(arg->prompt, " Choked Timer:      %ds\n",
1064                arg->bundle->cfg.choked.timeout);
1065
1066#ifndef NORADIUS
1067  radius_Show(&arg->bundle->radius, arg->prompt);
1068#endif
1069
1070  prompt_Printf(arg->prompt, " Idle Timer:        ");
1071  if (arg->bundle->cfg.idle.timeout) {
1072    prompt_Printf(arg->prompt, "%ds", arg->bundle->cfg.idle.timeout);
1073    if (arg->bundle->cfg.idle.min_timeout)
1074      prompt_Printf(arg->prompt, ", min %ds",
1075                    arg->bundle->cfg.idle.min_timeout);
1076    remaining = bundle_RemainingIdleTime(arg->bundle);
1077    if (remaining != -1)
1078      prompt_Printf(arg->prompt, " (%ds remaining)", remaining);
1079    prompt_Printf(arg->prompt, "\n");
1080  } else
1081    prompt_Printf(arg->prompt, "disabled\n");
1082
1083  prompt_Printf(arg->prompt, " Filter Decap:      %-20.20s",
1084                optval(arg->bundle, OPT_FILTERDECAP));
1085  prompt_Printf(arg->prompt, " ID check:          %s\n",
1086                optval(arg->bundle, OPT_IDCHECK));
1087  prompt_Printf(arg->prompt, " Iface-Alias:       %-20.20s",
1088                optval(arg->bundle, OPT_IFACEALIAS));
1089#ifndef NOINET6
1090  prompt_Printf(arg->prompt, " IPCP:              %s\n",
1091                optval(arg->bundle, OPT_IPCP));
1092  prompt_Printf(arg->prompt, " IPV6CP:            %-20.20s",
1093                optval(arg->bundle, OPT_IPV6CP));
1094#endif
1095  prompt_Printf(arg->prompt, " Keep-Session:      %s\n",
1096                optval(arg->bundle, OPT_KEEPSESSION));
1097  prompt_Printf(arg->prompt, " Loopback:          %-20.20s",
1098                optval(arg->bundle, OPT_LOOPBACK));
1099  prompt_Printf(arg->prompt, " PasswdAuth:        %s\n",
1100                optval(arg->bundle, OPT_PASSWDAUTH));
1101  prompt_Printf(arg->prompt, " Proxy:             %-20.20s",
1102                optval(arg->bundle, OPT_PROXY));
1103  prompt_Printf(arg->prompt, " Proxyall:          %s\n",
1104                optval(arg->bundle, OPT_PROXYALL));
1105  prompt_Printf(arg->prompt, " Sticky Routes:     %-20.20s",
1106                optval(arg->bundle, OPT_SROUTES));
1107  prompt_Printf(arg->prompt, " TCPMSS Fixup:      %s\n",
1108                optval(arg->bundle, OPT_TCPMSSFIXUP));
1109  prompt_Printf(arg->prompt, " Throughput:        %-20.20s",
1110                optval(arg->bundle, OPT_THROUGHPUT));
1111  prompt_Printf(arg->prompt, " Utmp Logging:      %s\n",
1112                optval(arg->bundle, OPT_UTMP));
1113
1114  return 0;
1115}
1116
1117static void
1118bundle_IdleTimeout(void *v)
1119{
1120  struct bundle *bundle = (struct bundle *)v;
1121
1122  log_Printf(LogPHASE, "Idle timer expired\n");
1123  bundle_StopIdleTimer(bundle);
1124  bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
1125}
1126
1127/*
1128 *  Start Idle timer. If timeout is reached, we call bundle_Close() to
1129 *  close LCP and link.
1130 */
1131void
1132bundle_StartIdleTimer(struct bundle *bundle, unsigned secs)
1133{
1134  timer_Stop(&bundle->idle.timer);
1135  if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) !=
1136      bundle->phys_type.open && bundle->cfg.idle.timeout) {
1137    time_t now = time(NULL);
1138
1139    if (secs == 0)
1140      secs = bundle->cfg.idle.timeout;
1141
1142    /* We want at least `secs' */
1143    if (bundle->cfg.idle.min_timeout > secs && bundle->upat) {
1144      int up = now - bundle->upat;
1145
1146      if ((long long)bundle->cfg.idle.min_timeout - up > (long long)secs)
1147        /* Only increase from the current `remaining' value */
1148        secs = bundle->cfg.idle.min_timeout - up;
1149    }
1150    bundle->idle.timer.func = bundle_IdleTimeout;
1151    bundle->idle.timer.name = "idle";
1152    bundle->idle.timer.load = secs * SECTICKS;
1153    bundle->idle.timer.arg = bundle;
1154    timer_Start(&bundle->idle.timer);
1155    bundle->idle.done = now + secs;
1156  }
1157}
1158
1159void
1160bundle_SetIdleTimer(struct bundle *bundle, int timeout, int min_timeout)
1161{
1162  bundle->cfg.idle.timeout = timeout;
1163  if (min_timeout >= 0)
1164    bundle->cfg.idle.min_timeout = min_timeout;
1165  if (ncp_LayersOpen(&bundle->ncp))
1166    bundle_StartIdleTimer(bundle, 0);
1167}
1168
1169void
1170bundle_StopIdleTimer(struct bundle *bundle)
1171{
1172  timer_Stop(&bundle->idle.timer);
1173  bundle->idle.done = 0;
1174}
1175
1176static int
1177bundle_RemainingIdleTime(struct bundle *bundle)
1178{
1179  if (bundle->idle.done)
1180    return bundle->idle.done - time(NULL);
1181  return -1;
1182}
1183
1184int
1185bundle_IsDead(struct bundle *bundle)
1186{
1187  return !bundle->links || (bundle->phase == PHASE_DEAD && bundle->CleaningUp);
1188}
1189
1190static struct datalink *
1191bundle_DatalinkLinkout(struct bundle *bundle, struct datalink *dl)
1192{
1193  struct datalink **dlp;
1194
1195  for (dlp = &bundle->links; *dlp; dlp = &(*dlp)->next)
1196    if (*dlp == dl) {
1197      *dlp = dl->next;
1198      dl->next = NULL;
1199      bundle_LinksRemoved(bundle);
1200      return dl;
1201    }
1202
1203  return NULL;
1204}
1205
1206static void
1207bundle_DatalinkLinkin(struct bundle *bundle, struct datalink *dl)
1208{
1209  struct datalink **dlp = &bundle->links;
1210
1211  while (*dlp)
1212    dlp = &(*dlp)->next;
1213
1214  *dlp = dl;
1215  dl->next = NULL;
1216
1217  bundle_LinkAdded(bundle, dl);
1218  mp_CheckAutoloadTimer(&bundle->ncp.mp);
1219}
1220
1221void
1222bundle_CleanDatalinks(struct bundle *bundle)
1223{
1224  struct datalink **dlp = &bundle->links;
1225  int found = 0;
1226
1227  while (*dlp)
1228    if ((*dlp)->state == DATALINK_CLOSED &&
1229        (*dlp)->physical->type &
1230        (PHYS_DIRECT|PHYS_BACKGROUND|PHYS_FOREGROUND)) {
1231      *dlp = datalink_Destroy(*dlp);
1232      found++;
1233    } else
1234      dlp = &(*dlp)->next;
1235
1236  if (found)
1237    bundle_LinksRemoved(bundle);
1238}
1239
1240int
1241bundle_DatalinkClone(struct bundle *bundle, struct datalink *dl,
1242                     const char *name)
1243{
1244  if (bundle2datalink(bundle, name)) {
1245    log_Printf(LogWARN, "Clone: %s: name already exists\n", name);
1246    return 0;
1247  }
1248
1249  bundle_DatalinkLinkin(bundle, datalink_Clone(dl, name));
1250  return 1;
1251}
1252
1253void
1254bundle_DatalinkRemove(struct bundle *bundle, struct datalink *dl)
1255{
1256  dl = bundle_DatalinkLinkout(bundle, dl);
1257  if (dl)
1258    datalink_Destroy(dl);
1259}
1260
1261void
1262bundle_SetLabel(struct bundle *bundle, const char *label)
1263{
1264  if (label)
1265    strncpy(bundle->cfg.label, label, sizeof bundle->cfg.label - 1);
1266  else
1267    *bundle->cfg.label = '\0';
1268}
1269
1270const char *
1271bundle_GetLabel(struct bundle *bundle)
1272{
1273  return *bundle->cfg.label ? bundle->cfg.label : NULL;
1274}
1275
1276int
1277bundle_LinkSize()
1278{
1279  struct iovec iov[SCATTER_SEGMENTS];
1280  int niov, expect, f;
1281
1282  iov[0].iov_len = strlen(Version) + 1;
1283  iov[0].iov_base = NULL;
1284  niov = 1;
1285  if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1286    log_Printf(LogERROR, "Cannot determine space required for link\n");
1287    return 0;
1288  }
1289
1290  for (f = expect = 0; f < niov; f++)
1291    expect += iov[f].iov_len;
1292
1293  return expect;
1294}
1295
1296void
1297bundle_ReceiveDatalink(struct bundle *bundle, int s)
1298{
1299  char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int) * SEND_MAXFD];
1300  int niov, expect, f, *fd, nfd, onfd, got;
1301  struct iovec iov[SCATTER_SEGMENTS];
1302  struct cmsghdr *cmsg;
1303  struct msghdr msg;
1304  struct datalink *dl;
1305  pid_t pid;
1306
1307  log_Printf(LogPHASE, "Receiving datalink\n");
1308
1309  /*
1310   * Create our scatter/gather array - passing NULL gets the space
1311   * allocation requirement rather than actually flattening the
1312   * structures.
1313   */
1314  iov[0].iov_len = strlen(Version) + 1;
1315  iov[0].iov_base = NULL;
1316  niov = 1;
1317  if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1318    log_Printf(LogERROR, "Cannot determine space required for link\n");
1319    return;
1320  }
1321
1322  /* Allocate the scatter/gather array for recvmsg() */
1323  for (f = expect = 0; f < niov; f++) {
1324    if ((iov[f].iov_base = malloc(iov[f].iov_len)) == NULL) {
1325      log_Printf(LogERROR, "Cannot allocate space to receive link\n");
1326      return;
1327    }
1328    if (f)
1329      expect += iov[f].iov_len;
1330  }
1331
1332  /* Set up our message */
1333  cmsg = (struct cmsghdr *)cmsgbuf;
1334  cmsg->cmsg_len = sizeof cmsgbuf;
1335  cmsg->cmsg_level = SOL_SOCKET;
1336  cmsg->cmsg_type = 0;
1337
1338  memset(&msg, '\0', sizeof msg);
1339  msg.msg_name = NULL;
1340  msg.msg_namelen = 0;
1341  msg.msg_iov = iov;
1342  msg.msg_iovlen = 1;		/* Only send the version at the first pass */
1343  msg.msg_control = cmsgbuf;
1344  msg.msg_controllen = sizeof cmsgbuf;
1345
1346  log_Printf(LogDEBUG, "Expecting %u scatter/gather bytes\n",
1347             (unsigned)iov[0].iov_len);
1348
1349  if ((got = recvmsg(s, &msg, MSG_WAITALL)) != iov[0].iov_len) {
1350    if (got == -1)
1351      log_Printf(LogERROR, "Failed recvmsg: %s\n", strerror(errno));
1352    else
1353      log_Printf(LogERROR, "Failed recvmsg: Got %d, not %u\n",
1354                 got, (unsigned)iov[0].iov_len);
1355    while (niov--)
1356      free(iov[niov].iov_base);
1357    return;
1358  }
1359
1360  if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) {
1361    log_Printf(LogERROR, "Recvmsg: no descriptors received !\n");
1362    while (niov--)
1363      free(iov[niov].iov_base);
1364    return;
1365  }
1366
1367  fd = (int *)CMSG_DATA(cmsg);
1368  nfd = ((caddr_t)cmsg + cmsg->cmsg_len - (caddr_t)fd) / sizeof(int);
1369
1370  if (nfd < 2) {
1371    log_Printf(LogERROR, "Recvmsg: %d descriptor%s received (too few) !\n",
1372               nfd, nfd == 1 ? "" : "s");
1373    while (nfd--)
1374      close(fd[nfd]);
1375    while (niov--)
1376      free(iov[niov].iov_base);
1377    return;
1378  }
1379
1380  /*
1381   * We've successfully received two or more open file descriptors
1382   * through our socket, plus a version string.  Make sure it's the
1383   * correct version, and drop the connection if it's not.
1384   */
1385  if (strncmp(Version, iov[0].iov_base, iov[0].iov_len)) {
1386    log_Printf(LogWARN, "Cannot receive datalink, incorrect version"
1387               " (\"%.*s\", not \"%s\")\n", (int)iov[0].iov_len,
1388               (char *)iov[0].iov_base, Version);
1389    while (nfd--)
1390      close(fd[nfd]);
1391    while (niov--)
1392      free(iov[niov].iov_base);
1393    return;
1394  }
1395
1396  /*
1397   * Everything looks good.  Send the other side our process id so that
1398   * they can transfer lock ownership, and wait for them to send the
1399   * actual link data.
1400   */
1401  pid = getpid();
1402  if ((got = write(fd[1], &pid, sizeof pid)) != sizeof pid) {
1403    if (got == -1)
1404      log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1405    else
1406      log_Printf(LogERROR, "Failed write: Got %d, not %d\n", got,
1407                 (int)(sizeof pid));
1408    while (nfd--)
1409      close(fd[nfd]);
1410    while (niov--)
1411      free(iov[niov].iov_base);
1412    return;
1413  }
1414
1415  if ((got = readv(fd[1], iov + 1, niov - 1)) != expect) {
1416    if (got == -1)
1417      log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1418    else
1419      log_Printf(LogERROR, "Failed write: Got %d, not %d\n", got, expect);
1420    while (nfd--)
1421      close(fd[nfd]);
1422    while (niov--)
1423      free(iov[niov].iov_base);
1424    return;
1425  }
1426  close(fd[1]);
1427
1428  onfd = nfd;	/* We've got this many in our array */
1429  nfd -= 2;	/* Don't include p->fd and our reply descriptor */
1430  niov = 1;	/* Skip the version id */
1431  dl = iov2datalink(bundle, iov, &niov, sizeof iov / sizeof *iov, fd[0],
1432                    fd + 2, &nfd);
1433  if (dl) {
1434
1435    if (nfd) {
1436      log_Printf(LogERROR, "bundle_ReceiveDatalink: Failed to handle %d "
1437                 "auxiliary file descriptors (%d remain)\n", onfd, nfd);
1438      datalink_Destroy(dl);
1439      while (nfd--)
1440        close(fd[onfd--]);
1441      close(fd[0]);
1442    } else {
1443      bundle_DatalinkLinkin(bundle, dl);
1444      datalink_AuthOk(dl);
1445      bundle_CalculateBandwidth(dl->bundle);
1446    }
1447  } else {
1448    while (nfd--)
1449      close(fd[onfd--]);
1450    close(fd[0]);
1451    close(fd[1]);
1452  }
1453
1454  free(iov[0].iov_base);
1455}
1456
1457void
1458bundle_SendDatalink(struct datalink *dl, int s, struct sockaddr_un *sun)
1459{
1460  char cmsgbuf[CMSG_SPACE(sizeof(int) * SEND_MAXFD)];
1461  const char *constlock;
1462  char *lock;
1463  struct cmsghdr *cmsg;
1464  struct msghdr msg;
1465  struct iovec iov[SCATTER_SEGMENTS];
1466  int niov, f, expect, newsid, fd[SEND_MAXFD], nfd, reply[2], got;
1467  pid_t newpid;
1468
1469  log_Printf(LogPHASE, "Transmitting datalink %s\n", dl->name);
1470
1471  /* Record the base device name for a lock transfer later */
1472  constlock = physical_LockedDevice(dl->physical);
1473  if (constlock) {
1474    lock = alloca(strlen(constlock) + 1);
1475    strcpy(lock, constlock);
1476  } else
1477    lock = NULL;
1478
1479  bundle_LinkClosed(dl->bundle, dl);
1480  bundle_DatalinkLinkout(dl->bundle, dl);
1481
1482  /* Build our scatter/gather array */
1483  iov[0].iov_len = strlen(Version) + 1;
1484  iov[0].iov_base = strdup(Version);
1485  niov = 1;
1486  nfd = 0;
1487
1488  fd[0] = datalink2iov(dl, iov, &niov, SCATTER_SEGMENTS, fd + 2, &nfd);
1489
1490  if (fd[0] != -1 && socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, reply) != -1) {
1491    /*
1492     * fd[1] is used to get the peer process id back, then to confirm that
1493     * we've transferred any device locks to that process id.
1494     */
1495    fd[1] = reply[1];
1496
1497    nfd += 2;			/* Include fd[0] and fd[1] */
1498    memset(&msg, '\0', sizeof msg);
1499
1500    msg.msg_name = NULL;
1501    msg.msg_namelen = 0;
1502    /*
1503     * Only send the version to start...  We used to send the whole lot, but
1504     * this caused problems with our RECVBUF size as a single link is about
1505     * 22k !  This way, we should bump into no limits.
1506     */
1507    msg.msg_iovlen = 1;
1508    msg.msg_iov = iov;
1509    msg.msg_control = cmsgbuf;
1510    msg.msg_controllen = CMSG_SPACE(sizeof(int) * nfd);
1511    msg.msg_flags = 0;
1512
1513    cmsg = (struct cmsghdr *)cmsgbuf;
1514    cmsg->cmsg_len = msg.msg_controllen;
1515    cmsg->cmsg_level = SOL_SOCKET;
1516    cmsg->cmsg_type = SCM_RIGHTS;
1517
1518    for (f = 0; f < nfd; f++)
1519      *((int *)CMSG_DATA(cmsg) + f) = fd[f];
1520
1521    for (f = 1, expect = 0; f < niov; f++)
1522      expect += iov[f].iov_len;
1523
1524    if (setsockopt(reply[0], SOL_SOCKET, SO_SNDBUF, &expect, sizeof(int)) == -1)
1525      log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1526                 strerror(errno));
1527    if (setsockopt(reply[1], SOL_SOCKET, SO_RCVBUF, &expect, sizeof(int)) == -1)
1528      log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1529                 strerror(errno));
1530
1531    log_Printf(LogDEBUG, "Sending %d descriptor%s and %u bytes in scatter"
1532               "/gather array\n", nfd, nfd == 1 ? "" : "s",
1533               (unsigned)iov[0].iov_len);
1534
1535    if ((got = sendmsg(s, &msg, 0)) == -1)
1536      log_Printf(LogERROR, "Failed sendmsg: %s: %s\n",
1537                 sun->sun_path, strerror(errno));
1538    else if (got != iov[0].iov_len)
1539      log_Printf(LogERROR, "%s: Failed initial sendmsg: Only sent %d of %u\n",
1540                 sun->sun_path, got, (unsigned)iov[0].iov_len);
1541    else {
1542      /* We must get the ACK before closing the descriptor ! */
1543      int res;
1544
1545      if ((got = read(reply[0], &newpid, sizeof newpid)) == sizeof newpid) {
1546        log_Printf(LogDEBUG, "Received confirmation from pid %d\n",
1547                   (int)newpid);
1548        if (lock && (res = ID0uu_lock_txfr(lock, newpid)) != UU_LOCK_OK)
1549            log_Printf(LogERROR, "uu_lock_txfr: %s\n", uu_lockerr(res));
1550
1551        log_Printf(LogDEBUG, "Transmitting link (%d bytes)\n", expect);
1552        if ((got = writev(reply[0], iov + 1, niov - 1)) != expect) {
1553          if (got == -1)
1554            log_Printf(LogERROR, "%s: Failed writev: %s\n",
1555                       sun->sun_path, strerror(errno));
1556          else
1557            log_Printf(LogERROR, "%s: Failed writev: Wrote %d of %d\n",
1558                       sun->sun_path, got, expect);
1559        }
1560      } else if (got == -1)
1561        log_Printf(LogERROR, "%s: Failed socketpair read: %s\n",
1562                   sun->sun_path, strerror(errno));
1563      else
1564        log_Printf(LogERROR, "%s: Failed socketpair read: Got %d of %d\n",
1565                   sun->sun_path, got, (int)(sizeof newpid));
1566    }
1567
1568    close(reply[0]);
1569    close(reply[1]);
1570
1571    newsid = Enabled(dl->bundle, OPT_KEEPSESSION) ||
1572             tcgetpgrp(fd[0]) == getpgrp();
1573    while (nfd)
1574      close(fd[--nfd]);
1575    if (newsid)
1576      bundle_setsid(dl->bundle, got != -1);
1577  }
1578  close(s);
1579
1580  while (niov--)
1581    free(iov[niov].iov_base);
1582}
1583
1584int
1585bundle_RenameDatalink(struct bundle *bundle, struct datalink *ndl,
1586                      const char *name)
1587{
1588  struct datalink *dl;
1589
1590  if (!strcasecmp(ndl->name, name))
1591    return 1;
1592
1593  for (dl = bundle->links; dl; dl = dl->next)
1594    if (!strcasecmp(dl->name, name))
1595      return 0;
1596
1597  datalink_Rename(ndl, name);
1598  return 1;
1599}
1600
1601int
1602bundle_SetMode(struct bundle *bundle, struct datalink *dl, int mode)
1603{
1604  int omode;
1605
1606  omode = dl->physical->type;
1607  if (omode == mode)
1608    return 1;
1609
1610  if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO))
1611    /* First auto link */
1612    if (bundle->ncp.ipcp.peer_ip.s_addr == INADDR_ANY) {
1613      log_Printf(LogWARN, "You must `set ifaddr' or `open' before"
1614                 " changing mode to %s\n", mode2Nam(mode));
1615      return 0;
1616    }
1617
1618  if (!datalink_SetMode(dl, mode))
1619    return 0;
1620
1621  if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO) &&
1622      bundle->phase != PHASE_NETWORK)
1623    /* First auto link, we need an interface */
1624    ipcp_InterfaceUp(&bundle->ncp.ipcp);
1625
1626  /* Regenerate phys_type and adjust idle timer */
1627  bundle_LinksRemoved(bundle);
1628
1629  return 1;
1630}
1631
1632void
1633bundle_setsid(struct bundle *bundle, int holdsession)
1634{
1635  /*
1636   * Lose the current session.  This means getting rid of our pid
1637   * too so that the tty device will really go away, and any getty
1638   * etc will be allowed to restart.
1639   */
1640  pid_t pid, orig;
1641  int fds[2];
1642  char done;
1643  struct datalink *dl;
1644
1645  if (!holdsession && bundle_IsDead(bundle)) {
1646    /*
1647     * No need to lose our session after all... we're going away anyway
1648     *
1649     * We should really stop the timer and pause if holdsession is set and
1650     * the bundle's dead, but that leaves other resources lying about :-(
1651     */
1652    return;
1653  }
1654
1655  orig = getpid();
1656  if (pipe(fds) == -1) {
1657    log_Printf(LogERROR, "pipe: %s\n", strerror(errno));
1658    return;
1659  }
1660  switch ((pid = fork())) {
1661    case -1:
1662      log_Printf(LogERROR, "fork: %s\n", strerror(errno));
1663      close(fds[0]);
1664      close(fds[1]);
1665      return;
1666    case 0:
1667      close(fds[1]);
1668      read(fds[0], &done, 1);		/* uu_locks are mine ! */
1669      close(fds[0]);
1670      if (pipe(fds) == -1) {
1671        log_Printf(LogERROR, "pipe(2): %s\n", strerror(errno));
1672        return;
1673      }
1674      switch ((pid = fork())) {
1675        case -1:
1676          log_Printf(LogERROR, "fork(2): %s\n", strerror(errno));
1677          close(fds[0]);
1678          close(fds[1]);
1679          return;
1680        case 0:
1681          close(fds[1]);
1682          bundle_LockTun(bundle);	/* update pid */
1683          read(fds[0], &done, 1);	/* uu_locks are mine ! */
1684          close(fds[0]);
1685          setsid();
1686          bundle_ChangedPID(bundle);
1687          log_Printf(LogDEBUG, "%d -> %d: %s session control\n",
1688                     (int)orig, (int)getpid(),
1689                     holdsession ? "Passed" : "Dropped");
1690          timer_InitService(0);		/* Start the Timer Service */
1691          break;
1692        default:
1693          close(fds[0]);
1694          /* Give away all our physical locks (to the final process) */
1695          for (dl = bundle->links; dl; dl = dl->next)
1696            if (dl->state != DATALINK_CLOSED)
1697              physical_ChangedPid(dl->physical, pid);
1698          write(fds[1], "!", 1);	/* done */
1699          close(fds[1]);
1700          _exit(0);
1701          break;
1702      }
1703      break;
1704    default:
1705      close(fds[0]);
1706      /* Give away all our physical locks (to the intermediate process) */
1707      for (dl = bundle->links; dl; dl = dl->next)
1708        if (dl->state != DATALINK_CLOSED)
1709          physical_ChangedPid(dl->physical, pid);
1710      write(fds[1], "!", 1);	/* done */
1711      close(fds[1]);
1712      if (holdsession) {
1713        int fd, status;
1714
1715        timer_TermService();
1716        signal(SIGPIPE, SIG_DFL);
1717        signal(SIGALRM, SIG_DFL);
1718        signal(SIGHUP, SIG_DFL);
1719        signal(SIGTERM, SIG_DFL);
1720        signal(SIGINT, SIG_DFL);
1721        signal(SIGQUIT, SIG_DFL);
1722        for (fd = getdtablesize(); fd >= 0; fd--)
1723          close(fd);
1724        /*
1725         * Reap the intermediate process.  As we're not exiting but the
1726         * intermediate is, we don't want it to become defunct.
1727         */
1728        waitpid(pid, &status, 0);
1729        /* Tweak our process arguments.... */
1730        SetTitle("session owner");
1731#ifndef NOSUID
1732        setuid(ID0realuid());
1733#endif
1734        /*
1735         * Hang around for a HUP.  This should happen as soon as the
1736         * ppp that we passed our ctty descriptor to closes it.
1737         * NOTE: If this process dies, the passed descriptor becomes
1738         *       invalid and will give a select() error by setting one
1739         *       of the error fds, aborting the other ppp.  We don't
1740         *       want that to happen !
1741         */
1742        pause();
1743      }
1744      _exit(0);
1745      break;
1746  }
1747}
1748
1749int
1750bundle_HighestState(struct bundle *bundle)
1751{
1752  struct datalink *dl;
1753  int result = DATALINK_CLOSED;
1754
1755  for (dl = bundle->links; dl; dl = dl->next)
1756    if (result < dl->state)
1757      result = dl->state;
1758
1759  return result;
1760}
1761
1762int
1763bundle_Exception(struct bundle *bundle, int fd)
1764{
1765  struct datalink *dl;
1766
1767  for (dl = bundle->links; dl; dl = dl->next)
1768    if (dl->physical->fd == fd) {
1769      datalink_Down(dl, CLOSE_NORMAL);
1770      return 1;
1771    }
1772
1773  return 0;
1774}
1775
1776void
1777bundle_AdjustFilters(struct bundle *bundle, struct ncpaddr *local,
1778                     struct ncpaddr *remote)
1779{
1780  filter_AdjustAddr(&bundle->filter.in, local, remote, NULL);
1781  filter_AdjustAddr(&bundle->filter.out, local, remote, NULL);
1782  filter_AdjustAddr(&bundle->filter.dial, local, remote, NULL);
1783  filter_AdjustAddr(&bundle->filter.alive, local, remote, NULL);
1784}
1785
1786void
1787bundle_AdjustDNS(struct bundle *bundle)
1788{
1789  struct in_addr *dns = bundle->ncp.ipcp.ns.dns;
1790
1791  filter_AdjustAddr(&bundle->filter.in, NULL, NULL, dns);
1792  filter_AdjustAddr(&bundle->filter.out, NULL, NULL, dns);
1793  filter_AdjustAddr(&bundle->filter.dial, NULL, NULL, dns);
1794  filter_AdjustAddr(&bundle->filter.alive, NULL, NULL, dns);
1795}
1796
1797void
1798bundle_CalculateBandwidth(struct bundle *bundle)
1799{
1800  struct datalink *dl;
1801  int sp, overhead, maxoverhead;
1802
1803  bundle->bandwidth = 0;
1804  bundle->iface->mtu = 0;
1805  maxoverhead = 0;
1806
1807  for (dl = bundle->links; dl; dl = dl->next) {
1808    overhead = ccp_MTUOverhead(&dl->physical->link.ccp);
1809    if (maxoverhead < overhead)
1810      maxoverhead = overhead;
1811    if (dl->state == DATALINK_OPEN) {
1812      if ((sp = dl->mp.bandwidth) == 0 &&
1813          (sp = physical_GetSpeed(dl->physical)) == 0)
1814        log_Printf(LogDEBUG, "%s: %s: Cannot determine bandwidth\n",
1815                   dl->name, dl->physical->name.full);
1816      else
1817        bundle->bandwidth += sp;
1818      if (!bundle->ncp.mp.active) {
1819        bundle->iface->mtu = dl->physical->link.lcp.his_mru;
1820        break;
1821      }
1822    }
1823  }
1824
1825  if(bundle->bandwidth == 0)
1826    bundle->bandwidth = 115200;		/* Shrug */
1827
1828  if (bundle->ncp.mp.active) {
1829    bundle->iface->mtu = bundle->ncp.mp.peer_mrru;
1830    overhead = ccp_MTUOverhead(&bundle->ncp.mp.link.ccp);
1831    if (maxoverhead < overhead)
1832      maxoverhead = overhead;
1833  } else if (!bundle->iface->mtu)
1834    bundle->iface->mtu = DEF_MRU;
1835
1836#ifndef NORADIUS
1837  if (bundle->radius.valid && bundle->radius.mtu &&
1838      bundle->radius.mtu < bundle->iface->mtu) {
1839    log_Printf(LogLCP, "Reducing MTU to radius value %lu\n",
1840               bundle->radius.mtu);
1841    bundle->iface->mtu = bundle->radius.mtu;
1842  }
1843#endif
1844
1845  if (maxoverhead) {
1846    log_Printf(LogLCP, "Reducing MTU from %d to %d (CCP requirement)\n",
1847               bundle->iface->mtu, bundle->iface->mtu - maxoverhead);
1848    bundle->iface->mtu -= maxoverhead;
1849  }
1850
1851  tun_configure(bundle);
1852
1853  route_UpdateMTU(bundle);
1854}
1855
1856void
1857bundle_AutoAdjust(struct bundle *bundle, int percent, int what)
1858{
1859  struct datalink *dl, *choice, *otherlinkup;
1860
1861  choice = otherlinkup = NULL;
1862  for (dl = bundle->links; dl; dl = dl->next)
1863    if (dl->physical->type == PHYS_AUTO) {
1864      if (dl->state == DATALINK_OPEN) {
1865        if (what == AUTO_DOWN) {
1866          if (choice)
1867            otherlinkup = choice;
1868          choice = dl;
1869        }
1870      } else if (dl->state == DATALINK_CLOSED) {
1871        if (what == AUTO_UP) {
1872          choice = dl;
1873          break;
1874        }
1875      } else {
1876        /* An auto link in an intermediate state - forget it for the moment */
1877        choice = NULL;
1878        break;
1879      }
1880    } else if (dl->state == DATALINK_OPEN && what == AUTO_DOWN)
1881      otherlinkup = dl;
1882
1883  if (choice) {
1884    if (what == AUTO_UP) {
1885      log_Printf(LogPHASE, "%d%% saturation -> Opening link ``%s''\n",
1886                 percent, choice->name);
1887      datalink_Up(choice, 1, 1);
1888      mp_CheckAutoloadTimer(&bundle->ncp.mp);
1889    } else if (otherlinkup) {	/* Only bring the second-last link down */
1890      log_Printf(LogPHASE, "%d%% saturation -> Closing link ``%s''\n",
1891                 percent, choice->name);
1892      datalink_Close(choice, CLOSE_STAYDOWN);
1893      mp_CheckAutoloadTimer(&bundle->ncp.mp);
1894    }
1895  }
1896}
1897
1898int
1899bundle_WantAutoloadTimer(struct bundle *bundle)
1900{
1901  struct datalink *dl;
1902  int autolink, opened;
1903
1904  if (bundle->phase == PHASE_NETWORK) {
1905    for (autolink = opened = 0, dl = bundle->links; dl; dl = dl->next)
1906      if (dl->physical->type == PHYS_AUTO) {
1907        if (++autolink == 2 || (autolink == 1 && opened))
1908          /* Two auto links or one auto and one open in NETWORK phase */
1909          return 1;
1910      } else if (dl->state == DATALINK_OPEN) {
1911        opened++;
1912        if (autolink)
1913          /* One auto and one open link in NETWORK phase */
1914          return 1;
1915      }
1916  }
1917
1918  return 0;
1919}
1920
1921void
1922bundle_ChangedPID(struct bundle *bundle)
1923{
1924#ifdef TUNSIFPID
1925  ioctl(bundle->dev.fd, TUNSIFPID, 0);
1926#endif
1927}
1928
1929int
1930bundle_Uptime(struct bundle *bundle)
1931{
1932  if (bundle->upat)
1933    return time(NULL) - bundle->upat;
1934
1935  return 0;
1936}
1937