bundle.c revision 61800
136285Sbrian/*-
236285Sbrian * Copyright (c) 1998 Brian Somers <brian@Awfulhak.org>
336285Sbrian * All rights reserved.
436285Sbrian *
536285Sbrian * Redistribution and use in source and binary forms, with or without
636285Sbrian * modification, are permitted provided that the following conditions
736285Sbrian * are met:
836285Sbrian * 1. Redistributions of source code must retain the above copyright
936285Sbrian *    notice, this list of conditions and the following disclaimer.
1036285Sbrian * 2. Redistributions in binary form must reproduce the above copyright
1136285Sbrian *    notice, this list of conditions and the following disclaimer in the
1236285Sbrian *    documentation and/or other materials provided with the distribution.
1336285Sbrian *
1436285Sbrian * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1536285Sbrian * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1636285Sbrian * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1736285Sbrian * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
1836285Sbrian * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1936285Sbrian * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2036285Sbrian * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2136285Sbrian * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2236285Sbrian * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2336285Sbrian * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2436285Sbrian * SUCH DAMAGE.
2536285Sbrian *
2650479Speter * $FreeBSD: head/usr.sbin/ppp/bundle.c 61800 2000-06-18 10:07:53Z brian $
2736285Sbrian */
2836285Sbrian
2936452Sbrian#include <sys/param.h>
3036285Sbrian#include <sys/socket.h>
3136285Sbrian#include <netinet/in.h>
3236285Sbrian#include <net/if.h>
3356413Sbrian#include <net/if_tun.h>		/* For TUNS* ioctls */
3436285Sbrian#include <arpa/inet.h>
3536285Sbrian#include <net/route.h>
3636285Sbrian#include <netinet/in_systm.h>
3736285Sbrian#include <netinet/ip.h>
3836285Sbrian#include <sys/un.h>
3936285Sbrian
4036285Sbrian#include <errno.h>
4136285Sbrian#include <fcntl.h>
4253298Sbrian#ifdef __OpenBSD__
4353298Sbrian#include <util.h>
4453298Sbrian#else
4553298Sbrian#include <libutil.h>
4653298Sbrian#endif
4736285Sbrian#include <paths.h>
4836285Sbrian#include <stdio.h>
4936285Sbrian#include <stdlib.h>
5036285Sbrian#include <string.h>
5136285Sbrian#include <sys/uio.h>
5236345Sbrian#include <sys/wait.h>
5351525Sbrian#if defined(__FreeBSD__) && !defined(NOKLDLOAD)
5451525Sbrian#include <sys/linker.h>
5553241Sbrian#include <sys/module.h>
5651525Sbrian#endif
5736285Sbrian#include <termios.h>
5836285Sbrian#include <unistd.h>
5936285Sbrian
6046686Sbrian#include "layer.h"
6137009Sbrian#include "defs.h"
6236285Sbrian#include "command.h"
6336285Sbrian#include "mbuf.h"
6436285Sbrian#include "log.h"
6536285Sbrian#include "id.h"
6636285Sbrian#include "timer.h"
6736285Sbrian#include "fsm.h"
6836285Sbrian#include "iplist.h"
6936285Sbrian#include "lqr.h"
7036285Sbrian#include "hdlc.h"
7136285Sbrian#include "throughput.h"
7236285Sbrian#include "slcompress.h"
7336285Sbrian#include "ipcp.h"
7436285Sbrian#include "filter.h"
7536285Sbrian#include "descriptor.h"
7636285Sbrian#include "route.h"
7736285Sbrian#include "lcp.h"
7836285Sbrian#include "ccp.h"
7936285Sbrian#include "link.h"
8036285Sbrian#include "mp.h"
8143313Sbrian#ifndef NORADIUS
8243313Sbrian#include "radius.h"
8343313Sbrian#endif
8436285Sbrian#include "bundle.h"
8536285Sbrian#include "async.h"
8636285Sbrian#include "physical.h"
8736285Sbrian#include "auth.h"
8846686Sbrian#include "proto.h"
8936285Sbrian#include "chap.h"
9036285Sbrian#include "tun.h"
9136285Sbrian#include "prompt.h"
9236285Sbrian#include "chat.h"
9338174Sbrian#include "cbcp.h"
9436285Sbrian#include "datalink.h"
9536285Sbrian#include "ip.h"
9640561Sbrian#include "iface.h"
9736285Sbrian
9853684Sbrian#define SCATTER_SEGMENTS 6  /* version, datalink, name, physical,
9953684Sbrian                               throughput, device                   */
10036285Sbrian
10153684Sbrian#define SEND_MAXFD 3        /* Max file descriptors passed through
10253684Sbrian                               the local domain socket              */
10352942Sbrian
10436285Sbrianstatic int bundle_RemainingIdleTime(struct bundle *);
10536285Sbrian
10655146Sbrianstatic const char * const PhaseNames[] = {
10736285Sbrian  "Dead", "Establish", "Authenticate", "Network", "Terminate"
10836285Sbrian};
10936285Sbrian
11036285Sbrianconst char *
11136285Sbrianbundle_PhaseName(struct bundle *bundle)
11236285Sbrian{
11336285Sbrian  return bundle->phase <= PHASE_TERMINATE ?
11436285Sbrian    PhaseNames[bundle->phase] : "unknown";
11536285Sbrian}
11636285Sbrian
11736285Sbrianvoid
11836285Sbrianbundle_NewPhase(struct bundle *bundle, u_int new)
11936285Sbrian{
12036285Sbrian  if (new == bundle->phase)
12136285Sbrian    return;
12236285Sbrian
12336285Sbrian  if (new <= PHASE_TERMINATE)
12436285Sbrian    log_Printf(LogPHASE, "bundle: %s\n", PhaseNames[new]);
12536285Sbrian
12636285Sbrian  switch (new) {
12736285Sbrian  case PHASE_DEAD:
12836314Sbrian    log_DisplayPrompts();
12936285Sbrian    bundle->phase = new;
13036285Sbrian    break;
13136285Sbrian
13236285Sbrian  case PHASE_ESTABLISH:
13336285Sbrian    bundle->phase = new;
13436285Sbrian    break;
13536285Sbrian
13636285Sbrian  case PHASE_AUTHENTICATE:
13736285Sbrian    bundle->phase = new;
13836314Sbrian    log_DisplayPrompts();
13936285Sbrian    break;
14036285Sbrian
14136285Sbrian  case PHASE_NETWORK:
14236285Sbrian    fsm_Up(&bundle->ncp.ipcp.fsm);
14336285Sbrian    fsm_Open(&bundle->ncp.ipcp.fsm);
14436285Sbrian    bundle->phase = new;
14536314Sbrian    log_DisplayPrompts();
14636285Sbrian    break;
14736285Sbrian
14836285Sbrian  case PHASE_TERMINATE:
14936285Sbrian    bundle->phase = new;
15036285Sbrian    mp_Down(&bundle->ncp.mp);
15136314Sbrian    log_DisplayPrompts();
15236285Sbrian    break;
15336285Sbrian  }
15436285Sbrian}
15536285Sbrian
15636285Sbrianstatic void
15736285Sbrianbundle_LayerStart(void *v, struct fsm *fp)
15836285Sbrian{
15936285Sbrian  /* The given FSM is about to start up ! */
16036285Sbrian}
16136285Sbrian
16236285Sbrian
16359084Sbrianvoid
16436285Sbrianbundle_Notify(struct bundle *bundle, char c)
16536285Sbrian{
16636285Sbrian  if (bundle->notify.fd != -1) {
16759084Sbrian    int ret;
16859084Sbrian
16959084Sbrian    ret = write(bundle->notify.fd, &c, 1);
17059084Sbrian    if (c != EX_REDIAL && c != EX_RECONNECT) {
17159084Sbrian      if (ret == 1)
17259084Sbrian        log_Printf(LogCHAT, "Parent notified of %s\n",
17359084Sbrian                   c == EX_NORMAL ? "success" : "failure");
17459084Sbrian      else
17559084Sbrian        log_Printf(LogERROR, "Failed to notify parent of success\n");
17659084Sbrian      close(bundle->notify.fd);
17759084Sbrian      bundle->notify.fd = -1;
17859084Sbrian    } else if (ret == 1)
17959084Sbrian      log_Printf(LogCHAT, "Parent notified of %s\n", ex_desc(c));
18036285Sbrian    else
18159084Sbrian      log_Printf(LogERROR, "Failed to notify parent of %s\n", ex_desc(c));
18236285Sbrian  }
18336285Sbrian}
18436285Sbrian
18538544Sbrianstatic void
18638544Sbrianbundle_ClearQueues(void *v)
18738544Sbrian{
18838544Sbrian  struct bundle *bundle = (struct bundle *)v;
18938544Sbrian  struct datalink *dl;
19038544Sbrian
19138544Sbrian  log_Printf(LogPHASE, "Clearing choked output queue\n");
19238544Sbrian  timer_Stop(&bundle->choked.timer);
19338544Sbrian
19438544Sbrian  /*
19538544Sbrian   * Emergency time:
19638544Sbrian   *
19738544Sbrian   * We've had a full queue for PACKET_DEL_SECS seconds without being
19838544Sbrian   * able to get rid of any of the packets.  We've probably given up
19938544Sbrian   * on the redials at this point, and the queued data has almost
20038544Sbrian   * definitely been timed out by the layer above.  As this is preventing
20138544Sbrian   * us from reading the TUN_NAME device (we don't want to buffer stuff
20238544Sbrian   * indefinitely), we may as well nuke this data and start with a clean
20338544Sbrian   * slate !
20438544Sbrian   *
20538544Sbrian   * Unfortunately, this has the side effect of shafting any compression
20638544Sbrian   * dictionaries in use (causing the relevant RESET_REQ/RESET_ACK).
20738544Sbrian   */
20838544Sbrian
20938557Sbrian  ip_DeleteQueue(&bundle->ncp.ipcp);
21038544Sbrian  mp_DeleteQueue(&bundle->ncp.mp);
21138544Sbrian  for (dl = bundle->links; dl; dl = dl->next)
21238544Sbrian    physical_DeleteQueue(dl->physical);
21338544Sbrian}
21438544Sbrian
21536285Sbrianstatic void
21636928Sbrianbundle_LinkAdded(struct bundle *bundle, struct datalink *dl)
21736928Sbrian{
21836928Sbrian  bundle->phys_type.all |= dl->physical->type;
21936928Sbrian  if (dl->state == DATALINK_OPEN)
22036928Sbrian    bundle->phys_type.open |= dl->physical->type;
22136285Sbrian
22236928Sbrian  if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
22336928Sbrian      != bundle->phys_type.open && bundle->idle.timer.state == TIMER_STOPPED)
22436928Sbrian    /* We may need to start our idle timer */
22536928Sbrian    bundle_StartIdleTimer(bundle);
22636928Sbrian}
22736928Sbrian
22838174Sbrianvoid
22936928Sbrianbundle_LinksRemoved(struct bundle *bundle)
23036928Sbrian{
23136928Sbrian  struct datalink *dl;
23236928Sbrian
23336928Sbrian  bundle->phys_type.all = bundle->phys_type.open = 0;
23436928Sbrian  for (dl = bundle->links; dl; dl = dl->next)
23536928Sbrian    bundle_LinkAdded(bundle, dl);
23636928Sbrian
23749434Sbrian  bundle_CalculateBandwidth(bundle);
23849434Sbrian  mp_CheckAutoloadTimer(&bundle->ncp.mp);
23949434Sbrian
24036928Sbrian  if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
24136928Sbrian      == bundle->phys_type.open)
24236928Sbrian    bundle_StopIdleTimer(bundle);
24336928Sbrian}
24436928Sbrian
24536928Sbrianstatic void
24636285Sbrianbundle_LayerUp(void *v, struct fsm *fp)
24736285Sbrian{
24836285Sbrian  /*
24936285Sbrian   * The given fsm is now up
25049434Sbrian   * If it's an LCP, adjust our phys_mode.open value and check the
25149434Sbrian   * autoload timer.
25249434Sbrian   * If it's the first NCP, calculate our bandwidth
25349978Sbrian   * If it's the first NCP, set our ``upat'' time
25449434Sbrian   * If it's the first NCP, start the idle timer.
25536285Sbrian   * If it's an NCP, tell our -background parent to go away.
25649434Sbrian   * If it's the first NCP, start the autoload timer
25736285Sbrian   */
25836285Sbrian  struct bundle *bundle = (struct bundle *)v;
25936285Sbrian
26036285Sbrian  if (fp->proto == PROTO_LCP) {
26136928Sbrian    struct physical *p = link2physical(fp->link);
26236928Sbrian
26336928Sbrian    bundle_LinkAdded(bundle, p->dl);
26449434Sbrian    mp_CheckAutoloadTimer(&bundle->ncp.mp);
26536285Sbrian  } else if (fp->proto == PROTO_IPCP) {
26649434Sbrian    bundle_CalculateBandwidth(fp->bundle);
26749978Sbrian    time(&bundle->upat);
26836285Sbrian    bundle_StartIdleTimer(bundle);
26936285Sbrian    bundle_Notify(bundle, EX_NORMAL);
27049434Sbrian    mp_CheckAutoloadTimer(&fp->bundle->ncp.mp);
27136285Sbrian  }
27236285Sbrian}
27336285Sbrian
27436285Sbrianstatic void
27536285Sbrianbundle_LayerDown(void *v, struct fsm *fp)
27636285Sbrian{
27736285Sbrian  /*
27836285Sbrian   * The given FSM has been told to come down.
27936285Sbrian   * If it's our last NCP, stop the idle timer.
28049978Sbrian   * If it's our last NCP, clear our ``upat'' value.
28149434Sbrian   * If it's our last NCP, stop the autoload timer
28236928Sbrian   * If it's an LCP, adjust our phys_type.open value and any timers.
28336312Sbrian   * If it's an LCP and we're in multilink mode, adjust our tun
28459070Sbrian   * If it's the last LCP, down all NCPs
28536312Sbrian   * speed and make sure our minimum sequence number is adjusted.
28636285Sbrian   */
28736285Sbrian
28836285Sbrian  struct bundle *bundle = (struct bundle *)v;
28936285Sbrian
29049434Sbrian  if (fp->proto == PROTO_IPCP) {
29136285Sbrian    bundle_StopIdleTimer(bundle);
29249978Sbrian    bundle->upat = 0;
29349434Sbrian    mp_StopAutoloadTimer(&bundle->ncp.mp);
29449434Sbrian  } else if (fp->proto == PROTO_LCP) {
29559070Sbrian    struct datalink *dl;
29659070Sbrian    struct datalink *lost;
29759070Sbrian    int others_active;
29859070Sbrian
29936928Sbrian    bundle_LinksRemoved(bundle);  /* adjust timers & phys_type values */
30036285Sbrian
30159070Sbrian    lost = NULL;
30259070Sbrian    others_active = 0;
30359070Sbrian    for (dl = bundle->links; dl; dl = dl->next) {
30459070Sbrian      if (fp == &dl->physical->link.lcp.fsm)
30559070Sbrian        lost = dl;
30659070Sbrian      else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
30759070Sbrian        others_active++;
30859070Sbrian    }
30936312Sbrian
31059070Sbrian    if (bundle->ncp.mp.active) {
31149434Sbrian      bundle_CalculateBandwidth(bundle);
31236312Sbrian
31336928Sbrian      if (lost)
31436928Sbrian        mp_LinkLost(&bundle->ncp.mp, lost);
31536928Sbrian      else
31637019Sbrian        log_Printf(LogALERT, "Oops, lost an unrecognised datalink (%s) !\n",
31736928Sbrian                   fp->link->name);
31836928Sbrian    }
31959070Sbrian
32059070Sbrian    if (!others_active)
32159070Sbrian      /* Down the NCPs.  We don't expect to get fsm_Close()d ourself ! */
32259070Sbrian      fsm2initial(&bundle->ncp.ipcp.fsm);
32336285Sbrian  }
32436285Sbrian}
32536285Sbrian
32636285Sbrianstatic void
32736285Sbrianbundle_LayerFinish(void *v, struct fsm *fp)
32836285Sbrian{
32936285Sbrian  /* The given fsm is now down (fp cannot be NULL)
33036285Sbrian   *
33136285Sbrian   * If it's the last NCP, fsm_Close all LCPs
33236285Sbrian   */
33336285Sbrian
33436285Sbrian  struct bundle *bundle = (struct bundle *)v;
33536285Sbrian  struct datalink *dl;
33636285Sbrian
33736285Sbrian  if (fp->proto == PROTO_IPCP) {
33836285Sbrian    if (bundle_Phase(bundle) != PHASE_DEAD)
33936285Sbrian      bundle_NewPhase(bundle, PHASE_TERMINATE);
34036285Sbrian    for (dl = bundle->links; dl; dl = dl->next)
34159070Sbrian      if (dl->state == DATALINK_OPEN)
34259070Sbrian        datalink_Close(dl, CLOSE_STAYDOWN);
34337060Sbrian    fsm2initial(fp);
34436285Sbrian  }
34536285Sbrian}
34636285Sbrian
34736285Sbrianint
34836285Sbrianbundle_LinkIsUp(const struct bundle *bundle)
34936285Sbrian{
35036285Sbrian  return bundle->ncp.ipcp.fsm.state == ST_OPENED;
35136285Sbrian}
35236285Sbrian
35336285Sbrianvoid
35437007Sbrianbundle_Close(struct bundle *bundle, const char *name, int how)
35536285Sbrian{
35636285Sbrian  /*
35736285Sbrian   * Please close the given datalink.
35836285Sbrian   * If name == NULL or name is the last datalink, fsm_Close all NCPs
35936285Sbrian   * (except our MP)
36036285Sbrian   * If it isn't the last datalink, just Close that datalink.
36136285Sbrian   */
36236285Sbrian
36336285Sbrian  struct datalink *dl, *this_dl;
36436285Sbrian  int others_active;
36536285Sbrian
36636285Sbrian  others_active = 0;
36736285Sbrian  this_dl = NULL;
36836285Sbrian
36936285Sbrian  for (dl = bundle->links; dl; dl = dl->next) {
37036285Sbrian    if (name && !strcasecmp(name, dl->name))
37136285Sbrian      this_dl = dl;
37236285Sbrian    if (name == NULL || this_dl == dl) {
37337007Sbrian      switch (how) {
37437007Sbrian        case CLOSE_LCP:
37537007Sbrian          datalink_DontHangup(dl);
37637007Sbrian          /* fall through */
37737007Sbrian        case CLOSE_STAYDOWN:
37837007Sbrian          datalink_StayDown(dl);
37937007Sbrian          break;
38037007Sbrian      }
38136285Sbrian    } else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
38236285Sbrian      others_active++;
38336285Sbrian  }
38436285Sbrian
38536285Sbrian  if (name && this_dl == NULL) {
38636285Sbrian    log_Printf(LogWARN, "%s: Invalid datalink name\n", name);
38736285Sbrian    return;
38836285Sbrian  }
38936285Sbrian
39036285Sbrian  if (!others_active) {
39136285Sbrian    bundle_StopIdleTimer(bundle);
39236285Sbrian    if (bundle->ncp.ipcp.fsm.state > ST_CLOSED ||
39336285Sbrian        bundle->ncp.ipcp.fsm.state == ST_STARTING)
39436285Sbrian      fsm_Close(&bundle->ncp.ipcp.fsm);
39536285Sbrian    else {
39637060Sbrian      fsm2initial(&bundle->ncp.ipcp.fsm);
39736285Sbrian      for (dl = bundle->links; dl; dl = dl->next)
39837007Sbrian        datalink_Close(dl, how);
39936285Sbrian    }
40036285Sbrian  } else if (this_dl && this_dl->state != DATALINK_CLOSED &&
40136285Sbrian             this_dl->state != DATALINK_HANGUP)
40237007Sbrian    datalink_Close(this_dl, how);
40336285Sbrian}
40436285Sbrian
40536285Sbrianvoid
40637018Sbrianbundle_Down(struct bundle *bundle, int how)
40736285Sbrian{
40836285Sbrian  struct datalink *dl;
40936285Sbrian
41036285Sbrian  for (dl = bundle->links; dl; dl = dl->next)
41137018Sbrian    datalink_Down(dl, how);
41236285Sbrian}
41336285Sbrian
41454912Sbrianstatic size_t
41554912Sbrianbundle_FillQueues(struct bundle *bundle)
41654912Sbrian{
41754912Sbrian  size_t total;
41854912Sbrian
41954912Sbrian  if (bundle->ncp.mp.active)
42054912Sbrian    total = mp_FillQueues(bundle);
42154912Sbrian  else {
42254912Sbrian    struct datalink *dl;
42354912Sbrian    size_t add;
42454912Sbrian
42554912Sbrian    for (total = 0, dl = bundle->links; dl; dl = dl->next)
42654912Sbrian      if (dl->state == DATALINK_OPEN) {
42754912Sbrian        add = link_QueueLen(&dl->physical->link);
42854912Sbrian        if (add == 0 && dl->physical->out == NULL)
42954912Sbrian          add = ip_PushPacket(&dl->physical->link, bundle);
43054912Sbrian        total += add;
43154912Sbrian      }
43254912Sbrian  }
43354912Sbrian
43454912Sbrian  return total + ip_QueueLen(&bundle->ncp.ipcp);
43554912Sbrian}
43654912Sbrian
43736285Sbrianstatic int
43858028Sbrianbundle_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
43936285Sbrian{
44036285Sbrian  struct bundle *bundle = descriptor2bundle(d);
44136285Sbrian  struct datalink *dl;
44254912Sbrian  int result, nlinks;
44361534Sbrian  u_short ifqueue;
44454912Sbrian  size_t queued;
44536285Sbrian
44636285Sbrian  result = 0;
44736285Sbrian
44836285Sbrian  /* If there are aren't many packets queued, look for some more. */
44936285Sbrian  for (nlinks = 0, dl = bundle->links; dl; dl = dl->next)
45036285Sbrian    nlinks++;
45136285Sbrian
45236285Sbrian  if (nlinks) {
45338557Sbrian    queued = r ? bundle_FillQueues(bundle) : ip_QueueLen(&bundle->ncp.ipcp);
45436285Sbrian
45536928Sbrian    if (r && (bundle->phase == PHASE_NETWORK ||
45636928Sbrian              bundle->phys_type.all & PHYS_AUTO)) {
45736285Sbrian      /* enough surplus so that we can tell if we're getting swamped */
45861534Sbrian      ifqueue = nlinks > bundle->cfg.ifqueue ? nlinks : bundle->cfg.ifqueue;
45961534Sbrian      if (queued < ifqueue) {
46036285Sbrian        /* Not enough - select() for more */
46138544Sbrian        if (bundle->choked.timer.state == TIMER_RUNNING)
46238544Sbrian          timer_Stop(&bundle->choked.timer);	/* Not needed any more */
46336285Sbrian        FD_SET(bundle->dev.fd, r);
46436285Sbrian        if (*n < bundle->dev.fd + 1)
46536285Sbrian          *n = bundle->dev.fd + 1;
46636452Sbrian        log_Printf(LogTIMER, "%s: fdset(r) %d\n", TUN_NAME, bundle->dev.fd);
46736285Sbrian        result++;
46838544Sbrian      } else if (bundle->choked.timer.state == TIMER_STOPPED) {
46938544Sbrian        bundle->choked.timer.func = bundle_ClearQueues;
47038544Sbrian        bundle->choked.timer.name = "output choke";
47138544Sbrian        bundle->choked.timer.load = bundle->cfg.choked.timeout * SECTICKS;
47238544Sbrian        bundle->choked.timer.arg = bundle;
47338544Sbrian        timer_Start(&bundle->choked.timer);
47436285Sbrian      }
47536285Sbrian    }
47636285Sbrian  }
47736285Sbrian
47843693Sbrian#ifndef NORADIUS
47943693Sbrian  result += descriptor_UpdateSet(&bundle->radius.desc, r, w, e, n);
48043693Sbrian#endif
48143693Sbrian
48236714Sbrian  /* Which links need a select() ? */
48336714Sbrian  for (dl = bundle->links; dl; dl = dl->next)
48436714Sbrian    result += descriptor_UpdateSet(&dl->desc, r, w, e, n);
48536714Sbrian
48636285Sbrian  /*
48736285Sbrian   * This *MUST* be called after the datalink UpdateSet()s as it
48836285Sbrian   * might be ``holding'' one of the datalinks (death-row) and
48958038Sbrian   * wants to be able to de-select() it from the descriptor set.
49036285Sbrian   */
49136314Sbrian  result += descriptor_UpdateSet(&bundle->ncp.mp.server.desc, r, w, e, n);
49236285Sbrian
49336285Sbrian  return result;
49436285Sbrian}
49536285Sbrian
49636285Sbrianstatic int
49758028Sbrianbundle_IsSet(struct fdescriptor *d, const fd_set *fdset)
49836285Sbrian{
49936285Sbrian  struct bundle *bundle = descriptor2bundle(d);
50036285Sbrian  struct datalink *dl;
50136285Sbrian
50236285Sbrian  for (dl = bundle->links; dl; dl = dl->next)
50336285Sbrian    if (descriptor_IsSet(&dl->desc, fdset))
50436285Sbrian      return 1;
50536285Sbrian
50643693Sbrian#ifndef NORADIUS
50743693Sbrian  if (descriptor_IsSet(&bundle->radius.desc, fdset))
50843693Sbrian    return 1;
50943693Sbrian#endif
51043693Sbrian
51136285Sbrian  if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
51236285Sbrian    return 1;
51336285Sbrian
51436285Sbrian  return FD_ISSET(bundle->dev.fd, fdset);
51536285Sbrian}
51636285Sbrian
51736285Sbrianstatic void
51858028Sbrianbundle_DescriptorRead(struct fdescriptor *d, struct bundle *bundle,
51936285Sbrian                      const fd_set *fdset)
52036285Sbrian{
52136285Sbrian  struct datalink *dl;
52236285Sbrian
52336285Sbrian  if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
52436285Sbrian    descriptor_Read(&bundle->ncp.mp.server.desc, bundle, fdset);
52536285Sbrian
52636285Sbrian  for (dl = bundle->links; dl; dl = dl->next)
52736285Sbrian    if (descriptor_IsSet(&dl->desc, fdset))
52836285Sbrian      descriptor_Read(&dl->desc, bundle, fdset);
52936285Sbrian
53043693Sbrian#ifndef NORADIUS
53143693Sbrian  if (descriptor_IsSet(&bundle->radius.desc, fdset))
53243693Sbrian    descriptor_Read(&bundle->radius.desc, bundle, fdset);
53343693Sbrian#endif
53443693Sbrian
53536285Sbrian  if (FD_ISSET(bundle->dev.fd, fdset)) {
53636285Sbrian    struct tun_data tun;
53736285Sbrian    int n, pri;
53856413Sbrian    char *data;
53956413Sbrian    size_t sz;
54036285Sbrian
54156413Sbrian    if (bundle->dev.header) {
54256413Sbrian      data = (char *)&tun;
54356413Sbrian      sz = sizeof tun;
54456413Sbrian    } else {
54556413Sbrian      data = tun.data;
54656413Sbrian      sz = sizeof tun.data;
54756413Sbrian    }
54856413Sbrian
54936285Sbrian    /* something to read from tun */
55056413Sbrian
55156413Sbrian    n = read(bundle->dev.fd, data, sz);
55236285Sbrian    if (n < 0) {
55356413Sbrian      log_Printf(LogWARN, "%s: read: %s\n", bundle->dev.Name, strerror(errno));
55436285Sbrian      return;
55536285Sbrian    }
55656413Sbrian
55756413Sbrian    if (bundle->dev.header) {
55856413Sbrian      n -= sz - sizeof tun.data;
55956413Sbrian      if (n <= 0) {
56056413Sbrian        log_Printf(LogERROR, "%s: read: Got only %d bytes of data !\n",
56156413Sbrian                   bundle->dev.Name, n);
56256413Sbrian        return;
56356413Sbrian      }
56456413Sbrian      if (ntohl(tun.family) != AF_INET)
56556413Sbrian        /* XXX: Should be maintaining drop/family counts ! */
56656413Sbrian        return;
56736285Sbrian    }
56836285Sbrian
56936285Sbrian    if (((struct ip *)tun.data)->ip_dst.s_addr ==
57036285Sbrian        bundle->ncp.ipcp.my_ip.s_addr) {
57136285Sbrian      /* we've been asked to send something addressed *to* us :( */
57236285Sbrian      if (Enabled(bundle, OPT_LOOPBACK)) {
57336285Sbrian        pri = PacketCheck(bundle, tun.data, n, &bundle->filter.in);
57436285Sbrian        if (pri >= 0) {
57556413Sbrian          n += sz - sizeof tun.data;
57656413Sbrian          write(bundle->dev.fd, data, n);
57736285Sbrian          log_Printf(LogDEBUG, "Looped back packet addressed to myself\n");
57836285Sbrian        }
57936285Sbrian        return;
58036285Sbrian      } else
58136285Sbrian        log_Printf(LogDEBUG, "Oops - forwarding packet addressed to myself\n");
58236285Sbrian    }
58336285Sbrian
58436285Sbrian    /*
58536285Sbrian     * Process on-demand dialup. Output packets are queued within tunnel
58636285Sbrian     * device until IPCP is opened.
58736285Sbrian     */
58836285Sbrian
58936285Sbrian    if (bundle_Phase(bundle) == PHASE_DEAD) {
59036285Sbrian      /*
59136285Sbrian       * Note, we must be in AUTO mode :-/ otherwise our interface should
59236285Sbrian       * *not* be UP and we can't receive data
59336285Sbrian       */
59436285Sbrian      if ((pri = PacketCheck(bundle, tun.data, n, &bundle->filter.dial)) >= 0)
59537955Sbrian        bundle_Open(bundle, NULL, PHYS_AUTO, 0);
59636285Sbrian      else
59736285Sbrian        /*
59836285Sbrian         * Drop the packet.  If we were to queue it, we'd just end up with
59936285Sbrian         * a pile of timed-out data in our output queue by the time we get
60036285Sbrian         * around to actually dialing.  We'd also prematurely reach the
60136285Sbrian         * threshold at which we stop select()ing to read() the tun
60236285Sbrian         * device - breaking auto-dial.
60336285Sbrian         */
60436285Sbrian        return;
60536285Sbrian    }
60636285Sbrian
60736285Sbrian    pri = PacketCheck(bundle, tun.data, n, &bundle->filter.out);
60846686Sbrian    if (pri >= 0)
60938557Sbrian      ip_Enqueue(&bundle->ncp.ipcp, pri, tun.data, n);
61036285Sbrian  }
61136285Sbrian}
61236285Sbrian
61337141Sbrianstatic int
61458028Sbrianbundle_DescriptorWrite(struct fdescriptor *d, struct bundle *bundle,
61536285Sbrian                       const fd_set *fdset)
61636285Sbrian{
61736285Sbrian  struct datalink *dl;
61837141Sbrian  int result = 0;
61936285Sbrian
62036285Sbrian  /* This is not actually necessary as struct mpserver doesn't Write() */
62136285Sbrian  if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
62236285Sbrian    descriptor_Write(&bundle->ncp.mp.server.desc, bundle, fdset);
62336285Sbrian
62436285Sbrian  for (dl = bundle->links; dl; dl = dl->next)
62536285Sbrian    if (descriptor_IsSet(&dl->desc, fdset))
62637141Sbrian      result += descriptor_Write(&dl->desc, bundle, fdset);
62737141Sbrian
62837141Sbrian  return result;
62936285Sbrian}
63036285Sbrian
63136709Sbrianvoid
63236452Sbrianbundle_LockTun(struct bundle *bundle)
63336452Sbrian{
63436452Sbrian  FILE *lockfile;
63536452Sbrian  char pidfile[MAXPATHLEN];
63636285Sbrian
63736452Sbrian  snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
63836452Sbrian  lockfile = ID0fopen(pidfile, "w");
63936452Sbrian  if (lockfile != NULL) {
64036452Sbrian    fprintf(lockfile, "%d\n", (int)getpid());
64136452Sbrian    fclose(lockfile);
64236452Sbrian  }
64336452Sbrian#ifndef RELEASE_CRUNCH
64436452Sbrian  else
64536452Sbrian    log_Printf(LogERROR, "Warning: Can't create %s: %s\n",
64636452Sbrian               pidfile, strerror(errno));
64736452Sbrian#endif
64836452Sbrian}
64936452Sbrian
65036452Sbrianstatic void
65136452Sbrianbundle_UnlockTun(struct bundle *bundle)
65236452Sbrian{
65336452Sbrian  char pidfile[MAXPATHLEN];
65436452Sbrian
65536452Sbrian  snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
65636452Sbrian  ID0unlink(pidfile);
65736452Sbrian}
65836452Sbrian
65936285Sbrianstruct bundle *
66053298Sbrianbundle_Create(const char *prefix, int type, int unit)
66136285Sbrian{
66247538Sbrian  static struct bundle bundle;		/* there can be only one */
66352396Sbrian  int enoentcount, err, minunit, maxunit;
66440561Sbrian  const char *ifname;
66553241Sbrian#if defined(__FreeBSD__) && !defined(NOKLDLOAD)
66651525Sbrian  int kldtried;
66751525Sbrian#endif
66856413Sbrian#if defined(TUNSIFMODE) || defined(TUNSLMODE) || defined(TUNSIFHEAD)
66945032Sbrian  int iff;
67045032Sbrian#endif
67136285Sbrian
67240561Sbrian  if (bundle.iface != NULL) {	/* Already allocated ! */
67337019Sbrian    log_Printf(LogALERT, "bundle_Create:  There's only one BUNDLE !\n");
67436285Sbrian    return NULL;
67536285Sbrian  }
67636285Sbrian
67752396Sbrian  if (unit == -1) {
67852396Sbrian    minunit = 0;
67952396Sbrian    maxunit = -1;
68052396Sbrian  } else {
68152396Sbrian    minunit = unit;
68252396Sbrian    maxunit = unit + 1;
68352396Sbrian  }
68436285Sbrian  err = ENOENT;
68536285Sbrian  enoentcount = 0;
68653241Sbrian#if defined(__FreeBSD__) && !defined(NOKLDLOAD)
68751525Sbrian  kldtried = 0;
68851525Sbrian#endif
68952396Sbrian  for (bundle.unit = minunit; bundle.unit != maxunit; bundle.unit++) {
69036285Sbrian    snprintf(bundle.dev.Name, sizeof bundle.dev.Name, "%s%d",
69136285Sbrian             prefix, bundle.unit);
69236285Sbrian    bundle.dev.fd = ID0open(bundle.dev.Name, O_RDWR);
69336285Sbrian    if (bundle.dev.fd >= 0)
69436285Sbrian      break;
69536285Sbrian    else if (errno == ENXIO) {
69653241Sbrian#if defined(__FreeBSD__) && !defined(NOKLDLOAD)
69752396Sbrian      if (bundle.unit == minunit && !kldtried++) {
69851525Sbrian        /*
69953241Sbrian	 * Attempt to load the tunnel interface KLD if it isn't loaded
70053241Sbrian	 * already.
70151525Sbrian         */
70253241Sbrian        if (modfind("if_tun") == -1) {
70351525Sbrian          if (ID0kldload("if_tun") != -1) {
70451525Sbrian            bundle.unit--;
70551525Sbrian            continue;
70651525Sbrian          }
70751525Sbrian          log_Printf(LogWARN, "kldload: if_tun: %s\n", strerror(errno));
70851525Sbrian        }
70951525Sbrian      }
71051525Sbrian#endif
71136285Sbrian      err = errno;
71236285Sbrian      break;
71336285Sbrian    } else if (errno == ENOENT) {
71436285Sbrian      if (++enoentcount > 2)
71536285Sbrian	break;
71636285Sbrian    } else
71736285Sbrian      err = errno;
71836285Sbrian  }
71936285Sbrian
72036285Sbrian  if (bundle.dev.fd < 0) {
72152396Sbrian    if (unit == -1)
72252396Sbrian      log_Printf(LogWARN, "No available tunnel devices found (%s)\n",
72352396Sbrian                strerror(err));
72452396Sbrian    else
72552396Sbrian      log_Printf(LogWARN, "%s%d: %s\n", prefix, unit, strerror(err));
72636285Sbrian    return NULL;
72736285Sbrian  }
72836285Sbrian
72936285Sbrian  log_SetTun(bundle.unit);
73036285Sbrian
73140561Sbrian  ifname = strrchr(bundle.dev.Name, '/');
73240561Sbrian  if (ifname == NULL)
73340561Sbrian    ifname = bundle.dev.Name;
73436285Sbrian  else
73540561Sbrian    ifname++;
73636285Sbrian
73740561Sbrian  bundle.iface = iface_Create(ifname);
73840561Sbrian  if (bundle.iface == NULL) {
73940561Sbrian    close(bundle.dev.fd);
74040561Sbrian    return NULL;
74140561Sbrian  }
74240561Sbrian
74345032Sbrian#ifdef TUNSIFMODE
74445032Sbrian  /* Make sure we're POINTOPOINT */
74545032Sbrian  iff = IFF_POINTOPOINT;
74645032Sbrian  if (ID0ioctl(bundle.dev.fd, TUNSIFMODE, &iff) < 0)
74745032Sbrian    log_Printf(LogERROR, "bundle_Create: ioctl(TUNSIFMODE): %s\n",
74845032Sbrian	       strerror(errno));
74945032Sbrian#endif
75045032Sbrian
75148103Sbrian#ifdef TUNSLMODE
75256413Sbrian  /* Make sure we're not prepending sockaddrs */
75348103Sbrian  iff = 0;
75448103Sbrian  if (ID0ioctl(bundle.dev.fd, TUNSLMODE, &iff) < 0)
75548103Sbrian    log_Printf(LogERROR, "bundle_Create: ioctl(TUNSLMODE): %s\n",
75648103Sbrian	       strerror(errno));
75748103Sbrian#endif
75848103Sbrian
75956413Sbrian#ifdef TUNSIFHEAD
76056413Sbrian  /* We want the address family please ! */
76156413Sbrian  iff = 1;
76256413Sbrian  if (ID0ioctl(bundle.dev.fd, TUNSIFHEAD, &iff) < 0) {
76356413Sbrian    log_Printf(LogERROR, "bundle_Create: ioctl(TUNSIFHEAD): %s\n",
76456413Sbrian	       strerror(errno));
76556413Sbrian    bundle.dev.header = 0;
76656413Sbrian  } else
76756413Sbrian    bundle.dev.header = 1;
76856413Sbrian#else
76956413Sbrian#ifdef __OpenBSD__
77056413Sbrian  /* Always present for OpenBSD */
77156413Sbrian  bundle.dev.header = 1;
77256413Sbrian#else
77356413Sbrian  /*
77456413Sbrian   * If TUNSIFHEAD isn't available and we're not OpenBSD, assume
77556413Sbrian   * everything's AF_INET (hopefully the tun device won't pass us
77656413Sbrian   * anything else !).
77756413Sbrian   */
77856413Sbrian  bundle.dev.header = 0;
77956413Sbrian#endif
78056413Sbrian#endif
78156413Sbrian
78247538Sbrian  if (!iface_SetFlags(bundle.iface, IFF_UP)) {
78340561Sbrian    iface_Destroy(bundle.iface);
78440561Sbrian    bundle.iface = NULL;
78536285Sbrian    close(bundle.dev.fd);
78636285Sbrian    return NULL;
78736285Sbrian  }
78836285Sbrian
78940561Sbrian  log_Printf(LogPHASE, "Using interface: %s\n", ifname);
79036285Sbrian
79149434Sbrian  bundle.bandwidth = 0;
79236285Sbrian  bundle.routing_seq = 0;
79336285Sbrian  bundle.phase = PHASE_DEAD;
79436285Sbrian  bundle.CleaningUp = 0;
79550059Sbrian  bundle.NatEnabled = 0;
79636285Sbrian
79736285Sbrian  bundle.fsm.LayerStart = bundle_LayerStart;
79836285Sbrian  bundle.fsm.LayerUp = bundle_LayerUp;
79936285Sbrian  bundle.fsm.LayerDown = bundle_LayerDown;
80036285Sbrian  bundle.fsm.LayerFinish = bundle_LayerFinish;
80136285Sbrian  bundle.fsm.object = &bundle;
80236285Sbrian
80349978Sbrian  bundle.cfg.idle.timeout = NCP_IDLE_TIMEOUT;
80449978Sbrian  bundle.cfg.idle.min_timeout = 0;
80536285Sbrian  *bundle.cfg.auth.name = '\0';
80636285Sbrian  *bundle.cfg.auth.key = '\0';
80736285Sbrian  bundle.cfg.opt = OPT_SROUTES | OPT_IDCHECK | OPT_LOOPBACK |
80836285Sbrian                   OPT_THROUGHPUT | OPT_UTMP;
80936285Sbrian  *bundle.cfg.label = '\0';
81036285Sbrian  bundle.cfg.mtu = DEF_MTU;
81161534Sbrian  bundle.cfg.ifqueue = DEF_IFQUEUE;
81238544Sbrian  bundle.cfg.choked.timeout = CHOKED_TIMEOUT;
81336928Sbrian  bundle.phys_type.all = type;
81436928Sbrian  bundle.phys_type.open = 0;
81549978Sbrian  bundle.upat = 0;
81636285Sbrian
81736285Sbrian  bundle.links = datalink_Create("deflink", &bundle, type);
81836285Sbrian  if (bundle.links == NULL) {
81937019Sbrian    log_Printf(LogALERT, "Cannot create data link: %s\n", strerror(errno));
82040561Sbrian    iface_Destroy(bundle.iface);
82140561Sbrian    bundle.iface = NULL;
82236285Sbrian    close(bundle.dev.fd);
82336285Sbrian    return NULL;
82436285Sbrian  }
82536285Sbrian
82636285Sbrian  bundle.desc.type = BUNDLE_DESCRIPTOR;
82736285Sbrian  bundle.desc.UpdateSet = bundle_UpdateSet;
82836285Sbrian  bundle.desc.IsSet = bundle_IsSet;
82936285Sbrian  bundle.desc.Read = bundle_DescriptorRead;
83036285Sbrian  bundle.desc.Write = bundle_DescriptorWrite;
83136285Sbrian
83236285Sbrian  mp_Init(&bundle.ncp.mp, &bundle);
83336285Sbrian
83436285Sbrian  /* Send over the first physical link by default */
83536285Sbrian  ipcp_Init(&bundle.ncp.ipcp, &bundle, &bundle.links->physical->link,
83636285Sbrian            &bundle.fsm);
83736285Sbrian
83836285Sbrian  memset(&bundle.filter, '\0', sizeof bundle.filter);
83936285Sbrian  bundle.filter.in.fragok = bundle.filter.in.logok = 1;
84036285Sbrian  bundle.filter.in.name = "IN";
84136285Sbrian  bundle.filter.out.fragok = bundle.filter.out.logok = 1;
84236285Sbrian  bundle.filter.out.name = "OUT";
84336285Sbrian  bundle.filter.dial.name = "DIAL";
84436285Sbrian  bundle.filter.dial.logok = 1;
84536285Sbrian  bundle.filter.alive.name = "ALIVE";
84636285Sbrian  bundle.filter.alive.logok = 1;
84749140Sbrian  {
84849140Sbrian    int	i;
84949140Sbrian    for (i = 0; i < MAXFILTERS; i++) {
85049140Sbrian        bundle.filter.in.rule[i].f_action = A_NONE;
85149140Sbrian        bundle.filter.out.rule[i].f_action = A_NONE;
85249140Sbrian        bundle.filter.dial.rule[i].f_action = A_NONE;
85349140Sbrian        bundle.filter.alive.rule[i].f_action = A_NONE;
85449140Sbrian    }
85549140Sbrian  }
85636285Sbrian  memset(&bundle.idle.timer, '\0', sizeof bundle.idle.timer);
85736285Sbrian  bundle.idle.done = 0;
85836285Sbrian  bundle.notify.fd = -1;
85938544Sbrian  memset(&bundle.choked.timer, '\0', sizeof bundle.choked.timer);
86043313Sbrian#ifndef NORADIUS
86143313Sbrian  radius_Init(&bundle.radius);
86243313Sbrian#endif
86336285Sbrian
86436285Sbrian  /* Clean out any leftover crud */
86540561Sbrian  iface_Clear(bundle.iface, IFACE_CLEAR_ALL);
86636285Sbrian
86736452Sbrian  bundle_LockTun(&bundle);
86836452Sbrian
86936285Sbrian  return &bundle;
87036285Sbrian}
87136285Sbrian
87236285Sbrianstatic void
87336285Sbrianbundle_DownInterface(struct bundle *bundle)
87436285Sbrian{
87536285Sbrian  route_IfDelete(bundle, 1);
87647538Sbrian  iface_ClearFlags(bundle->iface, IFF_UP);
87736285Sbrian}
87836285Sbrian
87936285Sbrianvoid
88036285Sbrianbundle_Destroy(struct bundle *bundle)
88136285Sbrian{
88236285Sbrian  struct datalink *dl;
88336285Sbrian
88436285Sbrian  /*
88536285Sbrian   * Clean up the interface.  We don't need to timer_Stop()s, mp_Down(),
88636285Sbrian   * ipcp_CleanInterface() and bundle_DownInterface() unless we're getting
88758038Sbrian   * out under exceptional conditions such as a descriptor exception.
88836285Sbrian   */
88936285Sbrian  timer_Stop(&bundle->idle.timer);
89038544Sbrian  timer_Stop(&bundle->choked.timer);
89136285Sbrian  mp_Down(&bundle->ncp.mp);
89236285Sbrian  ipcp_CleanInterface(&bundle->ncp.ipcp);
89336285Sbrian  bundle_DownInterface(bundle);
89436452Sbrian
89543313Sbrian#ifndef NORADIUS
89643313Sbrian  /* Tell the radius server the bad news */
89743313Sbrian  radius_Destroy(&bundle->radius);
89843313Sbrian#endif
89943313Sbrian
90036285Sbrian  /* Again, these are all DATALINK_CLOSED unless we're abending */
90136285Sbrian  dl = bundle->links;
90236285Sbrian  while (dl)
90336285Sbrian    dl = datalink_Destroy(dl);
90436285Sbrian
90550867Sbrian  ipcp_Destroy(&bundle->ncp.ipcp);
90650867Sbrian
90736452Sbrian  close(bundle->dev.fd);
90836452Sbrian  bundle_UnlockTun(bundle);
90936452Sbrian
91036285Sbrian  /* In case we never made PHASE_NETWORK */
91136285Sbrian  bundle_Notify(bundle, EX_ERRDEAD);
91236285Sbrian
91340561Sbrian  iface_Destroy(bundle->iface);
91440561Sbrian  bundle->iface = NULL;
91536285Sbrian}
91636285Sbrian
91736285Sbrianstruct rtmsg {
91836285Sbrian  struct rt_msghdr m_rtm;
91936285Sbrian  char m_space[64];
92036285Sbrian};
92136285Sbrian
92236285Sbrianint
92336285Sbrianbundle_SetRoute(struct bundle *bundle, int cmd, struct in_addr dst,
92437927Sbrian                struct in_addr gateway, struct in_addr mask, int bang, int ssh)
92536285Sbrian{
92636285Sbrian  struct rtmsg rtmes;
92736285Sbrian  int s, nb, wb;
92836285Sbrian  char *cp;
92936285Sbrian  const char *cmdstr;
93036285Sbrian  struct sockaddr_in rtdata;
93136285Sbrian  int result = 1;
93236285Sbrian
93336285Sbrian  if (bang)
93436285Sbrian    cmdstr = (cmd == RTM_ADD ? "Add!" : "Delete!");
93536285Sbrian  else
93636285Sbrian    cmdstr = (cmd == RTM_ADD ? "Add" : "Delete");
93736285Sbrian  s = ID0socket(PF_ROUTE, SOCK_RAW, 0);
93836285Sbrian  if (s < 0) {
93936285Sbrian    log_Printf(LogERROR, "bundle_SetRoute: socket(): %s\n", strerror(errno));
94036285Sbrian    return result;
94136285Sbrian  }
94236285Sbrian  memset(&rtmes, '\0', sizeof rtmes);
94336285Sbrian  rtmes.m_rtm.rtm_version = RTM_VERSION;
94436285Sbrian  rtmes.m_rtm.rtm_type = cmd;
94536285Sbrian  rtmes.m_rtm.rtm_addrs = RTA_DST;
94636285Sbrian  rtmes.m_rtm.rtm_seq = ++bundle->routing_seq;
94736285Sbrian  rtmes.m_rtm.rtm_pid = getpid();
94836285Sbrian  rtmes.m_rtm.rtm_flags = RTF_UP | RTF_GATEWAY | RTF_STATIC;
94936285Sbrian
95040665Sbrian  if (cmd == RTM_ADD || cmd == RTM_CHANGE) {
95140665Sbrian    if (bundle->ncp.ipcp.cfg.sendpipe > 0) {
95240665Sbrian      rtmes.m_rtm.rtm_rmx.rmx_sendpipe = bundle->ncp.ipcp.cfg.sendpipe;
95340665Sbrian      rtmes.m_rtm.rtm_inits |= RTV_SPIPE;
95440665Sbrian    }
95540665Sbrian    if (bundle->ncp.ipcp.cfg.recvpipe > 0) {
95640665Sbrian      rtmes.m_rtm.rtm_rmx.rmx_recvpipe = bundle->ncp.ipcp.cfg.recvpipe;
95740665Sbrian      rtmes.m_rtm.rtm_inits |= RTV_RPIPE;
95840665Sbrian    }
95940665Sbrian  }
96040665Sbrian
96136285Sbrian  memset(&rtdata, '\0', sizeof rtdata);
96236285Sbrian  rtdata.sin_len = sizeof rtdata;
96336285Sbrian  rtdata.sin_family = AF_INET;
96436285Sbrian  rtdata.sin_port = 0;
96536285Sbrian  rtdata.sin_addr = dst;
96636285Sbrian
96736285Sbrian  cp = rtmes.m_space;
96836285Sbrian  memcpy(cp, &rtdata, rtdata.sin_len);
96936285Sbrian  cp += rtdata.sin_len;
97036285Sbrian  if (cmd == RTM_ADD) {
97136285Sbrian    if (gateway.s_addr == INADDR_ANY) {
97242321Sbrian      if (!ssh)
97342321Sbrian        log_Printf(LogERROR, "bundle_SetRoute: Cannot add a route with"
97442321Sbrian                   " destination 0.0.0.0\n");
97540561Sbrian      close(s);
97640561Sbrian      return result;
97736285Sbrian    } else {
97836285Sbrian      rtdata.sin_addr = gateway;
97936285Sbrian      memcpy(cp, &rtdata, rtdata.sin_len);
98036285Sbrian      cp += rtdata.sin_len;
98136285Sbrian      rtmes.m_rtm.rtm_addrs |= RTA_GATEWAY;
98236285Sbrian    }
98336285Sbrian  }
98436285Sbrian
98536285Sbrian  if (dst.s_addr == INADDR_ANY)
98636285Sbrian    mask.s_addr = INADDR_ANY;
98736285Sbrian
98836285Sbrian  if (cmd == RTM_ADD || dst.s_addr == INADDR_ANY) {
98936285Sbrian    rtdata.sin_addr = mask;
99036285Sbrian    memcpy(cp, &rtdata, rtdata.sin_len);
99136285Sbrian    cp += rtdata.sin_len;
99236285Sbrian    rtmes.m_rtm.rtm_addrs |= RTA_NETMASK;
99336285Sbrian  }
99436285Sbrian
99536285Sbrian  nb = cp - (char *) &rtmes;
99636285Sbrian  rtmes.m_rtm.rtm_msglen = nb;
99736285Sbrian  wb = ID0write(s, &rtmes, nb);
99836285Sbrian  if (wb < 0) {
99936285Sbrian    log_Printf(LogTCPIP, "bundle_SetRoute failure:\n");
100036285Sbrian    log_Printf(LogTCPIP, "bundle_SetRoute:  Cmd = %s\n", cmdstr);
100136285Sbrian    log_Printf(LogTCPIP, "bundle_SetRoute:  Dst = %s\n", inet_ntoa(dst));
100253684Sbrian    log_Printf(LogTCPIP, "bundle_SetRoute:  Gateway = %s\n",
100353684Sbrian               inet_ntoa(gateway));
100436285Sbrian    log_Printf(LogTCPIP, "bundle_SetRoute:  Mask = %s\n", inet_ntoa(mask));
100536285Sbrianfailed:
100636285Sbrian    if (cmd == RTM_ADD && (rtmes.m_rtm.rtm_errno == EEXIST ||
100736285Sbrian                           (rtmes.m_rtm.rtm_errno == 0 && errno == EEXIST))) {
100836285Sbrian      if (!bang) {
100936285Sbrian        log_Printf(LogWARN, "Add route failed: %s already exists\n",
101040665Sbrian		  dst.s_addr == 0 ? "default" : inet_ntoa(dst));
101136285Sbrian        result = 0;	/* Don't add to our dynamic list */
101236285Sbrian      } else {
101336285Sbrian        rtmes.m_rtm.rtm_type = cmd = RTM_CHANGE;
101436285Sbrian        if ((wb = ID0write(s, &rtmes, nb)) < 0)
101536285Sbrian          goto failed;
101636285Sbrian      }
101736285Sbrian    } else if (cmd == RTM_DELETE &&
101836285Sbrian             (rtmes.m_rtm.rtm_errno == ESRCH ||
101936285Sbrian              (rtmes.m_rtm.rtm_errno == 0 && errno == ESRCH))) {
102036285Sbrian      if (!bang)
102136285Sbrian        log_Printf(LogWARN, "Del route failed: %s: Non-existent\n",
102236285Sbrian                  inet_ntoa(dst));
102337927Sbrian    } else if (rtmes.m_rtm.rtm_errno == 0) {
102437927Sbrian      if (!ssh || errno != ENETUNREACH)
102537927Sbrian        log_Printf(LogWARN, "%s route failed: %s: errno: %s\n", cmdstr,
102637927Sbrian                   inet_ntoa(dst), strerror(errno));
102737927Sbrian    } else
102836285Sbrian      log_Printf(LogWARN, "%s route failed: %s: %s\n",
102937927Sbrian		 cmdstr, inet_ntoa(dst), strerror(rtmes.m_rtm.rtm_errno));
103036285Sbrian  }
103136285Sbrian  log_Printf(LogDEBUG, "wrote %d: cmd = %s, dst = %x, gateway = %x\n",
103236285Sbrian            wb, cmdstr, (unsigned)dst.s_addr, (unsigned)gateway.s_addr);
103336285Sbrian  close(s);
103436285Sbrian
103536285Sbrian  return result;
103636285Sbrian}
103736285Sbrian
103836285Sbrianvoid
103936285Sbrianbundle_LinkClosed(struct bundle *bundle, struct datalink *dl)
104036285Sbrian{
104136285Sbrian  /*
104236285Sbrian   * Our datalink has closed.
104336285Sbrian   * CleanDatalinks() (called from DoLoop()) will remove closed
104453830Sbrian   * BACKGROUND, FOREGROUND and DIRECT links.
104536285Sbrian   * If it's the last data link, enter phase DEAD.
104636285Sbrian   *
104736285Sbrian   * NOTE: dl may not be in our list (bundle_SendDatalink()) !
104836285Sbrian   */
104936285Sbrian
105036285Sbrian  struct datalink *odl;
105136285Sbrian  int other_links;
105236285Sbrian
105338200Sbrian  log_SetTtyCommandMode(dl);
105438200Sbrian
105536285Sbrian  other_links = 0;
105636285Sbrian  for (odl = bundle->links; odl; odl = odl->next)
105736285Sbrian    if (odl != dl && odl->state != DATALINK_CLOSED)
105836285Sbrian      other_links++;
105936285Sbrian
106036285Sbrian  if (!other_links) {
106136465Sbrian    if (dl->physical->type != PHYS_AUTO)	/* Not in -auto mode */
106236285Sbrian      bundle_DownInterface(bundle);
106337060Sbrian    fsm2initial(&bundle->ncp.ipcp.fsm);
106436285Sbrian    bundle_NewPhase(bundle, PHASE_DEAD);
106536314Sbrian    bundle_StopIdleTimer(bundle);
106649434Sbrian  }
106736285Sbrian}
106836285Sbrian
106936285Sbrianvoid
107037955Sbrianbundle_Open(struct bundle *bundle, const char *name, int mask, int force)
107136285Sbrian{
107236285Sbrian  /*
107336285Sbrian   * Please open the given datalink, or all if name == NULL
107436285Sbrian   */
107536285Sbrian  struct datalink *dl;
107636285Sbrian
107736285Sbrian  for (dl = bundle->links; dl; dl = dl->next)
107836285Sbrian    if (name == NULL || !strcasecmp(dl->name, name)) {
107937955Sbrian      if ((mask & dl->physical->type) &&
108037955Sbrian          (dl->state == DATALINK_CLOSED ||
108137955Sbrian           (force && dl->state == DATALINK_OPENING &&
108260945Sbrian            dl->dial.timer.state == TIMER_RUNNING) ||
108360945Sbrian           dl->state == DATALINK_READY)) {
108460945Sbrian        timer_Stop(&dl->dial.timer);	/* We're finished with this */
108536285Sbrian        datalink_Up(dl, 1, 1);
108649434Sbrian        if (mask & PHYS_AUTO)
108760945Sbrian          break;			/* Only one AUTO link at a time */
108836285Sbrian      }
108936285Sbrian      if (name != NULL)
109036285Sbrian        break;
109136285Sbrian    }
109236285Sbrian}
109336285Sbrian
109436285Sbrianstruct datalink *
109536285Sbrianbundle2datalink(struct bundle *bundle, const char *name)
109636285Sbrian{
109736285Sbrian  struct datalink *dl;
109836285Sbrian
109936285Sbrian  if (name != NULL) {
110036285Sbrian    for (dl = bundle->links; dl; dl = dl->next)
110136285Sbrian      if (!strcasecmp(dl->name, name))
110236285Sbrian        return dl;
110336285Sbrian  } else if (bundle->links && !bundle->links->next)
110436285Sbrian    return bundle->links;
110536285Sbrian
110636285Sbrian  return NULL;
110736285Sbrian}
110836285Sbrian
110936285Sbrianint
111036285Sbrianbundle_ShowLinks(struct cmdargs const *arg)
111136285Sbrian{
111236285Sbrian  struct datalink *dl;
111349434Sbrian  struct pppThroughput *t;
111449434Sbrian  int secs;
111536285Sbrian
111636285Sbrian  for (dl = arg->bundle->links; dl; dl = dl->next) {
111736316Sbrian    prompt_Printf(arg->prompt, "Name: %s [%s, %s]",
111836316Sbrian                  dl->name, mode2Nam(dl->physical->type), datalink_State(dl));
111936285Sbrian    if (dl->physical->link.throughput.rolling && dl->state == DATALINK_OPEN)
112049582Sbrian      prompt_Printf(arg->prompt, " bandwidth %d, %llu bps (%llu bytes/sec)",
112149434Sbrian                    dl->mp.bandwidth ? dl->mp.bandwidth :
112249434Sbrian                                       physical_GetSpeed(dl->physical),
112349434Sbrian                    dl->physical->link.throughput.OctetsPerSecond * 8,
112436285Sbrian                    dl->physical->link.throughput.OctetsPerSecond);
112536285Sbrian    prompt_Printf(arg->prompt, "\n");
112636285Sbrian  }
112736285Sbrian
112849434Sbrian  t = &arg->bundle->ncp.mp.link.throughput;
112949434Sbrian  secs = t->downtime ? 0 : throughput_uptime(t);
113049434Sbrian  if (secs > t->SamplePeriod)
113149434Sbrian    secs = t->SamplePeriod;
113249434Sbrian  if (secs)
113349582Sbrian    prompt_Printf(arg->prompt, "Currently averaging %llu bps (%llu bytes/sec)"
113449434Sbrian                  " over the last %d secs\n", t->OctetsPerSecond * 8,
113549434Sbrian                  t->OctetsPerSecond, secs);
113649434Sbrian
113736285Sbrian  return 0;
113836285Sbrian}
113936285Sbrian
114036285Sbrianstatic const char *
114136285Sbrianoptval(struct bundle *bundle, int bit)
114236285Sbrian{
114336285Sbrian  return (bundle->cfg.opt & bit) ? "enabled" : "disabled";
114436285Sbrian}
114536285Sbrian
114636285Sbrianint
114736285Sbrianbundle_ShowStatus(struct cmdargs const *arg)
114836285Sbrian{
114936285Sbrian  int remaining;
115036285Sbrian
115136285Sbrian  prompt_Printf(arg->prompt, "Phase %s\n", bundle_PhaseName(arg->bundle));
115236285Sbrian  prompt_Printf(arg->prompt, " Device:        %s\n", arg->bundle->dev.Name);
115349978Sbrian  prompt_Printf(arg->prompt, " Interface:     %s @ %lubps",
115449434Sbrian                arg->bundle->iface->name, arg->bundle->bandwidth);
115536285Sbrian
115649978Sbrian  if (arg->bundle->upat) {
115749978Sbrian    int secs = time(NULL) - arg->bundle->upat;
115849978Sbrian
115949978Sbrian    prompt_Printf(arg->prompt, ", up time %d:%02d:%02d", secs / 3600,
116049978Sbrian                  (secs / 60) % 60, secs % 60);
116149978Sbrian  }
116261800Sbrian  prompt_Printf(arg->prompt, "\n Queued:        %lu of %u\n",
116361534Sbrian                ip_QueueLen(&arg->bundle->ncp.ipcp), arg->bundle->cfg.ifqueue);
116449978Sbrian
116561534Sbrian  prompt_Printf(arg->prompt, "\nDefaults:\n");
116636285Sbrian  prompt_Printf(arg->prompt, " Label:         %s\n", arg->bundle->cfg.label);
116736285Sbrian  prompt_Printf(arg->prompt, " Auth name:     %s\n",
116836285Sbrian                arg->bundle->cfg.auth.name);
116936285Sbrian
117038544Sbrian  prompt_Printf(arg->prompt, " Choked Timer:  %ds\n",
117138544Sbrian                arg->bundle->cfg.choked.timeout);
117243313Sbrian
117343313Sbrian#ifndef NORADIUS
117443313Sbrian  radius_Show(&arg->bundle->radius, arg->prompt);
117543313Sbrian#endif
117643313Sbrian
117736285Sbrian  prompt_Printf(arg->prompt, " Idle Timer:    ");
117849978Sbrian  if (arg->bundle->cfg.idle.timeout) {
117949978Sbrian    prompt_Printf(arg->prompt, "%ds", arg->bundle->cfg.idle.timeout);
118049978Sbrian    if (arg->bundle->cfg.idle.min_timeout)
118149978Sbrian      prompt_Printf(arg->prompt, ", min %ds",
118249978Sbrian                    arg->bundle->cfg.idle.min_timeout);
118336285Sbrian    remaining = bundle_RemainingIdleTime(arg->bundle);
118436285Sbrian    if (remaining != -1)
118536285Sbrian      prompt_Printf(arg->prompt, " (%ds remaining)", remaining);
118636285Sbrian    prompt_Printf(arg->prompt, "\n");
118736285Sbrian  } else
118836285Sbrian    prompt_Printf(arg->prompt, "disabled\n");
118936285Sbrian  prompt_Printf(arg->prompt, " MTU:           ");
119036285Sbrian  if (arg->bundle->cfg.mtu)
119136285Sbrian    prompt_Printf(arg->prompt, "%d\n", arg->bundle->cfg.mtu);
119236285Sbrian  else
119336285Sbrian    prompt_Printf(arg->prompt, "unspecified\n");
119436285Sbrian
119540665Sbrian  prompt_Printf(arg->prompt, " sendpipe:      ");
119640665Sbrian  if (arg->bundle->ncp.ipcp.cfg.sendpipe > 0)
119749434Sbrian    prompt_Printf(arg->prompt, "%-20ld", arg->bundle->ncp.ipcp.cfg.sendpipe);
119840665Sbrian  else
119949434Sbrian    prompt_Printf(arg->prompt, "unspecified         ");
120040665Sbrian  prompt_Printf(arg->prompt, " recvpipe:      ");
120140665Sbrian  if (arg->bundle->ncp.ipcp.cfg.recvpipe > 0)
120240665Sbrian    prompt_Printf(arg->prompt, "%ld\n", arg->bundle->ncp.ipcp.cfg.recvpipe);
120340665Sbrian  else
120440665Sbrian    prompt_Printf(arg->prompt, "unspecified\n");
120540665Sbrian
120649434Sbrian  prompt_Printf(arg->prompt, " Sticky Routes: %-20.20s",
120736285Sbrian                optval(arg->bundle, OPT_SROUTES));
120836285Sbrian  prompt_Printf(arg->prompt, " ID check:      %s\n",
120936285Sbrian                optval(arg->bundle, OPT_IDCHECK));
121049434Sbrian  prompt_Printf(arg->prompt, " Keep-Session:  %-20.20s",
121147689Sbrian                optval(arg->bundle, OPT_KEEPSESSION));
121236285Sbrian  prompt_Printf(arg->prompt, " Loopback:      %s\n",
121336285Sbrian                optval(arg->bundle, OPT_LOOPBACK));
121449434Sbrian  prompt_Printf(arg->prompt, " PasswdAuth:    %-20.20s",
121536285Sbrian                optval(arg->bundle, OPT_PASSWDAUTH));
121636285Sbrian  prompt_Printf(arg->prompt, " Proxy:         %s\n",
121736285Sbrian                optval(arg->bundle, OPT_PROXY));
121849434Sbrian  prompt_Printf(arg->prompt, " Proxyall:      %-20.20s",
121940665Sbrian                optval(arg->bundle, OPT_PROXYALL));
122036285Sbrian  prompt_Printf(arg->prompt, " Throughput:    %s\n",
122136285Sbrian                optval(arg->bundle, OPT_THROUGHPUT));
122249434Sbrian  prompt_Printf(arg->prompt, " Utmp Logging:  %-20.20s",
122336285Sbrian                optval(arg->bundle, OPT_UTMP));
122440561Sbrian  prompt_Printf(arg->prompt, " Iface-Alias:   %s\n",
122540561Sbrian                optval(arg->bundle, OPT_IFACEALIAS));
122636285Sbrian
122736285Sbrian  return 0;
122836285Sbrian}
122936285Sbrian
123036285Sbrianstatic void
123136285Sbrianbundle_IdleTimeout(void *v)
123236285Sbrian{
123336285Sbrian  struct bundle *bundle = (struct bundle *)v;
123436285Sbrian
123559084Sbrian  log_Printf(LogPHASE, "Idle timer expired\n");
123636285Sbrian  bundle_StopIdleTimer(bundle);
123737007Sbrian  bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
123836285Sbrian}
123936285Sbrian
124036285Sbrian/*
124136285Sbrian *  Start Idle timer. If timeout is reached, we call bundle_Close() to
124236285Sbrian *  close LCP and link.
124336285Sbrian */
124436285Sbrianvoid
124536285Sbrianbundle_StartIdleTimer(struct bundle *bundle)
124636285Sbrian{
124736285Sbrian  timer_Stop(&bundle->idle.timer);
124836928Sbrian  if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) !=
124949978Sbrian      bundle->phys_type.open && bundle->cfg.idle.timeout) {
125049978Sbrian    int secs;
125149978Sbrian
125249978Sbrian    secs = bundle->cfg.idle.timeout;
125349978Sbrian    if (bundle->cfg.idle.min_timeout > secs && bundle->upat) {
125449978Sbrian      int up = time(NULL) - bundle->upat;
125549978Sbrian
125649978Sbrian      if ((long long)bundle->cfg.idle.min_timeout - up > (long long)secs)
125749978Sbrian        secs = bundle->cfg.idle.min_timeout - up;
125849978Sbrian    }
125936285Sbrian    bundle->idle.timer.func = bundle_IdleTimeout;
126036285Sbrian    bundle->idle.timer.name = "idle";
126149978Sbrian    bundle->idle.timer.load = secs * SECTICKS;
126236285Sbrian    bundle->idle.timer.arg = bundle;
126336285Sbrian    timer_Start(&bundle->idle.timer);
126449978Sbrian    bundle->idle.done = time(NULL) + secs;
126536285Sbrian  }
126636285Sbrian}
126736285Sbrian
126836285Sbrianvoid
126949978Sbrianbundle_SetIdleTimer(struct bundle *bundle, int timeout, int min_timeout)
127036285Sbrian{
127149978Sbrian  bundle->cfg.idle.timeout = timeout;
127249978Sbrian  if (min_timeout >= 0)
127349978Sbrian    bundle->cfg.idle.min_timeout = min_timeout;
127436285Sbrian  if (bundle_LinkIsUp(bundle))
127536285Sbrian    bundle_StartIdleTimer(bundle);
127636285Sbrian}
127736285Sbrian
127836285Sbrianvoid
127936285Sbrianbundle_StopIdleTimer(struct bundle *bundle)
128036285Sbrian{
128136285Sbrian  timer_Stop(&bundle->idle.timer);
128236285Sbrian  bundle->idle.done = 0;
128336285Sbrian}
128436285Sbrian
128536285Sbrianstatic int
128636285Sbrianbundle_RemainingIdleTime(struct bundle *bundle)
128736285Sbrian{
128836285Sbrian  if (bundle->idle.done)
128936285Sbrian    return bundle->idle.done - time(NULL);
129036285Sbrian  return -1;
129136285Sbrian}
129236285Sbrian
129336285Sbrianint
129436285Sbrianbundle_IsDead(struct bundle *bundle)
129536285Sbrian{
129636285Sbrian  return !bundle->links || (bundle->phase == PHASE_DEAD && bundle->CleaningUp);
129736285Sbrian}
129836285Sbrian
129936285Sbrianstatic struct datalink *
130036285Sbrianbundle_DatalinkLinkout(struct bundle *bundle, struct datalink *dl)
130136285Sbrian{
130236285Sbrian  struct datalink **dlp;
130336285Sbrian
130436314Sbrian  for (dlp = &bundle->links; *dlp; dlp = &(*dlp)->next)
130536314Sbrian    if (*dlp == dl) {
130636314Sbrian      *dlp = dl->next;
130736314Sbrian      dl->next = NULL;
130836314Sbrian      bundle_LinksRemoved(bundle);
130936314Sbrian      return dl;
131036314Sbrian    }
131136285Sbrian
131236285Sbrian  return NULL;
131336285Sbrian}
131436285Sbrian
131536285Sbrianstatic void
131636285Sbrianbundle_DatalinkLinkin(struct bundle *bundle, struct datalink *dl)
131736285Sbrian{
131836285Sbrian  struct datalink **dlp = &bundle->links;
131936285Sbrian
132036285Sbrian  while (*dlp)
132136285Sbrian    dlp = &(*dlp)->next;
132236285Sbrian
132336285Sbrian  *dlp = dl;
132436285Sbrian  dl->next = NULL;
132536285Sbrian
132636285Sbrian  bundle_LinkAdded(bundle, dl);
132749434Sbrian  mp_CheckAutoloadTimer(&bundle->ncp.mp);
132836285Sbrian}
132936285Sbrian
133036285Sbrianvoid
133136285Sbrianbundle_CleanDatalinks(struct bundle *bundle)
133236285Sbrian{
133336285Sbrian  struct datalink **dlp = &bundle->links;
133436285Sbrian  int found = 0;
133536285Sbrian
133636285Sbrian  while (*dlp)
133736285Sbrian    if ((*dlp)->state == DATALINK_CLOSED &&
133853830Sbrian        (*dlp)->physical->type &
133953830Sbrian        (PHYS_DIRECT|PHYS_BACKGROUND|PHYS_FOREGROUND)) {
134036285Sbrian      *dlp = datalink_Destroy(*dlp);
134136285Sbrian      found++;
134236285Sbrian    } else
134336285Sbrian      dlp = &(*dlp)->next;
134436285Sbrian
134536285Sbrian  if (found)
134636285Sbrian    bundle_LinksRemoved(bundle);
134736285Sbrian}
134836285Sbrian
134936285Sbrianint
135036285Sbrianbundle_DatalinkClone(struct bundle *bundle, struct datalink *dl,
135136285Sbrian                     const char *name)
135236285Sbrian{
135336285Sbrian  if (bundle2datalink(bundle, name)) {
135436285Sbrian    log_Printf(LogWARN, "Clone: %s: name already exists\n", name);
135536285Sbrian    return 0;
135636285Sbrian  }
135736285Sbrian
135836285Sbrian  bundle_DatalinkLinkin(bundle, datalink_Clone(dl, name));
135936285Sbrian  return 1;
136036285Sbrian}
136136285Sbrian
136236285Sbrianvoid
136336285Sbrianbundle_DatalinkRemove(struct bundle *bundle, struct datalink *dl)
136436285Sbrian{
136536285Sbrian  dl = bundle_DatalinkLinkout(bundle, dl);
136636285Sbrian  if (dl)
136736285Sbrian    datalink_Destroy(dl);
136836285Sbrian}
136936285Sbrian
137036285Sbrianvoid
137136285Sbrianbundle_SetLabel(struct bundle *bundle, const char *label)
137236285Sbrian{
137336285Sbrian  if (label)
137436285Sbrian    strncpy(bundle->cfg.label, label, sizeof bundle->cfg.label - 1);
137536285Sbrian  else
137636285Sbrian    *bundle->cfg.label = '\0';
137736285Sbrian}
137836285Sbrian
137936285Sbrianconst char *
138036285Sbrianbundle_GetLabel(struct bundle *bundle)
138136285Sbrian{
138236285Sbrian  return *bundle->cfg.label ? bundle->cfg.label : NULL;
138336285Sbrian}
138436285Sbrian
138553684Sbrianint
138653684Sbrianbundle_LinkSize()
138753684Sbrian{
138853684Sbrian  struct iovec iov[SCATTER_SEGMENTS];
138953684Sbrian  int niov, expect, f;
139053684Sbrian
139153684Sbrian  iov[0].iov_len = strlen(Version) + 1;
139253684Sbrian  iov[0].iov_base = NULL;
139353684Sbrian  niov = 1;
139453684Sbrian  if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
139553684Sbrian    log_Printf(LogERROR, "Cannot determine space required for link\n");
139653684Sbrian    return 0;
139753684Sbrian  }
139853684Sbrian
139953684Sbrian  for (f = expect = 0; f < niov; f++)
140053684Sbrian    expect += iov[f].iov_len;
140153684Sbrian
140253684Sbrian  return expect;
140353684Sbrian}
140453684Sbrian
140536285Sbrianvoid
140653684Sbrianbundle_ReceiveDatalink(struct bundle *bundle, int s)
140736285Sbrian{
140853684Sbrian  char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int) * SEND_MAXFD];
140953970Sbrian  int niov, expect, f, *fd, nfd, onfd, got;
141053684Sbrian  struct iovec iov[SCATTER_SEGMENTS];
141152942Sbrian  struct cmsghdr *cmsg;
141236285Sbrian  struct msghdr msg;
141336285Sbrian  struct datalink *dl;
141436450Sbrian  pid_t pid;
141536285Sbrian
141636285Sbrian  log_Printf(LogPHASE, "Receiving datalink\n");
141736285Sbrian
141853684Sbrian  /*
141953684Sbrian   * Create our scatter/gather array - passing NULL gets the space
142053684Sbrian   * allocation requirement rather than actually flattening the
142153684Sbrian   * structures.
142253684Sbrian   */
142353684Sbrian  iov[0].iov_len = strlen(Version) + 1;
142453684Sbrian  iov[0].iov_base = NULL;
142536285Sbrian  niov = 1;
142653684Sbrian  if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
142753684Sbrian    log_Printf(LogERROR, "Cannot determine space required for link\n");
142836285Sbrian    return;
142936345Sbrian  }
143036285Sbrian
143153684Sbrian  /* Allocate the scatter/gather array for recvmsg() */
143253684Sbrian  for (f = expect = 0; f < niov; f++) {
143353684Sbrian    if ((iov[f].iov_base = malloc(iov[f].iov_len)) == NULL) {
143453684Sbrian      log_Printf(LogERROR, "Cannot allocate space to receive link\n");
143553684Sbrian      return;
143653684Sbrian    }
143753970Sbrian    if (f)
143853970Sbrian      expect += iov[f].iov_len;
143953684Sbrian  }
144036285Sbrian
144136285Sbrian  /* Set up our message */
144253684Sbrian  cmsg = (struct cmsghdr *)cmsgbuf;
144353684Sbrian  cmsg->cmsg_len = sizeof cmsgbuf;
144453684Sbrian  cmsg->cmsg_level = SOL_SOCKET;
144553684Sbrian  cmsg->cmsg_type = 0;
144636285Sbrian
144736285Sbrian  memset(&msg, '\0', sizeof msg);
144853684Sbrian  msg.msg_name = NULL;
144953684Sbrian  msg.msg_namelen = 0;
145036285Sbrian  msg.msg_iov = iov;
145153970Sbrian  msg.msg_iovlen = 1;		/* Only send the version at the first pass */
145236285Sbrian  msg.msg_control = cmsgbuf;
145336285Sbrian  msg.msg_controllen = sizeof cmsgbuf;
145436285Sbrian
145558042Sbrian  log_Printf(LogDEBUG, "Expecting %u scatter/gather bytes\n",
145658042Sbrian             (unsigned)iov[0].iov_len);
145753684Sbrian
145853970Sbrian  if ((got = recvmsg(s, &msg, MSG_WAITALL)) != iov[0].iov_len) {
145953970Sbrian    if (got == -1)
146036285Sbrian      log_Printf(LogERROR, "Failed recvmsg: %s\n", strerror(errno));
146136285Sbrian    else
146258042Sbrian      log_Printf(LogERROR, "Failed recvmsg: Got %d, not %u\n",
146358042Sbrian                 got, (unsigned)iov[0].iov_len);
146436285Sbrian    while (niov--)
146536285Sbrian      free(iov[niov].iov_base);
146636285Sbrian    return;
146736285Sbrian  }
146836285Sbrian
146953684Sbrian  if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) {
147053684Sbrian    log_Printf(LogERROR, "Recvmsg: no descriptors received !\n");
147153684Sbrian    while (niov--)
147253684Sbrian      free(iov[niov].iov_base);
147353684Sbrian    return;
147452942Sbrian  }
147552942Sbrian
147653684Sbrian  fd = (int *)(cmsg + 1);
147753684Sbrian  nfd = (cmsg->cmsg_len - sizeof *cmsg) / sizeof(int);
147853684Sbrian
147953684Sbrian  if (nfd < 2) {
148058038Sbrian    log_Printf(LogERROR, "Recvmsg: %d descriptor%s received (too few) !\n",
148153684Sbrian               nfd, nfd == 1 ? "" : "s");
148253684Sbrian    while (nfd--)
148353684Sbrian      close(fd[nfd]);
148437054Sbrian    while (niov--)
148537054Sbrian      free(iov[niov].iov_base);
148637054Sbrian    return;
148736345Sbrian  }
148836285Sbrian
148952942Sbrian  /*
149053970Sbrian   * We've successfully received two or more open file descriptors
149153970Sbrian   * through our socket, plus a version string.  Make sure it's the
149253970Sbrian   * correct version, and drop the connection if it's not.
149352942Sbrian   */
149436285Sbrian  if (strncmp(Version, iov[0].iov_base, iov[0].iov_len)) {
149536285Sbrian    log_Printf(LogWARN, "Cannot receive datalink, incorrect version"
149636285Sbrian               " (\"%.*s\", not \"%s\")\n", (int)iov[0].iov_len,
149737188Sbrian               (char *)iov[0].iov_base, Version);
149853684Sbrian    while (nfd--)
149953684Sbrian      close(fd[nfd]);
150036285Sbrian    while (niov--)
150136285Sbrian      free(iov[niov].iov_base);
150236285Sbrian    return;
150336285Sbrian  }
150436285Sbrian
150553970Sbrian  /*
150653970Sbrian   * Everything looks good.  Send the other side our process id so that
150753970Sbrian   * they can transfer lock ownership, and wait for them to send the
150853970Sbrian   * actual link data.
150953970Sbrian   */
151053970Sbrian  pid = getpid();
151153970Sbrian  if ((got = write(fd[1], &pid, sizeof pid)) != sizeof pid) {
151253970Sbrian    if (got == -1)
151353970Sbrian      log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
151453970Sbrian    else
151553970Sbrian      log_Printf(LogERROR, "Failed write: Got %d, not %d\n", got,
151653970Sbrian                 (int)(sizeof pid));
151753970Sbrian    while (nfd--)
151853970Sbrian      close(fd[nfd]);
151953970Sbrian    while (niov--)
152053970Sbrian      free(iov[niov].iov_base);
152153970Sbrian    return;
152253970Sbrian  }
152353970Sbrian
152453970Sbrian  if ((got = readv(fd[1], iov + 1, niov - 1)) != expect) {
152553970Sbrian    if (got == -1)
152653970Sbrian      log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
152753970Sbrian    else
152853970Sbrian      log_Printf(LogERROR, "Failed write: Got %d, not %d\n", got, expect);
152953970Sbrian    while (nfd--)
153053970Sbrian      close(fd[nfd]);
153153970Sbrian    while (niov--)
153253970Sbrian      free(iov[niov].iov_base);
153353970Sbrian    return;
153453970Sbrian  }
153553970Sbrian  close(fd[1]);
153653970Sbrian
153753684Sbrian  onfd = nfd;	/* We've got this many in our array */
153858038Sbrian  nfd -= 2;	/* Don't include p->fd and our reply descriptor */
153953684Sbrian  niov = 1;	/* Skip the version id */
154052942Sbrian  dl = iov2datalink(bundle, iov, &niov, sizeof iov / sizeof *iov, fd[0],
154153684Sbrian                    fd + 2, &nfd);
154236285Sbrian  if (dl) {
154353684Sbrian
154452942Sbrian    if (nfd) {
154552942Sbrian      log_Printf(LogERROR, "bundle_ReceiveDatalink: Failed to handle %d "
154653684Sbrian                 "auxiliary file descriptors (%d remain)\n", onfd, nfd);
154752942Sbrian      datalink_Destroy(dl);
154852942Sbrian      while (nfd--)
154952942Sbrian        close(fd[onfd--]);
155053684Sbrian      close(fd[0]);
155152942Sbrian    } else {
155252942Sbrian      bundle_DatalinkLinkin(bundle, dl);
155352942Sbrian      datalink_AuthOk(dl);
155452942Sbrian      bundle_CalculateBandwidth(dl->bundle);
155552942Sbrian    }
155652942Sbrian  } else {
155752942Sbrian    while (nfd--)
155852942Sbrian      close(fd[onfd--]);
155952942Sbrian    close(fd[0]);
156053684Sbrian    close(fd[1]);
156152942Sbrian  }
156236285Sbrian
156336285Sbrian  free(iov[0].iov_base);
156436285Sbrian}
156536285Sbrian
156636285Sbrianvoid
156736285Sbrianbundle_SendDatalink(struct datalink *dl, int s, struct sockaddr_un *sun)
156836285Sbrian{
156953684Sbrian  char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int) * SEND_MAXFD];
157053684Sbrian  const char *constlock;
157153684Sbrian  char *lock;
157252942Sbrian  struct cmsghdr *cmsg;
157336285Sbrian  struct msghdr msg;
157436285Sbrian  struct iovec iov[SCATTER_SEGMENTS];
157553684Sbrian  int niov, f, expect, newsid, fd[SEND_MAXFD], nfd, reply[2], got;
157636450Sbrian  pid_t newpid;
157736285Sbrian
157836285Sbrian  log_Printf(LogPHASE, "Transmitting datalink %s\n", dl->name);
157936285Sbrian
158053684Sbrian  /* Record the base device name for a lock transfer later */
158153684Sbrian  constlock = physical_LockedDevice(dl->physical);
158253684Sbrian  if (constlock) {
158353684Sbrian    lock = alloca(strlen(constlock) + 1);
158453684Sbrian    strcpy(lock, constlock);
158553684Sbrian  } else
158653684Sbrian    lock = NULL;
158753684Sbrian
158836314Sbrian  bundle_LinkClosed(dl->bundle, dl);
158936285Sbrian  bundle_DatalinkLinkout(dl->bundle, dl);
159036285Sbrian
159136285Sbrian  /* Build our scatter/gather array */
159236285Sbrian  iov[0].iov_len = strlen(Version) + 1;
159336285Sbrian  iov[0].iov_base = strdup(Version);
159436285Sbrian  niov = 1;
159552942Sbrian  nfd = 0;
159636285Sbrian
159753684Sbrian  fd[0] = datalink2iov(dl, iov, &niov, SCATTER_SEGMENTS, fd + 2, &nfd);
159836285Sbrian
159953684Sbrian  if (fd[0] != -1 && socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, reply) != -1) {
160053684Sbrian    /*
160153684Sbrian     * fd[1] is used to get the peer process id back, then to confirm that
160253684Sbrian     * we've transferred any device locks to that process id.
160353684Sbrian     */
160453684Sbrian    fd[1] = reply[1];
160552942Sbrian
160653684Sbrian    nfd += 2;			/* Include fd[0] and fd[1] */
160736345Sbrian    memset(&msg, '\0', sizeof msg);
160836285Sbrian
160953684Sbrian    msg.msg_name = NULL;
161053684Sbrian    msg.msg_namelen = 0;
161153970Sbrian    /*
161253970Sbrian     * Only send the version to start...  We used to send the whole lot, but
161353970Sbrian     * this caused problems with our RECVBUF size as a single link is about
161453970Sbrian     * 22k !  This way, we should bump into no limits.
161553970Sbrian     */
161653970Sbrian    msg.msg_iovlen = 1;
161736285Sbrian    msg.msg_iov = iov;
161853684Sbrian    msg.msg_control = cmsgbuf;
161953684Sbrian    msg.msg_controllen = sizeof *cmsg + sizeof(int) * nfd;
162053684Sbrian    msg.msg_flags = 0;
162136285Sbrian
162253684Sbrian    cmsg = (struct cmsghdr *)cmsgbuf;
162353684Sbrian    cmsg->cmsg_len = msg.msg_controllen;
162453684Sbrian    cmsg->cmsg_level = SOL_SOCKET;
162553684Sbrian    cmsg->cmsg_type = SCM_RIGHTS;
162652942Sbrian
162753684Sbrian    for (f = 0; f < nfd; f++)
162853684Sbrian      *((int *)(cmsg + 1) + f) = fd[f];
162936345Sbrian
163053970Sbrian    for (f = 1, expect = 0; f < niov; f++)
163136285Sbrian      expect += iov[f].iov_len;
163236285Sbrian
163353970Sbrian    if (setsockopt(reply[0], SOL_SOCKET, SO_SNDBUF, &expect, sizeof(int)) == -1)
163453970Sbrian      log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
163553970Sbrian                 strerror(errno));
163653970Sbrian    if (setsockopt(reply[1], SOL_SOCKET, SO_RCVBUF, &expect, sizeof(int)) == -1)
163753970Sbrian      log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
163853970Sbrian                 strerror(errno));
163953970Sbrian
164058042Sbrian    log_Printf(LogDEBUG, "Sending %d descriptor%s and %u bytes in scatter"
164158042Sbrian               "/gather array\n", nfd, nfd == 1 ? "" : "s",
164258042Sbrian               (unsigned)iov[0].iov_len);
164336285Sbrian
164453684Sbrian    if ((got = sendmsg(s, &msg, 0)) == -1)
164553684Sbrian      log_Printf(LogERROR, "Failed sendmsg: %s: %s\n",
164653684Sbrian                 sun->sun_path, strerror(errno));
164753970Sbrian    else if (got != iov[0].iov_len)
164858042Sbrian      log_Printf(LogERROR, "%s: Failed initial sendmsg: Only sent %d of %u\n",
164958042Sbrian                 sun->sun_path, got, (unsigned)iov[0].iov_len);
165053684Sbrian    else {
165158038Sbrian      /* We must get the ACK before closing the descriptor ! */
165253684Sbrian      int res;
165336345Sbrian
165453970Sbrian      if ((got = read(reply[0], &newpid, sizeof newpid)) == sizeof newpid) {
165553970Sbrian        log_Printf(LogDEBUG, "Received confirmation from pid %d\n",
165653970Sbrian                   (int)newpid);
165753970Sbrian        if (lock && (res = ID0uu_lock_txfr(lock, newpid)) != UU_LOCK_OK)
165859084Sbrian            log_Printf(LogERROR, "uu_lock_txfr: %s\n", uu_lockerr(res));
165953684Sbrian
166053970Sbrian        log_Printf(LogDEBUG, "Transmitting link (%d bytes)\n", expect);
166153970Sbrian        if ((got = writev(reply[0], iov + 1, niov - 1)) != expect) {
166253970Sbrian          if (got == -1)
166353970Sbrian            log_Printf(LogERROR, "%s: Failed writev: %s\n",
166453970Sbrian                       sun->sun_path, strerror(errno));
166553970Sbrian          else
166653970Sbrian            log_Printf(LogERROR, "%s: Failed writev: Wrote %d of %d\n",
166753970Sbrian                       sun->sun_path, got, expect);
166853970Sbrian        }
166953970Sbrian      } else if (got == -1)
167053970Sbrian        log_Printf(LogERROR, "%s: Failed socketpair read: %s\n",
167153970Sbrian                   sun->sun_path, strerror(errno));
167253970Sbrian      else
167353970Sbrian        log_Printf(LogERROR, "%s: Failed socketpair read: Got %d of %d\n",
167453970Sbrian                   sun->sun_path, got, (int)(sizeof newpid));
167553684Sbrian    }
167653684Sbrian
167753684Sbrian    close(reply[0]);
167853684Sbrian    close(reply[1]);
167953684Sbrian
168047689Sbrian    newsid = Enabled(dl->bundle, OPT_KEEPSESSION) ||
168152942Sbrian             tcgetpgrp(fd[0]) == getpgrp();
168252942Sbrian    while (nfd)
168352942Sbrian      close(fd[--nfd]);
168436452Sbrian    if (newsid)
168553684Sbrian      bundle_setsid(dl->bundle, got != -1);
168636285Sbrian  }
168736450Sbrian  close(s);
168836285Sbrian
168936285Sbrian  while (niov--)
169036285Sbrian    free(iov[niov].iov_base);
169136285Sbrian}
169236285Sbrian
169336285Sbrianint
169436285Sbrianbundle_RenameDatalink(struct bundle *bundle, struct datalink *ndl,
169536285Sbrian                      const char *name)
169636285Sbrian{
169736285Sbrian  struct datalink *dl;
169836285Sbrian
169936285Sbrian  if (!strcasecmp(ndl->name, name))
170036285Sbrian    return 1;
170136285Sbrian
170236285Sbrian  for (dl = bundle->links; dl; dl = dl->next)
170336285Sbrian    if (!strcasecmp(dl->name, name))
170436285Sbrian      return 0;
170536285Sbrian
170636285Sbrian  datalink_Rename(ndl, name);
170736285Sbrian  return 1;
170836285Sbrian}
170936285Sbrian
171036285Sbrianint
171136285Sbrianbundle_SetMode(struct bundle *bundle, struct datalink *dl, int mode)
171236285Sbrian{
171336285Sbrian  int omode;
171436285Sbrian
171536285Sbrian  omode = dl->physical->type;
171636285Sbrian  if (omode == mode)
171736285Sbrian    return 1;
171836285Sbrian
171936928Sbrian  if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO))
172036928Sbrian    /* First auto link */
172136285Sbrian    if (bundle->ncp.ipcp.peer_ip.s_addr == INADDR_ANY) {
172236928Sbrian      log_Printf(LogWARN, "You must `set ifaddr' or `open' before"
172336928Sbrian                 " changing mode to %s\n", mode2Nam(mode));
172436285Sbrian      return 0;
172536285Sbrian    }
172636285Sbrian
172736285Sbrian  if (!datalink_SetMode(dl, mode))
172836285Sbrian    return 0;
172936285Sbrian
173036928Sbrian  if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO) &&
173136928Sbrian      bundle->phase != PHASE_NETWORK)
173236928Sbrian    /* First auto link, we need an interface */
173336285Sbrian    ipcp_InterfaceUp(&bundle->ncp.ipcp);
173436285Sbrian
173549434Sbrian  /* Regenerate phys_type and adjust idle timer */
173636285Sbrian  bundle_LinksRemoved(bundle);
173736285Sbrian
173836285Sbrian  return 1;
173936285Sbrian}
174036452Sbrian
174136452Sbrianvoid
174236452Sbrianbundle_setsid(struct bundle *bundle, int holdsession)
174336452Sbrian{
174436452Sbrian  /*
174536452Sbrian   * Lose the current session.  This means getting rid of our pid
174636452Sbrian   * too so that the tty device will really go away, and any getty
174736452Sbrian   * etc will be allowed to restart.
174836452Sbrian   */
174936452Sbrian  pid_t pid, orig;
175036452Sbrian  int fds[2];
175136452Sbrian  char done;
175236452Sbrian  struct datalink *dl;
175336452Sbrian
175455066Sbrian  if (!holdsession && bundle_IsDead(bundle)) {
175555066Sbrian    /*
175655066Sbrian     * No need to lose our session after all... we're going away anyway
175755066Sbrian     *
175855066Sbrian     * We should really stop the timer and pause if holdsession is set and
175955066Sbrian     * the bundle's dead, but that leaves other resources lying about :-(
176055066Sbrian     */
176155066Sbrian    return;
176255066Sbrian  }
176355066Sbrian
176436452Sbrian  orig = getpid();
176536452Sbrian  if (pipe(fds) == -1) {
176636452Sbrian    log_Printf(LogERROR, "pipe: %s\n", strerror(errno));
176736452Sbrian    return;
176836452Sbrian  }
176936452Sbrian  switch ((pid = fork())) {
177036452Sbrian    case -1:
177136452Sbrian      log_Printf(LogERROR, "fork: %s\n", strerror(errno));
177236452Sbrian      close(fds[0]);
177336452Sbrian      close(fds[1]);
177436452Sbrian      return;
177536452Sbrian    case 0:
177644541Sbrian      close(fds[1]);
177744541Sbrian      read(fds[0], &done, 1);		/* uu_locks are mine ! */
177836452Sbrian      close(fds[0]);
177936452Sbrian      if (pipe(fds) == -1) {
178036452Sbrian        log_Printf(LogERROR, "pipe(2): %s\n", strerror(errno));
178136452Sbrian        return;
178236452Sbrian      }
178336452Sbrian      switch ((pid = fork())) {
178436452Sbrian        case -1:
178537019Sbrian          log_Printf(LogERROR, "fork(2): %s\n", strerror(errno));
178636452Sbrian          close(fds[0]);
178736452Sbrian          close(fds[1]);
178836452Sbrian          return;
178936452Sbrian        case 0:
179044541Sbrian          close(fds[1]);
179144541Sbrian          bundle_LockTun(bundle);	/* update pid */
179244541Sbrian          read(fds[0], &done, 1);	/* uu_locks are mine ! */
179336452Sbrian          close(fds[0]);
179436452Sbrian          setsid();
179556350Sbrian          bundle_ChangedPID(bundle);
179659084Sbrian          log_Printf(LogDEBUG, "%d -> %d: %s session control\n",
179736452Sbrian                     (int)orig, (int)getpid(),
179836452Sbrian                     holdsession ? "Passed" : "Dropped");
179941799Sbrian          timer_InitService(0);		/* Start the Timer Service */
180036452Sbrian          break;
180136452Sbrian        default:
180244541Sbrian          close(fds[0]);
180346686Sbrian          /* Give away all our physical locks (to the final process) */
180436452Sbrian          for (dl = bundle->links; dl; dl = dl->next)
180536452Sbrian            if (dl->state != DATALINK_CLOSED)
180646686Sbrian              physical_ChangedPid(dl->physical, pid);
180744541Sbrian          write(fds[1], "!", 1);	/* done */
180844541Sbrian          close(fds[1]);
180953684Sbrian          _exit(0);
181036452Sbrian          break;
181136452Sbrian      }
181236452Sbrian      break;
181336452Sbrian    default:
181444541Sbrian      close(fds[0]);
181546686Sbrian      /* Give away all our physical locks (to the intermediate process) */
181636452Sbrian      for (dl = bundle->links; dl; dl = dl->next)
181736452Sbrian        if (dl->state != DATALINK_CLOSED)
181846686Sbrian          physical_ChangedPid(dl->physical, pid);
181944541Sbrian      write(fds[1], "!", 1);	/* done */
182044541Sbrian      close(fds[1]);
182136452Sbrian      if (holdsession) {
182236452Sbrian        int fd, status;
182336452Sbrian
182436452Sbrian        timer_TermService();
182536452Sbrian        signal(SIGPIPE, SIG_DFL);
182636452Sbrian        signal(SIGALRM, SIG_DFL);
182736452Sbrian        signal(SIGHUP, SIG_DFL);
182836452Sbrian        signal(SIGTERM, SIG_DFL);
182936452Sbrian        signal(SIGINT, SIG_DFL);
183036452Sbrian        signal(SIGQUIT, SIG_DFL);
183136452Sbrian        for (fd = getdtablesize(); fd >= 0; fd--)
183236452Sbrian          close(fd);
183336452Sbrian        /*
183436452Sbrian         * Reap the intermediate process.  As we're not exiting but the
183536452Sbrian         * intermediate is, we don't want it to become defunct.
183636452Sbrian         */
183736452Sbrian        waitpid(pid, &status, 0);
183836467Sbrian        /* Tweak our process arguments.... */
183953298Sbrian        ID0setproctitle("session owner");
184055252Sbrian        setuid(ID0realuid());
184136452Sbrian        /*
184236452Sbrian         * Hang around for a HUP.  This should happen as soon as the
184358038Sbrian         * ppp that we passed our ctty descriptor to closes it.
184458038Sbrian         * NOTE: If this process dies, the passed descriptor becomes
184536452Sbrian         *       invalid and will give a select() error by setting one
184636452Sbrian         *       of the error fds, aborting the other ppp.  We don't
184736452Sbrian         *       want that to happen !
184836452Sbrian         */
184936452Sbrian        pause();
185036452Sbrian      }
185153684Sbrian      _exit(0);
185236452Sbrian      break;
185336452Sbrian  }
185436452Sbrian}
185540622Sbrian
185640622Sbrianint
185740622Sbrianbundle_HighestState(struct bundle *bundle)
185840622Sbrian{
185940622Sbrian  struct datalink *dl;
186040622Sbrian  int result = DATALINK_CLOSED;
186140622Sbrian
186240622Sbrian  for (dl = bundle->links; dl; dl = dl->next)
186340622Sbrian    if (result < dl->state)
186440622Sbrian      result = dl->state;
186540622Sbrian
186640622Sbrian  return result;
186740622Sbrian}
186841654Sbrian
186941654Sbrianint
187041654Sbrianbundle_Exception(struct bundle *bundle, int fd)
187141654Sbrian{
187241654Sbrian  struct datalink *dl;
187341654Sbrian
187441654Sbrian  for (dl = bundle->links; dl; dl = dl->next)
187541654Sbrian    if (dl->physical->fd == fd) {
187641654Sbrian      datalink_Down(dl, CLOSE_NORMAL);
187741654Sbrian      return 1;
187841654Sbrian    }
187941654Sbrian
188041654Sbrian  return 0;
188141654Sbrian}
188247648Sbrian
188347648Sbrianvoid
188447648Sbrianbundle_AdjustFilters(struct bundle *bundle, struct in_addr *my_ip,
188547648Sbrian                     struct in_addr *peer_ip)
188647648Sbrian{
188758044Sbrian  filter_AdjustAddr(&bundle->filter.in, my_ip, peer_ip, NULL);
188858044Sbrian  filter_AdjustAddr(&bundle->filter.out, my_ip, peer_ip, NULL);
188958044Sbrian  filter_AdjustAddr(&bundle->filter.dial, my_ip, peer_ip, NULL);
189058044Sbrian  filter_AdjustAddr(&bundle->filter.alive, my_ip, peer_ip, NULL);
189147648Sbrian}
189249434Sbrian
189349434Sbrianvoid
189458044Sbrianbundle_AdjustDNS(struct bundle *bundle, struct in_addr dns[2])
189558044Sbrian{
189658044Sbrian  filter_AdjustAddr(&bundle->filter.in, NULL, NULL, dns);
189758044Sbrian  filter_AdjustAddr(&bundle->filter.out, NULL, NULL, dns);
189858044Sbrian  filter_AdjustAddr(&bundle->filter.dial, NULL, NULL, dns);
189958044Sbrian  filter_AdjustAddr(&bundle->filter.alive, NULL, NULL, dns);
190058044Sbrian}
190158044Sbrian
190258044Sbrianvoid
190349434Sbrianbundle_CalculateBandwidth(struct bundle *bundle)
190449434Sbrian{
190549434Sbrian  struct datalink *dl;
190649434Sbrian  int mtu, sp;
190749434Sbrian
190849434Sbrian  bundle->bandwidth = 0;
190949434Sbrian  mtu = 0;
191049434Sbrian  for (dl = bundle->links; dl; dl = dl->next)
191149434Sbrian    if (dl->state == DATALINK_OPEN) {
191249434Sbrian      if ((sp = dl->mp.bandwidth) == 0 &&
191349434Sbrian          (sp = physical_GetSpeed(dl->physical)) == 0)
191449434Sbrian        log_Printf(LogDEBUG, "%s: %s: Cannot determine bandwidth\n",
191549434Sbrian                   dl->name, dl->physical->name.full);
191649434Sbrian      else
191749434Sbrian        bundle->bandwidth += sp;
191849434Sbrian      if (!bundle->ncp.mp.active) {
191949434Sbrian        mtu = dl->physical->link.lcp.his_mru;
192049434Sbrian        break;
192149434Sbrian      }
192249434Sbrian    }
192349434Sbrian
192449434Sbrian  if(bundle->bandwidth == 0)
192549434Sbrian    bundle->bandwidth = 115200;		/* Shrug */
192649434Sbrian
192749434Sbrian  if (bundle->ncp.mp.active)
192849434Sbrian    mtu = bundle->ncp.mp.peer_mrru;
192949434Sbrian  else if (!mtu)
193049434Sbrian    mtu = 1500;
193149434Sbrian
193249434Sbrian#ifndef NORADIUS
193349434Sbrian  if (bundle->radius.valid && bundle->radius.mtu && bundle->radius.mtu < mtu) {
193449434Sbrian    log_Printf(LogLCP, "Reducing MTU to radius value %lu\n",
193549434Sbrian               bundle->radius.mtu);
193649434Sbrian    mtu = bundle->radius.mtu;
193749434Sbrian  }
193849434Sbrian#endif
193949434Sbrian
194049434Sbrian  tun_configure(bundle, mtu);
194149434Sbrian}
194249434Sbrian
194349434Sbrianvoid
194449434Sbrianbundle_AutoAdjust(struct bundle *bundle, int percent, int what)
194549434Sbrian{
194649434Sbrian  struct datalink *dl, *choice, *otherlinkup;
194749434Sbrian
194849434Sbrian  choice = otherlinkup = NULL;
194949434Sbrian  for (dl = bundle->links; dl; dl = dl->next)
195049434Sbrian    if (dl->physical->type == PHYS_AUTO) {
195149434Sbrian      if (dl->state == DATALINK_OPEN) {
195249434Sbrian        if (what == AUTO_DOWN) {
195349434Sbrian          if (choice)
195449434Sbrian            otherlinkup = choice;
195549434Sbrian          choice = dl;
195649434Sbrian        }
195749434Sbrian      } else if (dl->state == DATALINK_CLOSED) {
195849434Sbrian        if (what == AUTO_UP) {
195949434Sbrian          choice = dl;
196049434Sbrian          break;
196149434Sbrian        }
196249434Sbrian      } else {
196349434Sbrian        /* An auto link in an intermediate state - forget it for the moment */
196449434Sbrian        choice = NULL;
196549434Sbrian        break;
196649434Sbrian      }
196749434Sbrian    } else if (dl->state == DATALINK_OPEN && what == AUTO_DOWN)
196849434Sbrian      otherlinkup = dl;
196949434Sbrian
197049434Sbrian  if (choice) {
197149434Sbrian    if (what == AUTO_UP) {
197249434Sbrian      log_Printf(LogPHASE, "%d%% saturation -> Opening link ``%s''\n",
197349434Sbrian                 percent, choice->name);
197449434Sbrian      datalink_Up(choice, 1, 1);
197561129Sbrian      mp_CheckAutoloadTimer(&bundle->ncp.mp);
197649434Sbrian    } else if (otherlinkup) {	/* Only bring the second-last link down */
197749434Sbrian      log_Printf(LogPHASE, "%d%% saturation -> Closing link ``%s''\n",
197849434Sbrian                 percent, choice->name);
197951945Sbrian      datalink_Close(choice, CLOSE_STAYDOWN);
198061129Sbrian      mp_CheckAutoloadTimer(&bundle->ncp.mp);
198149434Sbrian    }
198249434Sbrian  }
198349434Sbrian}
198449434Sbrian
198549434Sbrianint
198649434Sbrianbundle_WantAutoloadTimer(struct bundle *bundle)
198749434Sbrian{
198849434Sbrian  struct datalink *dl;
198949434Sbrian  int autolink, opened;
199049434Sbrian
199149434Sbrian  if (bundle->phase == PHASE_NETWORK) {
199249434Sbrian    for (autolink = opened = 0, dl = bundle->links; dl; dl = dl->next)
199349434Sbrian      if (dl->physical->type == PHYS_AUTO) {
199449434Sbrian        if (++autolink == 2 || (autolink == 1 && opened))
199549434Sbrian          /* Two auto links or one auto and one open in NETWORK phase */
199649434Sbrian          return 1;
199749434Sbrian      } else if (dl->state == DATALINK_OPEN) {
199849434Sbrian        opened++;
199949434Sbrian        if (autolink)
200049434Sbrian          /* One auto and one open link in NETWORK phase */
200149434Sbrian          return 1;
200249434Sbrian      }
200349434Sbrian  }
200449434Sbrian
200549434Sbrian  return 0;
200649434Sbrian}
200756350Sbrian
200856350Sbrianvoid
200956350Sbrianbundle_ChangedPID(struct bundle *bundle)
201056350Sbrian{
201156350Sbrian#ifdef TUNSIFPID
201256350Sbrian  ioctl(bundle->dev.fd, TUNSIFPID, 0);
201356350Sbrian#endif
201456350Sbrian}
2015