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