bundle.c revision 96153
137Srgrimes/*-
237Srgrimes * Copyright (c) 1998 Brian Somers <brian@Awfulhak.org>
3358Srgrimes * All rights reserved.
437Srgrimes *
537Srgrimes * Redistribution and use in source and binary forms, with or without
637Srgrimes * modification, are permitted provided that the following conditions
7147Srgrimes * are met:
8147Srgrimes * 1. Redistributions of source code must retain the above copyright
9147Srgrimes *    notice, this list of conditions and the following disclaimer.
10207Snate * 2. Redistributions in binary form must reproduce the above copyright
11377Srgrimes *    notice, this list of conditions and the following disclaimer in the
12147Srgrimes *    documentation and/or other materials provided with the distribution.
13147Srgrimes *
1437Srgrimes * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
1537Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1637Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1737Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18147Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19147Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20147Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21491Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2237Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2337Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2437Srgrimes * SUCH DAMAGE.
2537Srgrimes *
2637Srgrimes * $FreeBSD: head/usr.sbin/ppp/bundle.c 96153 2002-05-07 10:06:54Z brian $
27263Srgrimes */
28284Srgrimes
29355Srgrimes#include <sys/param.h>
30277Srgrimes#include <sys/socket.h>
31277Srgrimes#include <netinet/in.h>
32284Srgrimes#include <net/if.h>
33463Srgrimes#include <net/if_tun.h>		/* For TUNS* ioctls */
34284Srgrimes#include <net/route.h>
35284Srgrimes#include <netinet/in_systm.h>
36284Srgrimes#include <netinet/ip.h>
37284Srgrimes#include <sys/un.h>
38284Srgrimes
39284Srgrimes#include <errno.h>
40284Srgrimes#include <fcntl.h>
41284Srgrimes#ifdef __OpenBSD__
42284Srgrimes#include <util.h>
43284Srgrimes#else
44358Srgrimes#include <libutil.h>
45358Srgrimes#endif
46358Srgrimes#include <paths.h>
47452Srgrimes#include <stdio.h>
48358Srgrimes#include <stdlib.h>
49412Salm#include <string.h>
50358Srgrimes#include <sys/uio.h>
51452Srgrimes#include <sys/wait.h>
52358Srgrimes#include <termios.h>
53452Srgrimes#include <unistd.h>
54358Srgrimes
55358Srgrimes#include "layer.h"
56412Salm#include "defs.h"
57358Srgrimes#include "command.h"
58358Srgrimes#include "mbuf.h"
59358Srgrimes#include "log.h"
60263Srgrimes#include "id.h"
61358Srgrimes#include "timer.h"
62358Srgrimes#include "fsm.h"
63452Srgrimes#include "iplist.h"
64481Salm#include "lqr.h"
65452Srgrimes#include "hdlc.h"
66452Srgrimes#include "throughput.h"
67358Srgrimes#include "slcompress.h"
68358Srgrimes#include "ncpaddr.h"
69358Srgrimes#include "ip.h"
70358Srgrimes#include "ipcp.h"
71358Srgrimes#include "filter.h"
72482Salm#include "descriptor.h"
73284Srgrimes#include "route.h"
74347Srgrimes#include "lcp.h"
75372Srgrimes#include "ccp.h"
76372Srgrimes#include "link.h"
77372Srgrimes#include "mp.h"
78372Srgrimes#ifndef NORADIUS
79372Srgrimes#include "radius.h"
80372Srgrimes#endif
81347Srgrimes#include "ipv6cp.h"
8237Srgrimes#include "ncp.h"
8337Srgrimes#include "bundle.h"
84347Srgrimes#include "async.h"
85347Srgrimes#include "physical.h"
86347Srgrimes#include "auth.h"
87355Srgrimes#include "proto.h"
88372Srgrimes#include "chap.h"
89347Srgrimes#include "tun.h"
90355Srgrimes#include "prompt.h"
91347Srgrimes#include "chat.h"
92347Srgrimes#include "cbcp.h"
93347Srgrimes#include "datalink.h"
94347Srgrimes#include "iface.h"
95372Srgrimes#include "server.h"
96347Srgrimes#include "probe.h"
97355Srgrimes#ifndef NODES
98347Srgrimes#include "mppe.h"
99347Srgrimes#endif
100147Srgrimes
10137Srgrimes#define SCATTER_SEGMENTS 7  /* version, datalink, name, physical,
10237Srgrimes                               throughput, throughput, device       */
103147Srgrimes
104147Srgrimes#define SEND_MAXFD 3        /* Max file descriptors passed through
105238Sroot                               the local domain socket              */
10637Srgrimes
107358Srgrimesstatic int bundle_RemainingIdleTime(struct bundle *);
10837Srgrimes
10937Srgrimesstatic const char * const PhaseNames[] = {
110347Srgrimes  "Dead", "Establish", "Authenticate", "Network", "Terminate"
111147Srgrimes};
112347Srgrimes
11337Srgrimesconst char *
11437Srgrimesbundle_PhaseName(struct bundle *bundle)
11537Srgrimes{
11637Srgrimes  return bundle->phase <= PHASE_TERMINATE ?
11737Srgrimes    PhaseNames[bundle->phase] : "unknown";
11837Srgrimes}
11937Srgrimes
12037Srgrimesvoid
12137Srgrimesbundle_NewPhase(struct bundle *bundle, u_int new)
12237Srgrimes{
12337Srgrimes  if (new == bundle->phase)
12437Srgrimes    return;
12537Srgrimes
12637Srgrimes  if (new <= PHASE_TERMINATE)
12737Srgrimes    log_Printf(LogPHASE, "bundle: %s\n", PhaseNames[new]);
12837Srgrimes
12937Srgrimes  switch (new) {
13037Srgrimes  case PHASE_DEAD:
131147Srgrimes    bundle->phase = new;
132147Srgrimes#ifndef NODES
13337Srgrimes    MPPE_MasterKeyValid = 0;
134147Srgrimes#endif
13537Srgrimes    log_DisplayPrompts();
13637Srgrimes    break;
13737Srgrimes
138288Srgrimes  case PHASE_ESTABLISH:
139288Srgrimes    bundle->phase = new;
140147Srgrimes    break;
14137Srgrimes
142147Srgrimes  case PHASE_AUTHENTICATE:
143147Srgrimes    bundle->phase = new;
14437Srgrimes    log_DisplayPrompts();
14537Srgrimes    break;
146147Srgrimes
147347Srgrimes  case PHASE_NETWORK:
148355Srgrimes    if (ncp_fsmStart(&bundle->ncp, bundle)) {
149355Srgrimes      bundle->phase = new;
150347Srgrimes      log_DisplayPrompts();
151355Srgrimes    } else {
152355Srgrimes      log_Printf(LogPHASE, "bundle: All NCPs are disabled\n");
153347Srgrimes      bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
154277Srgrimes    }
155355Srgrimes    break;
156277Srgrimes
157355Srgrimes  case PHASE_TERMINATE:
158238Sroot    bundle->phase = new;
159238Sroot    mp_Down(&bundle->ncp.mp);
160277Srgrimes    log_DisplayPrompts();
161277Srgrimes    break;
162355Srgrimes  }
163333Srgrimes}
164333Srgrimes
165333Srgrimesstatic void
166168Srgrimesbundle_LayerStart(void *v, struct fsm *fp)
167333Srgrimes{
168333Srgrimes  /* The given FSM is about to start up ! */
169333Srgrimes}
170333Srgrimes
17137Srgrimes
17237Srgrimesvoid
17337Srgrimesbundle_Notify(struct bundle *bundle, char c)
17437Srgrimes{
17537Srgrimes  if (bundle->notify.fd != -1) {
176358Srgrimes    int ret;
177320Srgrimes
178320Srgrimes    ret = write(bundle->notify.fd, &c, 1);
179355Srgrimes    if (c != EX_REDIAL && c != EX_RECONNECT) {
180320Srgrimes      if (ret == 1)
181320Srgrimes        log_Printf(LogCHAT, "Parent notified of %s\n",
182355Srgrimes                   c == EX_NORMAL ? "success" : "failure");
183320Srgrimes      else
184320Srgrimes        log_Printf(LogERROR, "Failed to notify parent of success\n");
185320Srgrimes      close(bundle->notify.fd);
186358Srgrimes      bundle->notify.fd = -1;
187277Srgrimes    } else if (ret == 1)
188277Srgrimes      log_Printf(LogCHAT, "Parent notified of %s\n", ex_desc(c));
189277Srgrimes    else
190333Srgrimes      log_Printf(LogERROR, "Failed to notify parent of %s\n", ex_desc(c));
191333Srgrimes  }
192284Srgrimes}
193320Srgrimes
194277Srgrimesstatic void
195277Srgrimesbundle_ClearQueues(void *v)
196277Srgrimes{
197333Srgrimes  struct bundle *bundle = (struct bundle *)v;
198284Srgrimes  struct datalink *dl;
199320Srgrimes
200277Srgrimes  log_Printf(LogPHASE, "Clearing choked output queue\n");
201277Srgrimes  timer_Stop(&bundle->choked.timer);
202320Srgrimes
203372Srgrimes  /*
204372Srgrimes   * Emergency time:
205320Srgrimes   *
206277Srgrimes   * We've had a full queue for PACKET_DEL_SECS seconds without being
207277Srgrimes   * able to get rid of any of the packets.  We've probably given up
208277Srgrimes   * on the redials at this point, and the queued data has almost
209277Srgrimes   * definitely been timed out by the layer above.  As this is preventing
210372Srgrimes   * us from reading the TUN_NAME device (we don't want to buffer stuff
211358Srgrimes   * indefinitely), we may as well nuke this data and start with a clean
212372Srgrimes   * slate !
213372Srgrimes   *
214277Srgrimes   * Unfortunately, this has the side effect of shafting any compression
215372Srgrimes   * dictionaries in use (causing the relevant RESET_REQ/RESET_ACK).
216372Srgrimes   */
217320Srgrimes
218320Srgrimes  ncp_DeleteQueues(&bundle->ncp);
219320Srgrimes  for (dl = bundle->links; dl; dl = dl->next)
220320Srgrimes    physical_DeleteQueue(dl->physical);
221320Srgrimes}
222372Srgrimes
223358Srgrimesstatic void
224372Srgrimesbundle_LinkAdded(struct bundle *bundle, struct datalink *dl)
225372Srgrimes{
226320Srgrimes  bundle->phys_type.all |= dl->physical->type;
227358Srgrimes  if (dl->state == DATALINK_OPEN)
228284Srgrimes    bundle->phys_type.open |= dl->physical->type;
229284Srgrimes
230284Srgrimes#ifndef NORADIUS
231333Srgrimes  if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
232333Srgrimes      != bundle->phys_type.open && bundle->session.timer.state == TIMER_STOPPED)
233284Srgrimes    if (bundle->radius.sessiontime)
234358Srgrimes      bundle_StartSessionTimer(bundle, 0);
235284Srgrimes#endif
236284Srgrimes
237284Srgrimes  if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
238435Srgrimes      != bundle->phys_type.open && bundle->idle.timer.state == TIMER_STOPPED)
239435Srgrimes    /* We may need to start our idle timer */
240284Srgrimes    bundle_StartIdleTimer(bundle, 0);
241358Srgrimes}
242284Srgrimes
243284Srgrimesvoid
244284Srgrimesbundle_LinksRemoved(struct bundle *bundle)
245284Srgrimes{
246284Srgrimes  struct datalink *dl;
247358Srgrimes
248358Srgrimes  bundle->phys_type.all = bundle->phys_type.open = 0;
249358Srgrimes  for (dl = bundle->links; dl; dl = dl->next)
250333Srgrimes    bundle_LinkAdded(bundle, dl);
251333Srgrimes
252284Srgrimes  bundle_CalculateBandwidth(bundle);
253284Srgrimes  mp_CheckAutoloadTimer(&bundle->ncp.mp);
254284Srgrimes
255372Srgrimes  if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
256358Srgrimes      == bundle->phys_type.open) {
257372Srgrimes#ifndef NORADIUS
258372Srgrimes    if (bundle->radius.sessiontime)
259284Srgrimes      bundle_StopSessionTimer(bundle);
260358Srgrimes#endif
261284Srgrimes    bundle_StopIdleTimer(bundle);
262284Srgrimes   }
263284Srgrimes}
264333Srgrimes
265333Srgrimesstatic void
266284Srgrimesbundle_LayerUp(void *v, struct fsm *fp)
267358Srgrimes{
268284Srgrimes  /*
269444Srgrimes   * The given fsm is now up
270444Srgrimes   * If it's an LCP, adjust our phys_mode.open value and check the
271284Srgrimes   * autoload timer.
272284Srgrimes   * If it's the first NCP, calculate our bandwidth
273284Srgrimes   * If it's the first NCP, set our ``upat'' time
274284Srgrimes   * If it's the first NCP, start the idle timer.
275284Srgrimes   * If it's an NCP, tell our -background parent to go away.
276284Srgrimes   * If it's the first NCP, start the autoload timer
277284Srgrimes   */
278372Srgrimes  struct bundle *bundle = (struct bundle *)v;
279358Srgrimes
280372Srgrimes  if (fp->proto == PROTO_LCP) {
281372Srgrimes    struct physical *p = link2physical(fp->link);
282284Srgrimes
283372Srgrimes    bundle_LinkAdded(bundle, p->dl);
284372Srgrimes    mp_CheckAutoloadTimer(&bundle->ncp.mp);
285538Srgrimes  } else if (isncp(fp->proto)) {
286538Srgrimes    if (ncp_LayersOpen(&fp->bundle->ncp) == 1) {
287538Srgrimes      bundle_CalculateBandwidth(fp->bundle);
288538Srgrimes      time(&bundle->upat);
289372Srgrimes#ifndef NORADIUS
290538Srgrimes      if (bundle->radius.sessiontime)
291376Srgrimes        bundle_StartSessionTimer(bundle, 0);
292538Srgrimes#endif
293538Srgrimes      bundle_StartIdleTimer(bundle, 0);
294538Srgrimes      mp_CheckAutoloadTimer(&fp->bundle->ncp.mp);
295538Srgrimes    }
296376Srgrimes    bundle_Notify(bundle, EX_NORMAL);
297538Srgrimes  } else if (fp->proto == PROTO_CCP)
298376Srgrimes    bundle_CalculateBandwidth(fp->bundle);	/* Against ccp_MTUOverhead */
299538Srgrimes}
300538Srgrimes
301538Srgrimesstatic void
302538Srgrimesbundle_LayerDown(void *v, struct fsm *fp)
303376Srgrimes{
304538Srgrimes  /*
305538Srgrimes   * The given FSM has been told to come down.
306538Srgrimes   * If it's our last NCP, stop the idle timer.
307538Srgrimes   * If it's our last NCP, clear our ``upat'' value.
308538Srgrimes   * If it's our last NCP, stop the autoload timer
309538Srgrimes   * If it's an LCP, adjust our phys_type.open value and any timers.
310538Srgrimes   * If it's an LCP and we're in multilink mode, adjust our tun
311538Srgrimes   * If it's the last LCP, down all NCPs
312538Srgrimes   * speed and make sure our minimum sequence number is adjusted.
313538Srgrimes   */
314538Srgrimes
315538Srgrimes  struct bundle *bundle = (struct bundle *)v;
316538Srgrimes
317538Srgrimes  if (isncp(fp->proto)) {
318538Srgrimes    if (ncp_LayersOpen(&fp->bundle->ncp) == 0) {
319538Srgrimes#ifndef NORADIUS
320538Srgrimes      if (bundle->radius.sessiontime)
321538Srgrimes        bundle_StopSessionTimer(bundle);
322538Srgrimes#endif
323538Srgrimes      bundle_StopIdleTimer(bundle);
324538Srgrimes      bundle->upat = 0;
325538Srgrimes      mp_StopAutoloadTimer(&bundle->ncp.mp);
326538Srgrimes    }
327538Srgrimes  } else if (fp->proto == PROTO_LCP) {
328538Srgrimes    struct datalink *dl;
329538Srgrimes    struct datalink *lost;
330538Srgrimes    int others_active;
331538Srgrimes
332538Srgrimes    bundle_LinksRemoved(bundle);  /* adjust timers & phys_type values */
333538Srgrimes
334538Srgrimes    lost = NULL;
335538Srgrimes    others_active = 0;
336538Srgrimes    for (dl = bundle->links; dl; dl = dl->next) {
337538Srgrimes      if (fp == &dl->physical->link.lcp.fsm)
338538Srgrimes        lost = dl;
339538Srgrimes      else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
340538Srgrimes        others_active++;
341538Srgrimes    }
342538Srgrimes
343538Srgrimes    if (bundle->ncp.mp.active) {
344538Srgrimes      bundle_CalculateBandwidth(bundle);
345538Srgrimes
346538Srgrimes      if (lost)
347538Srgrimes        mp_LinkLost(&bundle->ncp.mp, lost);
348538Srgrimes      else
349538Srgrimes        log_Printf(LogALERT, "Oops, lost an unrecognised datalink (%s) !\n",
350538Srgrimes                   fp->link->name);
351538Srgrimes    }
352538Srgrimes
353538Srgrimes    if (!others_active) {
354538Srgrimes      /* Down the NCPs.  We don't expect to get fsm_Close()d ourself ! */
355538Srgrimes      ncp2initial(&bundle->ncp);
356538Srgrimes      mp_Down(&bundle->ncp.mp);
357538Srgrimes    }
358538Srgrimes  }
359538Srgrimes}
360538Srgrimes
361538Srgrimesstatic void
362538Srgrimesbundle_LayerFinish(void *v, struct fsm *fp)
363538Srgrimes{
364538Srgrimes  /* The given fsm is now down (fp cannot be NULL)
365538Srgrimes   *
366538Srgrimes   * If it's the last NCP, fsm_Close all LCPs
367538Srgrimes   * If it's the last NCP, bring any MP layer down
368538Srgrimes   */
369538Srgrimes
370538Srgrimes  struct bundle *bundle = (struct bundle *)v;
371538Srgrimes  struct datalink *dl;
372538Srgrimes
373538Srgrimes  if (isncp(fp->proto) && !ncp_LayersUnfinished(&bundle->ncp)) {
374538Srgrimes    if (bundle_Phase(bundle) != PHASE_DEAD)
375538Srgrimes      bundle_NewPhase(bundle, PHASE_TERMINATE);
376538Srgrimes    for (dl = bundle->links; dl; dl = dl->next)
377538Srgrimes      if (dl->state == DATALINK_OPEN)
378538Srgrimes        datalink_Close(dl, CLOSE_STAYDOWN);
379538Srgrimes    fsm2initial(fp);
380538Srgrimes    mp_Down(&bundle->ncp.mp);
381538Srgrimes  }
382538Srgrimes}
383538Srgrimes
384538Srgrimesvoid
385538Srgrimesbundle_Close(struct bundle *bundle, const char *name, int how)
386538Srgrimes{
387538Srgrimes  /*
388538Srgrimes   * Please close the given datalink.
389538Srgrimes   * If name == NULL or name is the last datalink, fsm_Close all NCPs
390538Srgrimes   * (except our MP)
391538Srgrimes   * If it isn't the last datalink, just Close that datalink.
392538Srgrimes   */
393538Srgrimes
394538Srgrimes  struct datalink *dl, *this_dl;
395538Srgrimes  int others_active;
396538Srgrimes
397538Srgrimes  others_active = 0;
398538Srgrimes  this_dl = NULL;
399538Srgrimes
400538Srgrimes  for (dl = bundle->links; dl; dl = dl->next) {
401372Srgrimes    if (name && !strcasecmp(name, dl->name))
402372Srgrimes      this_dl = dl;
403372Srgrimes    if (name == NULL || this_dl == dl) {
404372Srgrimes      switch (how) {
405372Srgrimes        case CLOSE_LCP:
406372Srgrimes          datalink_DontHangup(dl);
407372Srgrimes          break;
408372Srgrimes        case CLOSE_STAYDOWN:
409372Srgrimes          datalink_StayDown(dl);
410372Srgrimes          break;
411372Srgrimes      }
412372Srgrimes    } else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
413372Srgrimes      others_active++;
414372Srgrimes  }
415372Srgrimes
416372Srgrimes  if (name && this_dl == NULL) {
417372Srgrimes    log_Printf(LogWARN, "%s: Invalid datalink name\n", name);
418372Srgrimes    return;
419372Srgrimes  }
420372Srgrimes
421372Srgrimes  if (!others_active) {
422372Srgrimes#ifndef NORADIUS
423372Srgrimes    if (bundle->radius.sessiontime)
424372Srgrimes      bundle_StopSessionTimer(bundle);
425372Srgrimes#endif
426372Srgrimes    bundle_StopIdleTimer(bundle);
427372Srgrimes    if (ncp_LayersUnfinished(&bundle->ncp))
428538Srgrimes      ncp_Close(&bundle->ncp);
429538Srgrimes    else {
430372Srgrimes      ncp2initial(&bundle->ncp);
431436Srgrimes      mp_Down(&bundle->ncp.mp);
432372Srgrimes      for (dl = bundle->links; dl; dl = dl->next)
433372Srgrimes        datalink_Close(dl, how);
434147Srgrimes    }
435238Sroot  } else if (this_dl && this_dl->state != DATALINK_CLOSED &&
436147Srgrimes             this_dl->state != DATALINK_HANGUP)
437147Srgrimes    datalink_Close(this_dl, how);
438372Srgrimes}
439372Srgrimes
440372Srgrimesvoid
441410Srgrimesbundle_Down(struct bundle *bundle, int how)
442147Srgrimes{
443372Srgrimes  struct datalink *dl;
444372Srgrimes
445372Srgrimes  for (dl = bundle->links; dl; dl = dl->next)
446376Srgrimes    datalink_Down(dl, how);
447376Srgrimes}
448372Srgrimes
449372Srgrimesstatic int
450372Srgrimesbundle_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
451372Srgrimes{
452372Srgrimes  struct bundle *bundle = descriptor2bundle(d);
453372Srgrimes  struct datalink *dl;
454372Srgrimes  int result, nlinks;
455372Srgrimes  u_short ifqueue;
456372Srgrimes  size_t queued;
457372Srgrimes
458372Srgrimes  result = 0;
459372Srgrimes
460372Srgrimes  /* If there are aren't many packets queued, look for some more. */
461372Srgrimes  for (nlinks = 0, dl = bundle->links; dl; dl = dl->next)
462372Srgrimes    nlinks++;
46337Srgrimes
464  if (nlinks) {
465    queued = r ? ncp_FillPhysicalQueues(&bundle->ncp, bundle) :
466                 ncp_QueueLen(&bundle->ncp);
467
468    if (r && (bundle->phase == PHASE_NETWORK ||
469              bundle->phys_type.all & PHYS_AUTO)) {
470      /* enough surplus so that we can tell if we're getting swamped */
471      ifqueue = nlinks > bundle->cfg.ifqueue ? nlinks : bundle->cfg.ifqueue;
472      if (queued < ifqueue) {
473        /* Not enough - select() for more */
474        if (bundle->choked.timer.state == TIMER_RUNNING)
475          timer_Stop(&bundle->choked.timer);	/* Not needed any more */
476        FD_SET(bundle->dev.fd, r);
477        if (*n < bundle->dev.fd + 1)
478          *n = bundle->dev.fd + 1;
479        log_Printf(LogTIMER, "%s: fdset(r) %d\n", TUN_NAME, bundle->dev.fd);
480        result++;
481      } else if (bundle->choked.timer.state == TIMER_STOPPED) {
482        bundle->choked.timer.func = bundle_ClearQueues;
483        bundle->choked.timer.name = "output choke";
484        bundle->choked.timer.load = bundle->cfg.choked.timeout * SECTICKS;
485        bundle->choked.timer.arg = bundle;
486        timer_Start(&bundle->choked.timer);
487      }
488    }
489  }
490
491#ifndef NORADIUS
492  result += descriptor_UpdateSet(&bundle->radius.desc, r, w, e, n);
493#endif
494
495  /* Which links need a select() ? */
496  for (dl = bundle->links; dl; dl = dl->next)
497    result += descriptor_UpdateSet(&dl->desc, r, w, e, n);
498
499  /*
500   * This *MUST* be called after the datalink UpdateSet()s as it
501   * might be ``holding'' one of the datalinks (death-row) and
502   * wants to be able to de-select() it from the descriptor set.
503   */
504  result += descriptor_UpdateSet(&bundle->ncp.mp.server.desc, r, w, e, n);
505
506  return result;
507}
508
509static int
510bundle_IsSet(struct fdescriptor *d, const fd_set *fdset)
511{
512  struct bundle *bundle = descriptor2bundle(d);
513  struct datalink *dl;
514
515  for (dl = bundle->links; dl; dl = dl->next)
516    if (descriptor_IsSet(&dl->desc, fdset))
517      return 1;
518
519#ifndef NORADIUS
520  if (descriptor_IsSet(&bundle->radius.desc, fdset))
521    return 1;
522#endif
523
524  if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
525    return 1;
526
527  return FD_ISSET(bundle->dev.fd, fdset);
528}
529
530static void
531bundle_DescriptorRead(struct fdescriptor *d, struct bundle *bundle,
532                      const fd_set *fdset)
533{
534  struct datalink *dl;
535  unsigned secs;
536  u_int32_t af;
537
538  if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
539    descriptor_Read(&bundle->ncp.mp.server.desc, bundle, fdset);
540
541  for (dl = bundle->links; dl; dl = dl->next)
542    if (descriptor_IsSet(&dl->desc, fdset))
543      descriptor_Read(&dl->desc, bundle, fdset);
544
545#ifndef NORADIUS
546  if (descriptor_IsSet(&bundle->radius.desc, fdset))
547    descriptor_Read(&bundle->radius.desc, bundle, fdset);
548#endif
549
550  if (FD_ISSET(bundle->dev.fd, fdset)) {
551    struct tun_data tun;
552    int n, pri;
553    u_char *data;
554    size_t sz;
555
556    if (bundle->dev.header) {
557      data = (u_char *)&tun;
558      sz = sizeof tun;
559    } else {
560      data = tun.data;
561      sz = sizeof tun.data;
562    }
563
564    /* something to read from tun */
565
566    n = read(bundle->dev.fd, data, sz);
567    if (n < 0) {
568      log_Printf(LogWARN, "%s: read: %s\n", bundle->dev.Name, strerror(errno));
569      return;
570    }
571
572    if (bundle->dev.header) {
573      n -= sz - sizeof tun.data;
574      if (n <= 0) {
575        log_Printf(LogERROR, "%s: read: Got only %d bytes of data !\n",
576                   bundle->dev.Name, n);
577        return;
578      }
579      af = ntohl(tun.header.family);
580#ifndef NOINET6
581      if (af != AF_INET && af != AF_INET6)
582#else
583      if (af != AF_INET)
584#endif
585        /* XXX: Should be maintaining drop/family counts ! */
586        return;
587    } else
588      af = AF_INET;
589
590    if (af == AF_INET && ((struct ip *)tun.data)->ip_dst.s_addr ==
591        bundle->ncp.ipcp.my_ip.s_addr) {
592      /* we've been asked to send something addressed *to* us :( */
593      if (Enabled(bundle, OPT_LOOPBACK)) {
594        pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.in,
595                          NULL, NULL);
596        if (pri >= 0) {
597          n += sz - sizeof tun.data;
598          write(bundle->dev.fd, data, n);
599          log_Printf(LogDEBUG, "Looped back packet addressed to myself\n");
600        }
601        return;
602      } else
603        log_Printf(LogDEBUG, "Oops - forwarding packet addressed to myself\n");
604    }
605
606    /*
607     * Process on-demand dialup. Output packets are queued within the tunnel
608     * device until the appropriate NCP is opened.
609     */
610
611    if (bundle_Phase(bundle) == PHASE_DEAD) {
612      /*
613       * Note, we must be in AUTO mode :-/ otherwise our interface should
614       * *not* be UP and we can't receive data
615       */
616      pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.dial,
617                        NULL, NULL);
618      if (pri >= 0)
619        bundle_Open(bundle, NULL, PHYS_AUTO, 0);
620      else
621        /*
622         * Drop the packet.  If we were to queue it, we'd just end up with
623         * a pile of timed-out data in our output queue by the time we get
624         * around to actually dialing.  We'd also prematurely reach the
625         * threshold at which we stop select()ing to read() the tun
626         * device - breaking auto-dial.
627         */
628        return;
629    }
630
631    secs = 0;
632    pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.out,
633                      NULL, &secs);
634    if (pri >= 0) {
635      /* Prepend the number of seconds timeout given in the filter */
636      tun.header.timeout = secs;
637      ncp_Enqueue(&bundle->ncp, af, pri, (char *)&tun, n + sizeof tun.header);
638    }
639  }
640}
641
642static int
643bundle_DescriptorWrite(struct fdescriptor *d, struct bundle *bundle,
644                       const fd_set *fdset)
645{
646  struct datalink *dl;
647  int result = 0;
648
649  /* This is not actually necessary as struct mpserver doesn't Write() */
650  if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
651    if (descriptor_Write(&bundle->ncp.mp.server.desc, bundle, fdset) == 1)
652      result++;
653
654  for (dl = bundle->links; dl; dl = dl->next)
655    if (descriptor_IsSet(&dl->desc, fdset))
656      switch (descriptor_Write(&dl->desc, bundle, fdset)) {
657      case -1:
658        datalink_ComeDown(dl, CLOSE_NORMAL);
659        break;
660      case 1:
661        result++;
662      }
663
664  return result;
665}
666
667void
668bundle_LockTun(struct bundle *bundle)
669{
670  FILE *lockfile;
671  char pidfile[PATH_MAX];
672
673  snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
674  lockfile = ID0fopen(pidfile, "w");
675  if (lockfile != NULL) {
676    fprintf(lockfile, "%d\n", (int)getpid());
677    fclose(lockfile);
678  }
679#ifndef RELEASE_CRUNCH
680  else
681    log_Printf(LogERROR, "Warning: Can't create %s: %s\n",
682               pidfile, strerror(errno));
683#endif
684}
685
686static void
687bundle_UnlockTun(struct bundle *bundle)
688{
689  char pidfile[PATH_MAX];
690
691  snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
692  ID0unlink(pidfile);
693}
694
695struct bundle *
696bundle_Create(const char *prefix, int type, int unit)
697{
698  static struct bundle bundle;		/* there can be only one */
699  int enoentcount, err, minunit, maxunit;
700  const char *ifname;
701#if defined(__FreeBSD__) && !defined(NOKLDLOAD)
702  int kldtried;
703#endif
704#if defined(TUNSIFMODE) || defined(TUNSLMODE) || defined(TUNSIFHEAD)
705  int iff;
706#endif
707
708  if (bundle.iface != NULL) {	/* Already allocated ! */
709    log_Printf(LogALERT, "bundle_Create:  There's only one BUNDLE !\n");
710    return NULL;
711  }
712
713  if (unit == -1) {
714    minunit = 0;
715    maxunit = -1;
716  } else {
717    minunit = unit;
718    maxunit = unit + 1;
719  }
720  err = ENOENT;
721  enoentcount = 0;
722#if defined(__FreeBSD__) && !defined(NOKLDLOAD)
723  kldtried = 0;
724#endif
725  for (bundle.unit = minunit; bundle.unit != maxunit; bundle.unit++) {
726    snprintf(bundle.dev.Name, sizeof bundle.dev.Name, "%s%d",
727             prefix, bundle.unit);
728    bundle.dev.fd = ID0open(bundle.dev.Name, O_RDWR);
729    if (bundle.dev.fd >= 0)
730      break;
731    else if (errno == ENXIO || errno == ENOENT) {
732#if defined(__FreeBSD__) && !defined(NOKLDLOAD)
733      if (bundle.unit == minunit && !kldtried++) {
734        /*
735         * Attempt to load the tunnel interface KLD if it isn't loaded
736         * already.
737         */
738        if (loadmodules(LOAD_VERBOSLY, "if_tun", NULL))
739          bundle.unit--;
740        continue;
741      }
742#endif
743      if (errno != ENOENT || ++enoentcount > 2) {
744        err = errno;
745	break;
746      }
747    } else
748      err = errno;
749  }
750
751  if (bundle.dev.fd < 0) {
752    if (unit == -1)
753      log_Printf(LogWARN, "No available tunnel devices found (%s)\n",
754                strerror(err));
755    else
756      log_Printf(LogWARN, "%s%d: %s\n", prefix, unit, strerror(err));
757    return NULL;
758  }
759
760  log_SetTun(bundle.unit);
761
762  ifname = strrchr(bundle.dev.Name, '/');
763  if (ifname == NULL)
764    ifname = bundle.dev.Name;
765  else
766    ifname++;
767
768  bundle.iface = iface_Create(ifname);
769  if (bundle.iface == NULL) {
770    close(bundle.dev.fd);
771    return NULL;
772  }
773
774#ifdef TUNSIFMODE
775  /* Make sure we're POINTOPOINT & IFF_MULTICAST */
776  iff = IFF_POINTOPOINT | IFF_MULTICAST;
777  if (ID0ioctl(bundle.dev.fd, TUNSIFMODE, &iff) < 0)
778    log_Printf(LogERROR, "bundle_Create: ioctl(TUNSIFMODE): %s\n",
779	       strerror(errno));
780#endif
781
782#ifdef TUNSLMODE
783  /* Make sure we're not prepending sockaddrs */
784  iff = 0;
785  if (ID0ioctl(bundle.dev.fd, TUNSLMODE, &iff) < 0)
786    log_Printf(LogERROR, "bundle_Create: ioctl(TUNSLMODE): %s\n",
787	       strerror(errno));
788#endif
789
790#ifdef TUNSIFHEAD
791  /* We want the address family please ! */
792  iff = 1;
793  if (ID0ioctl(bundle.dev.fd, TUNSIFHEAD, &iff) < 0) {
794    log_Printf(LogERROR, "bundle_Create: ioctl(TUNSIFHEAD): %s\n",
795	       strerror(errno));
796    bundle.dev.header = 0;
797  } else
798    bundle.dev.header = 1;
799#else
800#ifdef __OpenBSD__
801  /* Always present for OpenBSD */
802  bundle.dev.header = 1;
803#else
804  /*
805   * If TUNSIFHEAD isn't available and we're not OpenBSD, assume
806   * everything's AF_INET (hopefully the tun device won't pass us
807   * anything else !).
808   */
809  bundle.dev.header = 0;
810#endif
811#endif
812
813  log_Printf(LogPHASE, "Using interface: %s\n", ifname);
814
815  bundle.bandwidth = 0;
816  bundle.routing_seq = 0;
817  bundle.phase = PHASE_DEAD;
818  bundle.CleaningUp = 0;
819  bundle.NatEnabled = 0;
820
821  bundle.fsm.LayerStart = bundle_LayerStart;
822  bundle.fsm.LayerUp = bundle_LayerUp;
823  bundle.fsm.LayerDown = bundle_LayerDown;
824  bundle.fsm.LayerFinish = bundle_LayerFinish;
825  bundle.fsm.object = &bundle;
826
827  bundle.cfg.idle.timeout = NCP_IDLE_TIMEOUT;
828  bundle.cfg.idle.min_timeout = 0;
829  *bundle.cfg.auth.name = '\0';
830  *bundle.cfg.auth.key = '\0';
831  bundle.cfg.opt = OPT_IDCHECK | OPT_LOOPBACK | OPT_SROUTES | OPT_TCPMSSFIXUP |
832                   OPT_THROUGHPUT | OPT_UTMP;
833#ifndef NOINET6
834  bundle.cfg.opt |= OPT_IPCP;
835  if (probe.ipv6_available)
836    bundle.cfg.opt |= OPT_IPV6CP;
837#endif
838  *bundle.cfg.label = '\0';
839  bundle.cfg.ifqueue = DEF_IFQUEUE;
840  bundle.cfg.choked.timeout = CHOKED_TIMEOUT;
841  bundle.phys_type.all = type;
842  bundle.phys_type.open = 0;
843  bundle.upat = 0;
844
845  bundle.links = datalink_Create("deflink", &bundle, type);
846  if (bundle.links == NULL) {
847    log_Printf(LogALERT, "Cannot create data link: %s\n", strerror(errno));
848    iface_Destroy(bundle.iface);
849    bundle.iface = NULL;
850    close(bundle.dev.fd);
851    return NULL;
852  }
853
854  bundle.desc.type = BUNDLE_DESCRIPTOR;
855  bundle.desc.UpdateSet = bundle_UpdateSet;
856  bundle.desc.IsSet = bundle_IsSet;
857  bundle.desc.Read = bundle_DescriptorRead;
858  bundle.desc.Write = bundle_DescriptorWrite;
859
860  ncp_Init(&bundle.ncp, &bundle);
861
862  memset(&bundle.filter, '\0', sizeof bundle.filter);
863  bundle.filter.in.fragok = bundle.filter.in.logok = 1;
864  bundle.filter.in.name = "IN";
865  bundle.filter.out.fragok = bundle.filter.out.logok = 1;
866  bundle.filter.out.name = "OUT";
867  bundle.filter.dial.name = "DIAL";
868  bundle.filter.dial.logok = 1;
869  bundle.filter.alive.name = "ALIVE";
870  bundle.filter.alive.logok = 1;
871  {
872    int	i;
873    for (i = 0; i < MAXFILTERS; i++) {
874        bundle.filter.in.rule[i].f_action = A_NONE;
875        bundle.filter.out.rule[i].f_action = A_NONE;
876        bundle.filter.dial.rule[i].f_action = A_NONE;
877        bundle.filter.alive.rule[i].f_action = A_NONE;
878    }
879  }
880  memset(&bundle.idle.timer, '\0', sizeof bundle.idle.timer);
881  bundle.idle.done = 0;
882  bundle.notify.fd = -1;
883  memset(&bundle.choked.timer, '\0', sizeof bundle.choked.timer);
884#ifndef NORADIUS
885  radius_Init(&bundle.radius);
886#endif
887
888  /* Clean out any leftover crud */
889  iface_Clear(bundle.iface, &bundle.ncp, 0, IFACE_CLEAR_ALL);
890
891  bundle_LockTun(&bundle);
892
893  return &bundle;
894}
895
896static void
897bundle_DownInterface(struct bundle *bundle)
898{
899  route_IfDelete(bundle, 1);
900  iface_ClearFlags(bundle->iface->name, IFF_UP);
901}
902
903void
904bundle_Destroy(struct bundle *bundle)
905{
906  struct datalink *dl;
907
908  /*
909   * Clean up the interface.  We don't really need to do the timer_Stop()s,
910   * mp_Down(), iface_Clear() and bundle_DownInterface() unless we're getting
911   * out under exceptional conditions such as a descriptor exception.
912   */
913  timer_Stop(&bundle->idle.timer);
914  timer_Stop(&bundle->choked.timer);
915  mp_Down(&bundle->ncp.mp);
916  iface_Clear(bundle->iface, &bundle->ncp, 0, IFACE_CLEAR_ALL);
917  bundle_DownInterface(bundle);
918
919#ifndef NORADIUS
920  /* Tell the radius server the bad news */
921  radius_Destroy(&bundle->radius);
922#endif
923
924  /* Again, these are all DATALINK_CLOSED unless we're abending */
925  dl = bundle->links;
926  while (dl)
927    dl = datalink_Destroy(dl);
928
929  ncp_Destroy(&bundle->ncp);
930
931  close(bundle->dev.fd);
932  bundle_UnlockTun(bundle);
933
934  /* In case we never made PHASE_NETWORK */
935  bundle_Notify(bundle, EX_ERRDEAD);
936
937  iface_Destroy(bundle->iface);
938  bundle->iface = NULL;
939}
940
941void
942bundle_LinkClosed(struct bundle *bundle, struct datalink *dl)
943{
944  /*
945   * Our datalink has closed.
946   * CleanDatalinks() (called from DoLoop()) will remove closed
947   * BACKGROUND, FOREGROUND and DIRECT links.
948   * If it's the last data link, enter phase DEAD.
949   *
950   * NOTE: dl may not be in our list (bundle_SendDatalink()) !
951   */
952
953  struct datalink *odl;
954  int other_links;
955
956  log_SetTtyCommandMode(dl);
957
958  other_links = 0;
959  for (odl = bundle->links; odl; odl = odl->next)
960    if (odl != dl && odl->state != DATALINK_CLOSED)
961      other_links++;
962
963  if (!other_links) {
964    if (dl->physical->type != PHYS_AUTO)	/* Not in -auto mode */
965      bundle_DownInterface(bundle);
966    ncp2initial(&bundle->ncp);
967    mp_Down(&bundle->ncp.mp);
968    bundle_NewPhase(bundle, PHASE_DEAD);
969#ifndef NORADIUS
970    if (bundle->radius.sessiontime)
971      bundle_StopSessionTimer(bundle);
972#endif
973    bundle_StopIdleTimer(bundle);
974  }
975}
976
977void
978bundle_Open(struct bundle *bundle, const char *name, int mask, int force)
979{
980  /*
981   * Please open the given datalink, or all if name == NULL
982   */
983  struct datalink *dl;
984
985  for (dl = bundle->links; dl; dl = dl->next)
986    if (name == NULL || !strcasecmp(dl->name, name)) {
987      if ((mask & dl->physical->type) &&
988          (dl->state == DATALINK_CLOSED ||
989           (force && dl->state == DATALINK_OPENING &&
990            dl->dial.timer.state == TIMER_RUNNING) ||
991           dl->state == DATALINK_READY)) {
992        timer_Stop(&dl->dial.timer);	/* We're finished with this */
993        datalink_Up(dl, 1, 1);
994        if (mask & PHYS_AUTO)
995          break;			/* Only one AUTO link at a time */
996      }
997      if (name != NULL)
998        break;
999    }
1000}
1001
1002struct datalink *
1003bundle2datalink(struct bundle *bundle, const char *name)
1004{
1005  struct datalink *dl;
1006
1007  if (name != NULL) {
1008    for (dl = bundle->links; dl; dl = dl->next)
1009      if (!strcasecmp(dl->name, name))
1010        return dl;
1011  } else if (bundle->links && !bundle->links->next)
1012    return bundle->links;
1013
1014  return NULL;
1015}
1016
1017int
1018bundle_ShowLinks(struct cmdargs const *arg)
1019{
1020  struct datalink *dl;
1021  struct pppThroughput *t;
1022  unsigned long long octets;
1023  int secs;
1024
1025  for (dl = arg->bundle->links; dl; dl = dl->next) {
1026    octets = MAX(dl->physical->link.stats.total.in.OctetsPerSecond,
1027                 dl->physical->link.stats.total.out.OctetsPerSecond);
1028
1029    prompt_Printf(arg->prompt, "Name: %s [%s, %s]",
1030                  dl->name, mode2Nam(dl->physical->type), datalink_State(dl));
1031    if (dl->physical->link.stats.total.rolling && dl->state == DATALINK_OPEN)
1032      prompt_Printf(arg->prompt, " bandwidth %d, %llu bps (%llu bytes/sec)",
1033                    dl->mp.bandwidth ? dl->mp.bandwidth :
1034                                       physical_GetSpeed(dl->physical),
1035                    octets * 8, octets);
1036    prompt_Printf(arg->prompt, "\n");
1037  }
1038
1039  t = &arg->bundle->ncp.mp.link.stats.total;
1040  octets = MAX(t->in.OctetsPerSecond, t->out.OctetsPerSecond);
1041  secs = t->downtime ? 0 : throughput_uptime(t);
1042  if (secs > t->SamplePeriod)
1043    secs = t->SamplePeriod;
1044  if (secs)
1045    prompt_Printf(arg->prompt, "Currently averaging %llu bps (%llu bytes/sec)"
1046                  " over the last %d secs\n", octets * 8, octets, secs);
1047
1048  return 0;
1049}
1050
1051static const char *
1052optval(struct bundle *bundle, int bit)
1053{
1054  return (bundle->cfg.opt & bit) ? "enabled" : "disabled";
1055}
1056
1057int
1058bundle_ShowStatus(struct cmdargs const *arg)
1059{
1060  int remaining;
1061
1062  prompt_Printf(arg->prompt, "Phase %s\n", bundle_PhaseName(arg->bundle));
1063  prompt_Printf(arg->prompt, " Device:        %s\n", arg->bundle->dev.Name);
1064  prompt_Printf(arg->prompt, " Interface:     %s @ %lubps",
1065                arg->bundle->iface->name, arg->bundle->bandwidth);
1066
1067  if (arg->bundle->upat) {
1068    int secs = bundle_Uptime(arg->bundle);
1069
1070    prompt_Printf(arg->prompt, ", up time %d:%02d:%02d", secs / 3600,
1071                  (secs / 60) % 60, secs % 60);
1072  }
1073  prompt_Printf(arg->prompt, "\n Queued:        %lu of %u\n",
1074                (unsigned long)ncp_QueueLen(&arg->bundle->ncp),
1075                arg->bundle->cfg.ifqueue);
1076
1077  prompt_Printf(arg->prompt, "\nDefaults:\n");
1078  prompt_Printf(arg->prompt, " Label:             %s\n",
1079                arg->bundle->cfg.label);
1080  prompt_Printf(arg->prompt, " Auth name:         %s\n",
1081                arg->bundle->cfg.auth.name);
1082  prompt_Printf(arg->prompt, " Diagnostic socket: ");
1083  if (*server.cfg.sockname != '\0') {
1084    prompt_Printf(arg->prompt, "%s", server.cfg.sockname);
1085    if (server.cfg.mask != (mode_t)-1)
1086      prompt_Printf(arg->prompt, ", mask 0%03o", (int)server.cfg.mask);
1087    prompt_Printf(arg->prompt, "%s\n", server.fd == -1 ? " (not open)" : "");
1088  } else if (server.cfg.port != 0)
1089    prompt_Printf(arg->prompt, "TCP port %d%s\n", server.cfg.port,
1090                  server.fd == -1 ? " (not open)" : "");
1091  else
1092    prompt_Printf(arg->prompt, "none\n");
1093
1094  prompt_Printf(arg->prompt, " Choked Timer:      %ds\n",
1095                arg->bundle->cfg.choked.timeout);
1096
1097#ifndef NORADIUS
1098  radius_Show(&arg->bundle->radius, arg->prompt);
1099#endif
1100
1101  prompt_Printf(arg->prompt, " Idle Timer:        ");
1102  if (arg->bundle->cfg.idle.timeout) {
1103    prompt_Printf(arg->prompt, "%ds", arg->bundle->cfg.idle.timeout);
1104    if (arg->bundle->cfg.idle.min_timeout)
1105      prompt_Printf(arg->prompt, ", min %ds",
1106                    arg->bundle->cfg.idle.min_timeout);
1107    remaining = bundle_RemainingIdleTime(arg->bundle);
1108    if (remaining != -1)
1109      prompt_Printf(arg->prompt, " (%ds remaining)", remaining);
1110    prompt_Printf(arg->prompt, "\n");
1111  } else
1112    prompt_Printf(arg->prompt, "disabled\n");
1113
1114  prompt_Printf(arg->prompt, " Filter Decap:      %-20.20s",
1115                optval(arg->bundle, OPT_FILTERDECAP));
1116  prompt_Printf(arg->prompt, " ID check:          %s\n",
1117                optval(arg->bundle, OPT_IDCHECK));
1118  prompt_Printf(arg->prompt, " Iface-Alias:       %-20.20s",
1119                optval(arg->bundle, OPT_IFACEALIAS));
1120#ifndef NOINET6
1121  prompt_Printf(arg->prompt, " IPCP:              %s\n",
1122                optval(arg->bundle, OPT_IPCP));
1123  prompt_Printf(arg->prompt, " IPV6CP:            %-20.20s",
1124                optval(arg->bundle, OPT_IPV6CP));
1125#endif
1126  prompt_Printf(arg->prompt, " Keep-Session:      %s\n",
1127                optval(arg->bundle, OPT_KEEPSESSION));
1128  prompt_Printf(arg->prompt, " Loopback:          %-20.20s",
1129                optval(arg->bundle, OPT_LOOPBACK));
1130  prompt_Printf(arg->prompt, " PasswdAuth:        %s\n",
1131                optval(arg->bundle, OPT_PASSWDAUTH));
1132  prompt_Printf(arg->prompt, " Proxy:             %-20.20s",
1133                optval(arg->bundle, OPT_PROXY));
1134  prompt_Printf(arg->prompt, " Proxyall:          %s\n",
1135                optval(arg->bundle, OPT_PROXYALL));
1136  prompt_Printf(arg->prompt, " Sticky Routes:     %-20.20s",
1137                optval(arg->bundle, OPT_SROUTES));
1138  prompt_Printf(arg->prompt, " TCPMSS Fixup:      %s\n",
1139                optval(arg->bundle, OPT_TCPMSSFIXUP));
1140  prompt_Printf(arg->prompt, " Throughput:        %-20.20s",
1141                optval(arg->bundle, OPT_THROUGHPUT));
1142  prompt_Printf(arg->prompt, " Utmp Logging:      %s\n",
1143                optval(arg->bundle, OPT_UTMP));
1144
1145  return 0;
1146}
1147
1148static void
1149bundle_IdleTimeout(void *v)
1150{
1151  struct bundle *bundle = (struct bundle *)v;
1152
1153  log_Printf(LogPHASE, "Idle timer expired\n");
1154  bundle_StopIdleTimer(bundle);
1155  bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
1156}
1157
1158/*
1159 *  Start Idle timer. If timeout is reached, we call bundle_Close() to
1160 *  close LCP and link.
1161 */
1162void
1163bundle_StartIdleTimer(struct bundle *bundle, unsigned secs)
1164{
1165  timer_Stop(&bundle->idle.timer);
1166  if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) !=
1167      bundle->phys_type.open && bundle->cfg.idle.timeout) {
1168    time_t now = time(NULL);
1169
1170    if (secs == 0)
1171      secs = bundle->cfg.idle.timeout;
1172
1173    /* We want at least `secs' */
1174    if (bundle->cfg.idle.min_timeout > secs && bundle->upat) {
1175      int up = now - bundle->upat;
1176
1177      if ((long long)bundle->cfg.idle.min_timeout - up > (long long)secs)
1178        /* Only increase from the current `remaining' value */
1179        secs = bundle->cfg.idle.min_timeout - up;
1180    }
1181    bundle->idle.timer.func = bundle_IdleTimeout;
1182    bundle->idle.timer.name = "idle";
1183    bundle->idle.timer.load = secs * SECTICKS;
1184    bundle->idle.timer.arg = bundle;
1185    timer_Start(&bundle->idle.timer);
1186    bundle->idle.done = now + secs;
1187  }
1188}
1189
1190void
1191bundle_SetIdleTimer(struct bundle *bundle, int timeout, int min_timeout)
1192{
1193  bundle->cfg.idle.timeout = timeout;
1194  if (min_timeout >= 0)
1195    bundle->cfg.idle.min_timeout = min_timeout;
1196  if (ncp_LayersOpen(&bundle->ncp))
1197    bundle_StartIdleTimer(bundle, 0);
1198}
1199
1200void
1201bundle_StopIdleTimer(struct bundle *bundle)
1202{
1203  timer_Stop(&bundle->idle.timer);
1204  bundle->idle.done = 0;
1205}
1206
1207static int
1208bundle_RemainingIdleTime(struct bundle *bundle)
1209{
1210  if (bundle->idle.done)
1211    return bundle->idle.done - time(NULL);
1212  return -1;
1213}
1214
1215#ifndef NORADIUS
1216
1217static void
1218bundle_SessionTimeout(void *v)
1219{
1220  struct bundle *bundle = (struct bundle *)v;
1221
1222  log_Printf(LogPHASE, "Session-Timeout timer expired\n");
1223  bundle_StopSessionTimer(bundle);
1224  bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
1225}
1226
1227void
1228bundle_StartSessionTimer(struct bundle *bundle, unsigned secs)
1229{
1230  timer_Stop(&bundle->session.timer);
1231  if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) !=
1232      bundle->phys_type.open && bundle->radius.sessiontime) {
1233    time_t now = time(NULL);
1234
1235    if (secs == 0)
1236      secs = bundle->radius.sessiontime;
1237
1238    bundle->session.timer.func = bundle_SessionTimeout;
1239    bundle->session.timer.name = "session";
1240    bundle->session.timer.load = secs * SECTICKS;
1241    bundle->session.timer.arg = bundle;
1242    timer_Start(&bundle->session.timer);
1243    bundle->session.done = now + secs;
1244  }
1245}
1246
1247void
1248bundle_StopSessionTimer(struct bundle *bundle)
1249{
1250  timer_Stop(&bundle->session.timer);
1251  bundle->session.done = 0;
1252}
1253
1254#endif
1255
1256int
1257bundle_IsDead(struct bundle *bundle)
1258{
1259  return !bundle->links || (bundle->phase == PHASE_DEAD && bundle->CleaningUp);
1260}
1261
1262static struct datalink *
1263bundle_DatalinkLinkout(struct bundle *bundle, struct datalink *dl)
1264{
1265  struct datalink **dlp;
1266
1267  for (dlp = &bundle->links; *dlp; dlp = &(*dlp)->next)
1268    if (*dlp == dl) {
1269      *dlp = dl->next;
1270      dl->next = NULL;
1271      bundle_LinksRemoved(bundle);
1272      return dl;
1273    }
1274
1275  return NULL;
1276}
1277
1278static void
1279bundle_DatalinkLinkin(struct bundle *bundle, struct datalink *dl)
1280{
1281  struct datalink **dlp = &bundle->links;
1282
1283  while (*dlp)
1284    dlp = &(*dlp)->next;
1285
1286  *dlp = dl;
1287  dl->next = NULL;
1288
1289  bundle_LinkAdded(bundle, dl);
1290  mp_CheckAutoloadTimer(&bundle->ncp.mp);
1291}
1292
1293void
1294bundle_CleanDatalinks(struct bundle *bundle)
1295{
1296  struct datalink **dlp = &bundle->links;
1297  int found = 0;
1298
1299  while (*dlp)
1300    if ((*dlp)->state == DATALINK_CLOSED &&
1301        (*dlp)->physical->type &
1302        (PHYS_DIRECT|PHYS_BACKGROUND|PHYS_FOREGROUND)) {
1303      *dlp = datalink_Destroy(*dlp);
1304      found++;
1305    } else
1306      dlp = &(*dlp)->next;
1307
1308  if (found)
1309    bundle_LinksRemoved(bundle);
1310}
1311
1312int
1313bundle_DatalinkClone(struct bundle *bundle, struct datalink *dl,
1314                     const char *name)
1315{
1316  if (bundle2datalink(bundle, name)) {
1317    log_Printf(LogWARN, "Clone: %s: name already exists\n", name);
1318    return 0;
1319  }
1320
1321  bundle_DatalinkLinkin(bundle, datalink_Clone(dl, name));
1322  return 1;
1323}
1324
1325void
1326bundle_DatalinkRemove(struct bundle *bundle, struct datalink *dl)
1327{
1328  dl = bundle_DatalinkLinkout(bundle, dl);
1329  if (dl)
1330    datalink_Destroy(dl);
1331}
1332
1333void
1334bundle_SetLabel(struct bundle *bundle, const char *label)
1335{
1336  if (label)
1337    strncpy(bundle->cfg.label, label, sizeof bundle->cfg.label - 1);
1338  else
1339    *bundle->cfg.label = '\0';
1340}
1341
1342const char *
1343bundle_GetLabel(struct bundle *bundle)
1344{
1345  return *bundle->cfg.label ? bundle->cfg.label : NULL;
1346}
1347
1348int
1349bundle_LinkSize()
1350{
1351  struct iovec iov[SCATTER_SEGMENTS];
1352  int niov, expect, f;
1353
1354  iov[0].iov_len = strlen(Version) + 1;
1355  iov[0].iov_base = NULL;
1356  niov = 1;
1357  if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1358    log_Printf(LogERROR, "Cannot determine space required for link\n");
1359    return 0;
1360  }
1361
1362  for (f = expect = 0; f < niov; f++)
1363    expect += iov[f].iov_len;
1364
1365  return expect;
1366}
1367
1368void
1369bundle_ReceiveDatalink(struct bundle *bundle, int s)
1370{
1371  char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int) * SEND_MAXFD];
1372  int niov, expect, f, *fd, nfd, onfd, got;
1373  struct iovec iov[SCATTER_SEGMENTS];
1374  struct cmsghdr *cmsg;
1375  struct msghdr msg;
1376  struct datalink *dl;
1377  pid_t pid;
1378
1379  log_Printf(LogPHASE, "Receiving datalink\n");
1380
1381  /*
1382   * Create our scatter/gather array - passing NULL gets the space
1383   * allocation requirement rather than actually flattening the
1384   * structures.
1385   */
1386  iov[0].iov_len = strlen(Version) + 1;
1387  iov[0].iov_base = NULL;
1388  niov = 1;
1389  if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1390    log_Printf(LogERROR, "Cannot determine space required for link\n");
1391    return;
1392  }
1393
1394  /* Allocate the scatter/gather array for recvmsg() */
1395  for (f = expect = 0; f < niov; f++) {
1396    if ((iov[f].iov_base = malloc(iov[f].iov_len)) == NULL) {
1397      log_Printf(LogERROR, "Cannot allocate space to receive link\n");
1398      return;
1399    }
1400    if (f)
1401      expect += iov[f].iov_len;
1402  }
1403
1404  /* Set up our message */
1405  cmsg = (struct cmsghdr *)cmsgbuf;
1406  cmsg->cmsg_len = sizeof cmsgbuf;
1407  cmsg->cmsg_level = SOL_SOCKET;
1408  cmsg->cmsg_type = 0;
1409
1410  memset(&msg, '\0', sizeof msg);
1411  msg.msg_name = NULL;
1412  msg.msg_namelen = 0;
1413  msg.msg_iov = iov;
1414  msg.msg_iovlen = 1;		/* Only send the version at the first pass */
1415  msg.msg_control = cmsgbuf;
1416  msg.msg_controllen = sizeof cmsgbuf;
1417
1418  log_Printf(LogDEBUG, "Expecting %u scatter/gather bytes\n",
1419             (unsigned)iov[0].iov_len);
1420
1421  if ((got = recvmsg(s, &msg, MSG_WAITALL)) != iov[0].iov_len) {
1422    if (got == -1)
1423      log_Printf(LogERROR, "Failed recvmsg: %s\n", strerror(errno));
1424    else
1425      log_Printf(LogERROR, "Failed recvmsg: Got %d, not %u\n",
1426                 got, (unsigned)iov[0].iov_len);
1427    while (niov--)
1428      free(iov[niov].iov_base);
1429    return;
1430  }
1431
1432  if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) {
1433    log_Printf(LogERROR, "Recvmsg: no descriptors received !\n");
1434    while (niov--)
1435      free(iov[niov].iov_base);
1436    return;
1437  }
1438
1439  fd = (int *)CMSG_DATA(cmsg);
1440  nfd = ((caddr_t)cmsg + cmsg->cmsg_len - (caddr_t)fd) / sizeof(int);
1441
1442  if (nfd < 2) {
1443    log_Printf(LogERROR, "Recvmsg: %d descriptor%s received (too few) !\n",
1444               nfd, nfd == 1 ? "" : "s");
1445    while (nfd--)
1446      close(fd[nfd]);
1447    while (niov--)
1448      free(iov[niov].iov_base);
1449    return;
1450  }
1451
1452  /*
1453   * We've successfully received two or more open file descriptors
1454   * through our socket, plus a version string.  Make sure it's the
1455   * correct version, and drop the connection if it's not.
1456   */
1457  if (strncmp(Version, iov[0].iov_base, iov[0].iov_len)) {
1458    log_Printf(LogWARN, "Cannot receive datalink, incorrect version"
1459               " (\"%.*s\", not \"%s\")\n", (int)iov[0].iov_len,
1460               (char *)iov[0].iov_base, Version);
1461    while (nfd--)
1462      close(fd[nfd]);
1463    while (niov--)
1464      free(iov[niov].iov_base);
1465    return;
1466  }
1467
1468  /*
1469   * Everything looks good.  Send the other side our process id so that
1470   * they can transfer lock ownership, and wait for them to send the
1471   * actual link data.
1472   */
1473  pid = getpid();
1474  if ((got = write(fd[1], &pid, sizeof pid)) != sizeof pid) {
1475    if (got == -1)
1476      log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1477    else
1478      log_Printf(LogERROR, "Failed write: Got %d, not %d\n", got,
1479                 (int)(sizeof pid));
1480    while (nfd--)
1481      close(fd[nfd]);
1482    while (niov--)
1483      free(iov[niov].iov_base);
1484    return;
1485  }
1486
1487  if ((got = readv(fd[1], iov + 1, niov - 1)) != expect) {
1488    if (got == -1)
1489      log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1490    else
1491      log_Printf(LogERROR, "Failed write: Got %d, not %d\n", got, expect);
1492    while (nfd--)
1493      close(fd[nfd]);
1494    while (niov--)
1495      free(iov[niov].iov_base);
1496    return;
1497  }
1498  close(fd[1]);
1499
1500  onfd = nfd;	/* We've got this many in our array */
1501  nfd -= 2;	/* Don't include p->fd and our reply descriptor */
1502  niov = 1;	/* Skip the version id */
1503  dl = iov2datalink(bundle, iov, &niov, sizeof iov / sizeof *iov, fd[0],
1504                    fd + 2, &nfd);
1505  if (dl) {
1506
1507    if (nfd) {
1508      log_Printf(LogERROR, "bundle_ReceiveDatalink: Failed to handle %d "
1509                 "auxiliary file descriptors (%d remain)\n", onfd, nfd);
1510      datalink_Destroy(dl);
1511      while (nfd--)
1512        close(fd[onfd--]);
1513      close(fd[0]);
1514    } else {
1515      bundle_DatalinkLinkin(bundle, dl);
1516      datalink_AuthOk(dl);
1517      bundle_CalculateBandwidth(dl->bundle);
1518    }
1519  } else {
1520    while (nfd--)
1521      close(fd[onfd--]);
1522    close(fd[0]);
1523    close(fd[1]);
1524  }
1525
1526  free(iov[0].iov_base);
1527}
1528
1529void
1530bundle_SendDatalink(struct datalink *dl, int s, struct sockaddr_un *sun)
1531{
1532  char cmsgbuf[CMSG_SPACE(sizeof(int) * SEND_MAXFD)];
1533  const char *constlock;
1534  char *lock;
1535  struct cmsghdr *cmsg;
1536  struct msghdr msg;
1537  struct iovec iov[SCATTER_SEGMENTS];
1538  int niov, f, expect, newsid, fd[SEND_MAXFD], nfd, reply[2], got;
1539  pid_t newpid;
1540
1541  log_Printf(LogPHASE, "Transmitting datalink %s\n", dl->name);
1542
1543  /* Record the base device name for a lock transfer later */
1544  constlock = physical_LockedDevice(dl->physical);
1545  if (constlock) {
1546    lock = alloca(strlen(constlock) + 1);
1547    strcpy(lock, constlock);
1548  } else
1549    lock = NULL;
1550
1551  bundle_LinkClosed(dl->bundle, dl);
1552  bundle_DatalinkLinkout(dl->bundle, dl);
1553
1554  /* Build our scatter/gather array */
1555  iov[0].iov_len = strlen(Version) + 1;
1556  iov[0].iov_base = strdup(Version);
1557  niov = 1;
1558  nfd = 0;
1559
1560  fd[0] = datalink2iov(dl, iov, &niov, SCATTER_SEGMENTS, fd + 2, &nfd);
1561
1562  if (fd[0] != -1 && socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, reply) != -1) {
1563    /*
1564     * fd[1] is used to get the peer process id back, then to confirm that
1565     * we've transferred any device locks to that process id.
1566     */
1567    fd[1] = reply[1];
1568
1569    nfd += 2;			/* Include fd[0] and fd[1] */
1570    memset(&msg, '\0', sizeof msg);
1571
1572    msg.msg_name = NULL;
1573    msg.msg_namelen = 0;
1574    /*
1575     * Only send the version to start...  We used to send the whole lot, but
1576     * this caused problems with our RECVBUF size as a single link is about
1577     * 22k !  This way, we should bump into no limits.
1578     */
1579    msg.msg_iovlen = 1;
1580    msg.msg_iov = iov;
1581    msg.msg_control = cmsgbuf;
1582    msg.msg_controllen = CMSG_SPACE(sizeof(int) * nfd);
1583    msg.msg_flags = 0;
1584
1585    cmsg = (struct cmsghdr *)cmsgbuf;
1586    cmsg->cmsg_len = msg.msg_controllen;
1587    cmsg->cmsg_level = SOL_SOCKET;
1588    cmsg->cmsg_type = SCM_RIGHTS;
1589
1590    for (f = 0; f < nfd; f++)
1591      *((int *)CMSG_DATA(cmsg) + f) = fd[f];
1592
1593    for (f = 1, expect = 0; f < niov; f++)
1594      expect += iov[f].iov_len;
1595
1596    if (setsockopt(reply[0], SOL_SOCKET, SO_SNDBUF, &expect, sizeof(int)) == -1)
1597      log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1598                 strerror(errno));
1599    if (setsockopt(reply[1], SOL_SOCKET, SO_RCVBUF, &expect, sizeof(int)) == -1)
1600      log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1601                 strerror(errno));
1602
1603    log_Printf(LogDEBUG, "Sending %d descriptor%s and %u bytes in scatter"
1604               "/gather array\n", nfd, nfd == 1 ? "" : "s",
1605               (unsigned)iov[0].iov_len);
1606
1607    if ((got = sendmsg(s, &msg, 0)) == -1)
1608      log_Printf(LogERROR, "Failed sendmsg: %s: %s\n",
1609                 sun->sun_path, strerror(errno));
1610    else if (got != iov[0].iov_len)
1611      log_Printf(LogERROR, "%s: Failed initial sendmsg: Only sent %d of %u\n",
1612                 sun->sun_path, got, (unsigned)iov[0].iov_len);
1613    else {
1614      /* We must get the ACK before closing the descriptor ! */
1615      int res;
1616
1617      if ((got = read(reply[0], &newpid, sizeof newpid)) == sizeof newpid) {
1618        log_Printf(LogDEBUG, "Received confirmation from pid %d\n",
1619                   (int)newpid);
1620        if (lock && (res = ID0uu_lock_txfr(lock, newpid)) != UU_LOCK_OK)
1621            log_Printf(LogERROR, "uu_lock_txfr: %s\n", uu_lockerr(res));
1622
1623        log_Printf(LogDEBUG, "Transmitting link (%d bytes)\n", expect);
1624        if ((got = writev(reply[0], iov + 1, niov - 1)) != expect) {
1625          if (got == -1)
1626            log_Printf(LogERROR, "%s: Failed writev: %s\n",
1627                       sun->sun_path, strerror(errno));
1628          else
1629            log_Printf(LogERROR, "%s: Failed writev: Wrote %d of %d\n",
1630                       sun->sun_path, got, expect);
1631        }
1632      } else if (got == -1)
1633        log_Printf(LogERROR, "%s: Failed socketpair read: %s\n",
1634                   sun->sun_path, strerror(errno));
1635      else
1636        log_Printf(LogERROR, "%s: Failed socketpair read: Got %d of %d\n",
1637                   sun->sun_path, got, (int)(sizeof newpid));
1638    }
1639
1640    close(reply[0]);
1641    close(reply[1]);
1642
1643    newsid = Enabled(dl->bundle, OPT_KEEPSESSION) ||
1644             tcgetpgrp(fd[0]) == getpgrp();
1645    while (nfd)
1646      close(fd[--nfd]);
1647    if (newsid)
1648      bundle_setsid(dl->bundle, got != -1);
1649  }
1650  close(s);
1651
1652  while (niov--)
1653    free(iov[niov].iov_base);
1654}
1655
1656int
1657bundle_RenameDatalink(struct bundle *bundle, struct datalink *ndl,
1658                      const char *name)
1659{
1660  struct datalink *dl;
1661
1662  if (!strcasecmp(ndl->name, name))
1663    return 1;
1664
1665  for (dl = bundle->links; dl; dl = dl->next)
1666    if (!strcasecmp(dl->name, name))
1667      return 0;
1668
1669  datalink_Rename(ndl, name);
1670  return 1;
1671}
1672
1673int
1674bundle_SetMode(struct bundle *bundle, struct datalink *dl, int mode)
1675{
1676  int omode;
1677
1678  omode = dl->physical->type;
1679  if (omode == mode)
1680    return 1;
1681
1682  if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO))
1683    /* First auto link */
1684    if (bundle->ncp.ipcp.peer_ip.s_addr == INADDR_ANY) {
1685      log_Printf(LogWARN, "You must `set ifaddr' or `open' before"
1686                 " changing mode to %s\n", mode2Nam(mode));
1687      return 0;
1688    }
1689
1690  if (!datalink_SetMode(dl, mode))
1691    return 0;
1692
1693  if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO) &&
1694      bundle->phase != PHASE_NETWORK)
1695    /* First auto link, we need an interface */
1696    ipcp_InterfaceUp(&bundle->ncp.ipcp);
1697
1698  /* Regenerate phys_type and adjust idle timer */
1699  bundle_LinksRemoved(bundle);
1700
1701  return 1;
1702}
1703
1704void
1705bundle_setsid(struct bundle *bundle, int holdsession)
1706{
1707  /*
1708   * Lose the current session.  This means getting rid of our pid
1709   * too so that the tty device will really go away, and any getty
1710   * etc will be allowed to restart.
1711   */
1712  pid_t pid, orig;
1713  int fds[2];
1714  char done;
1715  struct datalink *dl;
1716
1717  if (!holdsession && bundle_IsDead(bundle)) {
1718    /*
1719     * No need to lose our session after all... we're going away anyway
1720     *
1721     * We should really stop the timer and pause if holdsession is set and
1722     * the bundle's dead, but that leaves other resources lying about :-(
1723     */
1724    return;
1725  }
1726
1727  orig = getpid();
1728  if (pipe(fds) == -1) {
1729    log_Printf(LogERROR, "pipe: %s\n", strerror(errno));
1730    return;
1731  }
1732  switch ((pid = fork())) {
1733    case -1:
1734      log_Printf(LogERROR, "fork: %s\n", strerror(errno));
1735      close(fds[0]);
1736      close(fds[1]);
1737      return;
1738    case 0:
1739      close(fds[1]);
1740      read(fds[0], &done, 1);		/* uu_locks are mine ! */
1741      close(fds[0]);
1742      if (pipe(fds) == -1) {
1743        log_Printf(LogERROR, "pipe(2): %s\n", strerror(errno));
1744        return;
1745      }
1746      switch ((pid = fork())) {
1747        case -1:
1748          log_Printf(LogERROR, "fork(2): %s\n", strerror(errno));
1749          close(fds[0]);
1750          close(fds[1]);
1751          return;
1752        case 0:
1753          close(fds[1]);
1754          bundle_LockTun(bundle);	/* update pid */
1755          read(fds[0], &done, 1);	/* uu_locks are mine ! */
1756          close(fds[0]);
1757          setsid();
1758          bundle_ChangedPID(bundle);
1759          log_Printf(LogDEBUG, "%d -> %d: %s session control\n",
1760                     (int)orig, (int)getpid(),
1761                     holdsession ? "Passed" : "Dropped");
1762          timer_InitService(0);		/* Start the Timer Service */
1763          break;
1764        default:
1765          close(fds[0]);
1766          /* Give away all our physical locks (to the final process) */
1767          for (dl = bundle->links; dl; dl = dl->next)
1768            if (dl->state != DATALINK_CLOSED)
1769              physical_ChangedPid(dl->physical, pid);
1770          write(fds[1], "!", 1);	/* done */
1771          close(fds[1]);
1772          _exit(0);
1773          break;
1774      }
1775      break;
1776    default:
1777      close(fds[0]);
1778      /* Give away all our physical locks (to the intermediate process) */
1779      for (dl = bundle->links; dl; dl = dl->next)
1780        if (dl->state != DATALINK_CLOSED)
1781          physical_ChangedPid(dl->physical, pid);
1782      write(fds[1], "!", 1);	/* done */
1783      close(fds[1]);
1784      if (holdsession) {
1785        int fd, status;
1786
1787        timer_TermService();
1788        signal(SIGPIPE, SIG_DFL);
1789        signal(SIGALRM, SIG_DFL);
1790        signal(SIGHUP, SIG_DFL);
1791        signal(SIGTERM, SIG_DFL);
1792        signal(SIGINT, SIG_DFL);
1793        signal(SIGQUIT, SIG_DFL);
1794        for (fd = getdtablesize(); fd >= 0; fd--)
1795          close(fd);
1796        /*
1797         * Reap the intermediate process.  As we're not exiting but the
1798         * intermediate is, we don't want it to become defunct.
1799         */
1800        waitpid(pid, &status, 0);
1801        /* Tweak our process arguments.... */
1802        SetTitle("session owner");
1803#ifndef NOSUID
1804        setuid(ID0realuid());
1805#endif
1806        /*
1807         * Hang around for a HUP.  This should happen as soon as the
1808         * ppp that we passed our ctty descriptor to closes it.
1809         * NOTE: If this process dies, the passed descriptor becomes
1810         *       invalid and will give a select() error by setting one
1811         *       of the error fds, aborting the other ppp.  We don't
1812         *       want that to happen !
1813         */
1814        pause();
1815      }
1816      _exit(0);
1817      break;
1818  }
1819}
1820
1821int
1822bundle_HighestState(struct bundle *bundle)
1823{
1824  struct datalink *dl;
1825  int result = DATALINK_CLOSED;
1826
1827  for (dl = bundle->links; dl; dl = dl->next)
1828    if (result < dl->state)
1829      result = dl->state;
1830
1831  return result;
1832}
1833
1834int
1835bundle_Exception(struct bundle *bundle, int fd)
1836{
1837  struct datalink *dl;
1838
1839  for (dl = bundle->links; dl; dl = dl->next)
1840    if (dl->physical->fd == fd) {
1841      datalink_Down(dl, CLOSE_NORMAL);
1842      return 1;
1843    }
1844
1845  return 0;
1846}
1847
1848void
1849bundle_AdjustFilters(struct bundle *bundle, struct ncpaddr *local,
1850                     struct ncpaddr *remote)
1851{
1852  filter_AdjustAddr(&bundle->filter.in, local, remote, NULL);
1853  filter_AdjustAddr(&bundle->filter.out, local, remote, NULL);
1854  filter_AdjustAddr(&bundle->filter.dial, local, remote, NULL);
1855  filter_AdjustAddr(&bundle->filter.alive, local, remote, NULL);
1856}
1857
1858void
1859bundle_AdjustDNS(struct bundle *bundle)
1860{
1861  struct in_addr *dns = bundle->ncp.ipcp.ns.dns;
1862
1863  filter_AdjustAddr(&bundle->filter.in, NULL, NULL, dns);
1864  filter_AdjustAddr(&bundle->filter.out, NULL, NULL, dns);
1865  filter_AdjustAddr(&bundle->filter.dial, NULL, NULL, dns);
1866  filter_AdjustAddr(&bundle->filter.alive, NULL, NULL, dns);
1867}
1868
1869void
1870bundle_CalculateBandwidth(struct bundle *bundle)
1871{
1872  struct datalink *dl;
1873  int sp, overhead, maxoverhead;
1874
1875  bundle->bandwidth = 0;
1876  bundle->iface->mtu = 0;
1877  maxoverhead = 0;
1878
1879  for (dl = bundle->links; dl; dl = dl->next) {
1880    overhead = ccp_MTUOverhead(&dl->physical->link.ccp);
1881    if (maxoverhead < overhead)
1882      maxoverhead = overhead;
1883    if (dl->state == DATALINK_OPEN) {
1884      if ((sp = dl->mp.bandwidth) == 0 &&
1885          (sp = physical_GetSpeed(dl->physical)) == 0)
1886        log_Printf(LogDEBUG, "%s: %s: Cannot determine bandwidth\n",
1887                   dl->name, dl->physical->name.full);
1888      else
1889        bundle->bandwidth += sp;
1890      if (!bundle->ncp.mp.active) {
1891        bundle->iface->mtu = dl->physical->link.lcp.his_mru;
1892        break;
1893      }
1894    }
1895  }
1896
1897  if (bundle->bandwidth == 0)
1898    bundle->bandwidth = 115200;		/* Shrug */
1899
1900  if (bundle->ncp.mp.active) {
1901    bundle->iface->mtu = bundle->ncp.mp.peer_mrru;
1902    overhead = ccp_MTUOverhead(&bundle->ncp.mp.link.ccp);
1903    if (maxoverhead < overhead)
1904      maxoverhead = overhead;
1905  } else if (!bundle->iface->mtu)
1906    bundle->iface->mtu = DEF_MRU;
1907
1908#ifndef NORADIUS
1909  if (bundle->radius.valid && bundle->radius.mtu &&
1910      bundle->radius.mtu < bundle->iface->mtu) {
1911    log_Printf(LogLCP, "Reducing MTU to radius value %lu\n",
1912               bundle->radius.mtu);
1913    bundle->iface->mtu = bundle->radius.mtu;
1914  }
1915#endif
1916
1917  if (maxoverhead) {
1918    log_Printf(LogLCP, "Reducing MTU from %d to %d (CCP requirement)\n",
1919               bundle->iface->mtu, bundle->iface->mtu - maxoverhead);
1920    bundle->iface->mtu -= maxoverhead;
1921  }
1922
1923  tun_configure(bundle);
1924
1925  route_UpdateMTU(bundle);
1926}
1927
1928void
1929bundle_AutoAdjust(struct bundle *bundle, int percent, int what)
1930{
1931  struct datalink *dl, *choice, *otherlinkup;
1932
1933  choice = otherlinkup = NULL;
1934  for (dl = bundle->links; dl; dl = dl->next)
1935    if (dl->physical->type == PHYS_AUTO) {
1936      if (dl->state == DATALINK_OPEN) {
1937        if (what == AUTO_DOWN) {
1938          if (choice)
1939            otherlinkup = choice;
1940          choice = dl;
1941        }
1942      } else if (dl->state == DATALINK_CLOSED) {
1943        if (what == AUTO_UP) {
1944          choice = dl;
1945          break;
1946        }
1947      } else {
1948        /* An auto link in an intermediate state - forget it for the moment */
1949        choice = NULL;
1950        break;
1951      }
1952    } else if (dl->state == DATALINK_OPEN && what == AUTO_DOWN)
1953      otherlinkup = dl;
1954
1955  if (choice) {
1956    if (what == AUTO_UP) {
1957      log_Printf(LogPHASE, "%d%% saturation -> Opening link ``%s''\n",
1958                 percent, choice->name);
1959      datalink_Up(choice, 1, 1);
1960      mp_CheckAutoloadTimer(&bundle->ncp.mp);
1961    } else if (otherlinkup) {	/* Only bring the second-last link down */
1962      log_Printf(LogPHASE, "%d%% saturation -> Closing link ``%s''\n",
1963                 percent, choice->name);
1964      datalink_Close(choice, CLOSE_STAYDOWN);
1965      mp_CheckAutoloadTimer(&bundle->ncp.mp);
1966    }
1967  }
1968}
1969
1970int
1971bundle_WantAutoloadTimer(struct bundle *bundle)
1972{
1973  struct datalink *dl;
1974  int autolink, opened;
1975
1976  if (bundle->phase == PHASE_NETWORK) {
1977    for (autolink = opened = 0, dl = bundle->links; dl; dl = dl->next)
1978      if (dl->physical->type == PHYS_AUTO) {
1979        if (++autolink == 2 || (autolink == 1 && opened))
1980          /* Two auto links or one auto and one open in NETWORK phase */
1981          return 1;
1982      } else if (dl->state == DATALINK_OPEN) {
1983        opened++;
1984        if (autolink)
1985          /* One auto and one open link in NETWORK phase */
1986          return 1;
1987      }
1988  }
1989
1990  return 0;
1991}
1992
1993void
1994bundle_ChangedPID(struct bundle *bundle)
1995{
1996#ifdef TUNSIFPID
1997  ioctl(bundle->dev.fd, TUNSIFPID, 0);
1998#endif
1999}
2000
2001int
2002bundle_Uptime(struct bundle *bundle)
2003{
2004  if (bundle->upat)
2005    return time(NULL) - bundle->upat;
2006
2007  return 0;
2008}
2009