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