bundle.c revision 81697
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 81697 2001-08-15 13:53:38Z 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#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 */
750  iff = IFF_POINTOPOINT;
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  if (!iface_SetFlags(bundle.iface->name, IFF_UP)) {
788    iface_Destroy(bundle.iface);
789    bundle.iface = NULL;
790    close(bundle.dev.fd);
791    return NULL;
792  }
793
794  log_Printf(LogPHASE, "Using interface: %s\n", ifname);
795
796  bundle.bandwidth = 0;
797  bundle.routing_seq = 0;
798  bundle.phase = PHASE_DEAD;
799  bundle.CleaningUp = 0;
800  bundle.NatEnabled = 0;
801
802  bundle.fsm.LayerStart = bundle_LayerStart;
803  bundle.fsm.LayerUp = bundle_LayerUp;
804  bundle.fsm.LayerDown = bundle_LayerDown;
805  bundle.fsm.LayerFinish = bundle_LayerFinish;
806  bundle.fsm.object = &bundle;
807
808  bundle.cfg.idle.timeout = NCP_IDLE_TIMEOUT;
809  bundle.cfg.idle.min_timeout = 0;
810  *bundle.cfg.auth.name = '\0';
811  *bundle.cfg.auth.key = '\0';
812  bundle.cfg.opt = OPT_IDCHECK | OPT_LOOPBACK | OPT_SROUTES | OPT_TCPMSSFIXUP |
813                   OPT_THROUGHPUT | OPT_UTMP;
814#ifndef NOINET6
815  bundle.cfg.opt |= OPT_IPCP;
816  if (probe.ipv6_available)
817    bundle.cfg.opt |= OPT_IPV6CP;
818#endif
819  *bundle.cfg.label = '\0';
820  bundle.cfg.ifqueue = DEF_IFQUEUE;
821  bundle.cfg.choked.timeout = CHOKED_TIMEOUT;
822  bundle.phys_type.all = type;
823  bundle.phys_type.open = 0;
824  bundle.upat = 0;
825
826  bundle.links = datalink_Create("deflink", &bundle, type);
827  if (bundle.links == NULL) {
828    log_Printf(LogALERT, "Cannot create data link: %s\n", strerror(errno));
829    iface_Destroy(bundle.iface);
830    bundle.iface = NULL;
831    close(bundle.dev.fd);
832    return NULL;
833  }
834
835  bundle.desc.type = BUNDLE_DESCRIPTOR;
836  bundle.desc.UpdateSet = bundle_UpdateSet;
837  bundle.desc.IsSet = bundle_IsSet;
838  bundle.desc.Read = bundle_DescriptorRead;
839  bundle.desc.Write = bundle_DescriptorWrite;
840
841  ncp_Init(&bundle.ncp, &bundle);
842
843  memset(&bundle.filter, '\0', sizeof bundle.filter);
844  bundle.filter.in.fragok = bundle.filter.in.logok = 1;
845  bundle.filter.in.name = "IN";
846  bundle.filter.out.fragok = bundle.filter.out.logok = 1;
847  bundle.filter.out.name = "OUT";
848  bundle.filter.dial.name = "DIAL";
849  bundle.filter.dial.logok = 1;
850  bundle.filter.alive.name = "ALIVE";
851  bundle.filter.alive.logok = 1;
852  {
853    int	i;
854    for (i = 0; i < MAXFILTERS; i++) {
855        bundle.filter.in.rule[i].f_action = A_NONE;
856        bundle.filter.out.rule[i].f_action = A_NONE;
857        bundle.filter.dial.rule[i].f_action = A_NONE;
858        bundle.filter.alive.rule[i].f_action = A_NONE;
859    }
860  }
861  memset(&bundle.idle.timer, '\0', sizeof bundle.idle.timer);
862  bundle.idle.done = 0;
863  bundle.notify.fd = -1;
864  memset(&bundle.choked.timer, '\0', sizeof bundle.choked.timer);
865#ifndef NORADIUS
866  radius_Init(&bundle.radius);
867#endif
868
869  /* Clean out any leftover crud */
870  iface_Clear(bundle.iface, &bundle.ncp, 0, IFACE_CLEAR_ALL);
871
872  bundle_LockTun(&bundle);
873
874  return &bundle;
875}
876
877static void
878bundle_DownInterface(struct bundle *bundle)
879{
880  route_IfDelete(bundle, 1);
881  iface_ClearFlags(bundle->iface->name, IFF_UP);
882}
883
884void
885bundle_Destroy(struct bundle *bundle)
886{
887  struct datalink *dl;
888
889  /*
890   * Clean up the interface.  We don't really need to do the timer_Stop()s,
891   * mp_Down(), iface_Clear() and bundle_DownInterface() unless we're getting
892   * out under exceptional conditions such as a descriptor exception.
893   */
894  timer_Stop(&bundle->idle.timer);
895  timer_Stop(&bundle->choked.timer);
896  mp_Down(&bundle->ncp.mp);
897  iface_Clear(bundle->iface, &bundle->ncp, 0, IFACE_CLEAR_ALL);
898  bundle_DownInterface(bundle);
899
900#ifndef NORADIUS
901  /* Tell the radius server the bad news */
902  radius_Destroy(&bundle->radius);
903#endif
904
905  /* Again, these are all DATALINK_CLOSED unless we're abending */
906  dl = bundle->links;
907  while (dl)
908    dl = datalink_Destroy(dl);
909
910  ncp_Destroy(&bundle->ncp);
911
912  close(bundle->dev.fd);
913  bundle_UnlockTun(bundle);
914
915  /* In case we never made PHASE_NETWORK */
916  bundle_Notify(bundle, EX_ERRDEAD);
917
918  iface_Destroy(bundle->iface);
919  bundle->iface = NULL;
920}
921
922void
923bundle_LinkClosed(struct bundle *bundle, struct datalink *dl)
924{
925  /*
926   * Our datalink has closed.
927   * CleanDatalinks() (called from DoLoop()) will remove closed
928   * BACKGROUND, FOREGROUND and DIRECT links.
929   * If it's the last data link, enter phase DEAD.
930   *
931   * NOTE: dl may not be in our list (bundle_SendDatalink()) !
932   */
933
934  struct datalink *odl;
935  int other_links;
936
937  log_SetTtyCommandMode(dl);
938
939  other_links = 0;
940  for (odl = bundle->links; odl; odl = odl->next)
941    if (odl != dl && odl->state != DATALINK_CLOSED)
942      other_links++;
943
944  if (!other_links) {
945    if (dl->physical->type != PHYS_AUTO)	/* Not in -auto mode */
946      bundle_DownInterface(bundle);
947    ncp2initial(&bundle->ncp);
948    bundle_NewPhase(bundle, PHASE_DEAD);
949    bundle_StopIdleTimer(bundle);
950  }
951}
952
953void
954bundle_Open(struct bundle *bundle, const char *name, int mask, int force)
955{
956  /*
957   * Please open the given datalink, or all if name == NULL
958   */
959  struct datalink *dl;
960
961  for (dl = bundle->links; dl; dl = dl->next)
962    if (name == NULL || !strcasecmp(dl->name, name)) {
963      if ((mask & dl->physical->type) &&
964          (dl->state == DATALINK_CLOSED ||
965           (force && dl->state == DATALINK_OPENING &&
966            dl->dial.timer.state == TIMER_RUNNING) ||
967           dl->state == DATALINK_READY)) {
968        timer_Stop(&dl->dial.timer);	/* We're finished with this */
969        datalink_Up(dl, 1, 1);
970        if (mask & PHYS_AUTO)
971          break;			/* Only one AUTO link at a time */
972      }
973      if (name != NULL)
974        break;
975    }
976}
977
978struct datalink *
979bundle2datalink(struct bundle *bundle, const char *name)
980{
981  struct datalink *dl;
982
983  if (name != NULL) {
984    for (dl = bundle->links; dl; dl = dl->next)
985      if (!strcasecmp(dl->name, name))
986        return dl;
987  } else if (bundle->links && !bundle->links->next)
988    return bundle->links;
989
990  return NULL;
991}
992
993int
994bundle_ShowLinks(struct cmdargs const *arg)
995{
996  struct datalink *dl;
997  struct pppThroughput *t;
998  unsigned long long octets;
999  int secs;
1000
1001  for (dl = arg->bundle->links; dl; dl = dl->next) {
1002    octets = MAX(dl->physical->link.stats.total.in.OctetsPerSecond,
1003                 dl->physical->link.stats.total.out.OctetsPerSecond);
1004
1005    prompt_Printf(arg->prompt, "Name: %s [%s, %s]",
1006                  dl->name, mode2Nam(dl->physical->type), datalink_State(dl));
1007    if (dl->physical->link.stats.total.rolling && dl->state == DATALINK_OPEN)
1008      prompt_Printf(arg->prompt, " bandwidth %d, %llu bps (%llu bytes/sec)",
1009                    dl->mp.bandwidth ? dl->mp.bandwidth :
1010                                       physical_GetSpeed(dl->physical),
1011                    octets * 8, octets);
1012    prompt_Printf(arg->prompt, "\n");
1013  }
1014
1015  t = &arg->bundle->ncp.mp.link.stats.total;
1016  octets = MAX(t->in.OctetsPerSecond, t->out.OctetsPerSecond);
1017  secs = t->downtime ? 0 : throughput_uptime(t);
1018  if (secs > t->SamplePeriod)
1019    secs = t->SamplePeriod;
1020  if (secs)
1021    prompt_Printf(arg->prompt, "Currently averaging %llu bps (%llu bytes/sec)"
1022                  " over the last %d secs\n", octets * 8, octets, secs);
1023
1024  return 0;
1025}
1026
1027static const char *
1028optval(struct bundle *bundle, int bit)
1029{
1030  return (bundle->cfg.opt & bit) ? "enabled" : "disabled";
1031}
1032
1033int
1034bundle_ShowStatus(struct cmdargs const *arg)
1035{
1036  int remaining;
1037
1038  prompt_Printf(arg->prompt, "Phase %s\n", bundle_PhaseName(arg->bundle));
1039  prompt_Printf(arg->prompt, " Device:        %s\n", arg->bundle->dev.Name);
1040  prompt_Printf(arg->prompt, " Interface:     %s @ %lubps",
1041                arg->bundle->iface->name, arg->bundle->bandwidth);
1042
1043  if (arg->bundle->upat) {
1044    int secs = time(NULL) - arg->bundle->upat;
1045
1046    prompt_Printf(arg->prompt, ", up time %d:%02d:%02d", secs / 3600,
1047                  (secs / 60) % 60, secs % 60);
1048  }
1049  prompt_Printf(arg->prompt, "\n Queued:        %lu of %u\n",
1050                (unsigned long)ncp_QueueLen(&arg->bundle->ncp),
1051                arg->bundle->cfg.ifqueue);
1052
1053  prompt_Printf(arg->prompt, "\nDefaults:\n");
1054  prompt_Printf(arg->prompt, " Label:             %s\n",
1055                arg->bundle->cfg.label);
1056  prompt_Printf(arg->prompt, " Auth name:         %s\n",
1057                arg->bundle->cfg.auth.name);
1058  prompt_Printf(arg->prompt, " Diagnostic socket: ");
1059  if (*server.cfg.sockname != '\0') {
1060    prompt_Printf(arg->prompt, "%s", server.cfg.sockname);
1061    if (server.cfg.mask != (mode_t)-1)
1062      prompt_Printf(arg->prompt, ", mask 0%03o", (int)server.cfg.mask);
1063    prompt_Printf(arg->prompt, "%s\n", server.fd == -1 ? " (not open)" : "");
1064  } else if (server.cfg.port != 0)
1065    prompt_Printf(arg->prompt, "TCP port %d%s\n", server.cfg.port,
1066                  server.fd == -1 ? " (not open)" : "");
1067  else
1068    prompt_Printf(arg->prompt, "none\n");
1069
1070  prompt_Printf(arg->prompt, " Choked Timer:      %ds\n",
1071                arg->bundle->cfg.choked.timeout);
1072
1073#ifndef NORADIUS
1074  radius_Show(&arg->bundle->radius, arg->prompt);
1075#endif
1076
1077  prompt_Printf(arg->prompt, " Idle Timer:        ");
1078  if (arg->bundle->cfg.idle.timeout) {
1079    prompt_Printf(arg->prompt, "%ds", arg->bundle->cfg.idle.timeout);
1080    if (arg->bundle->cfg.idle.min_timeout)
1081      prompt_Printf(arg->prompt, ", min %ds",
1082                    arg->bundle->cfg.idle.min_timeout);
1083    remaining = bundle_RemainingIdleTime(arg->bundle);
1084    if (remaining != -1)
1085      prompt_Printf(arg->prompt, " (%ds remaining)", remaining);
1086    prompt_Printf(arg->prompt, "\n");
1087  } else
1088    prompt_Printf(arg->prompt, "disabled\n");
1089
1090  prompt_Printf(arg->prompt, " Filter Decap:      %-20.20s",
1091                optval(arg->bundle, OPT_FILTERDECAP));
1092  prompt_Printf(arg->prompt, " ID check:          %s\n",
1093                optval(arg->bundle, OPT_IDCHECK));
1094  prompt_Printf(arg->prompt, " Iface-Alias:       %-20.20s",
1095                optval(arg->bundle, OPT_IFACEALIAS));
1096#ifndef NOINET6
1097  prompt_Printf(arg->prompt, " IPCP:              %s\n",
1098                optval(arg->bundle, OPT_IPCP));
1099  prompt_Printf(arg->prompt, " IPV6CP:            %-20.20s",
1100                optval(arg->bundle, OPT_IPV6CP));
1101#endif
1102  prompt_Printf(arg->prompt, " Keep-Session:      %s\n",
1103                optval(arg->bundle, OPT_KEEPSESSION));
1104  prompt_Printf(arg->prompt, " Loopback:          %-20.20s",
1105                optval(arg->bundle, OPT_LOOPBACK));
1106  prompt_Printf(arg->prompt, " PasswdAuth:        %s\n",
1107                optval(arg->bundle, OPT_PASSWDAUTH));
1108  prompt_Printf(arg->prompt, " Proxy:             %-20.20s",
1109                optval(arg->bundle, OPT_PROXY));
1110  prompt_Printf(arg->prompt, " Proxyall:          %s\n",
1111                optval(arg->bundle, OPT_PROXYALL));
1112  prompt_Printf(arg->prompt, " Sticky Routes:     %-20.20s",
1113                optval(arg->bundle, OPT_SROUTES));
1114  prompt_Printf(arg->prompt, " TCPMSS Fixup:      %s\n",
1115                optval(arg->bundle, OPT_TCPMSSFIXUP));
1116  prompt_Printf(arg->prompt, " Throughput:        %-20.20s",
1117                optval(arg->bundle, OPT_THROUGHPUT));
1118  prompt_Printf(arg->prompt, " Utmp Logging:      %s\n",
1119                optval(arg->bundle, OPT_UTMP));
1120
1121  return 0;
1122}
1123
1124static void
1125bundle_IdleTimeout(void *v)
1126{
1127  struct bundle *bundle = (struct bundle *)v;
1128
1129  log_Printf(LogPHASE, "Idle timer expired\n");
1130  bundle_StopIdleTimer(bundle);
1131  bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
1132}
1133
1134/*
1135 *  Start Idle timer. If timeout is reached, we call bundle_Close() to
1136 *  close LCP and link.
1137 */
1138void
1139bundle_StartIdleTimer(struct bundle *bundle, unsigned secs)
1140{
1141  timer_Stop(&bundle->idle.timer);
1142  if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) !=
1143      bundle->phys_type.open && bundle->cfg.idle.timeout) {
1144    time_t now = time(NULL);
1145
1146    if (secs == 0)
1147      secs = bundle->cfg.idle.timeout;
1148
1149    /* We want at least `secs' */
1150    if (bundle->cfg.idle.min_timeout > secs && bundle->upat) {
1151      int up = now - bundle->upat;
1152
1153      if ((long long)bundle->cfg.idle.min_timeout - up > (long long)secs)
1154        /* Only increase from the current `remaining' value */
1155        secs = bundle->cfg.idle.min_timeout - up;
1156    }
1157    bundle->idle.timer.func = bundle_IdleTimeout;
1158    bundle->idle.timer.name = "idle";
1159    bundle->idle.timer.load = secs * SECTICKS;
1160    bundle->idle.timer.arg = bundle;
1161    timer_Start(&bundle->idle.timer);
1162    bundle->idle.done = now + secs;
1163  }
1164}
1165
1166void
1167bundle_SetIdleTimer(struct bundle *bundle, int timeout, int min_timeout)
1168{
1169  bundle->cfg.idle.timeout = timeout;
1170  if (min_timeout >= 0)
1171    bundle->cfg.idle.min_timeout = min_timeout;
1172  if (ncp_LayersOpen(&bundle->ncp))
1173    bundle_StartIdleTimer(bundle, 0);
1174}
1175
1176void
1177bundle_StopIdleTimer(struct bundle *bundle)
1178{
1179  timer_Stop(&bundle->idle.timer);
1180  bundle->idle.done = 0;
1181}
1182
1183static int
1184bundle_RemainingIdleTime(struct bundle *bundle)
1185{
1186  if (bundle->idle.done)
1187    return bundle->idle.done - time(NULL);
1188  return -1;
1189}
1190
1191int
1192bundle_IsDead(struct bundle *bundle)
1193{
1194  return !bundle->links || (bundle->phase == PHASE_DEAD && bundle->CleaningUp);
1195}
1196
1197static struct datalink *
1198bundle_DatalinkLinkout(struct bundle *bundle, struct datalink *dl)
1199{
1200  struct datalink **dlp;
1201
1202  for (dlp = &bundle->links; *dlp; dlp = &(*dlp)->next)
1203    if (*dlp == dl) {
1204      *dlp = dl->next;
1205      dl->next = NULL;
1206      bundle_LinksRemoved(bundle);
1207      return dl;
1208    }
1209
1210  return NULL;
1211}
1212
1213static void
1214bundle_DatalinkLinkin(struct bundle *bundle, struct datalink *dl)
1215{
1216  struct datalink **dlp = &bundle->links;
1217
1218  while (*dlp)
1219    dlp = &(*dlp)->next;
1220
1221  *dlp = dl;
1222  dl->next = NULL;
1223
1224  bundle_LinkAdded(bundle, dl);
1225  mp_CheckAutoloadTimer(&bundle->ncp.mp);
1226}
1227
1228void
1229bundle_CleanDatalinks(struct bundle *bundle)
1230{
1231  struct datalink **dlp = &bundle->links;
1232  int found = 0;
1233
1234  while (*dlp)
1235    if ((*dlp)->state == DATALINK_CLOSED &&
1236        (*dlp)->physical->type &
1237        (PHYS_DIRECT|PHYS_BACKGROUND|PHYS_FOREGROUND)) {
1238      *dlp = datalink_Destroy(*dlp);
1239      found++;
1240    } else
1241      dlp = &(*dlp)->next;
1242
1243  if (found)
1244    bundle_LinksRemoved(bundle);
1245}
1246
1247int
1248bundle_DatalinkClone(struct bundle *bundle, struct datalink *dl,
1249                     const char *name)
1250{
1251  if (bundle2datalink(bundle, name)) {
1252    log_Printf(LogWARN, "Clone: %s: name already exists\n", name);
1253    return 0;
1254  }
1255
1256  bundle_DatalinkLinkin(bundle, datalink_Clone(dl, name));
1257  return 1;
1258}
1259
1260void
1261bundle_DatalinkRemove(struct bundle *bundle, struct datalink *dl)
1262{
1263  dl = bundle_DatalinkLinkout(bundle, dl);
1264  if (dl)
1265    datalink_Destroy(dl);
1266}
1267
1268void
1269bundle_SetLabel(struct bundle *bundle, const char *label)
1270{
1271  if (label)
1272    strncpy(bundle->cfg.label, label, sizeof bundle->cfg.label - 1);
1273  else
1274    *bundle->cfg.label = '\0';
1275}
1276
1277const char *
1278bundle_GetLabel(struct bundle *bundle)
1279{
1280  return *bundle->cfg.label ? bundle->cfg.label : NULL;
1281}
1282
1283int
1284bundle_LinkSize()
1285{
1286  struct iovec iov[SCATTER_SEGMENTS];
1287  int niov, expect, f;
1288
1289  iov[0].iov_len = strlen(Version) + 1;
1290  iov[0].iov_base = NULL;
1291  niov = 1;
1292  if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1293    log_Printf(LogERROR, "Cannot determine space required for link\n");
1294    return 0;
1295  }
1296
1297  for (f = expect = 0; f < niov; f++)
1298    expect += iov[f].iov_len;
1299
1300  return expect;
1301}
1302
1303void
1304bundle_ReceiveDatalink(struct bundle *bundle, int s)
1305{
1306  char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int) * SEND_MAXFD];
1307  int niov, expect, f, *fd, nfd, onfd, got;
1308  struct iovec iov[SCATTER_SEGMENTS];
1309  struct cmsghdr *cmsg;
1310  struct msghdr msg;
1311  struct datalink *dl;
1312  pid_t pid;
1313
1314  log_Printf(LogPHASE, "Receiving datalink\n");
1315
1316  /*
1317   * Create our scatter/gather array - passing NULL gets the space
1318   * allocation requirement rather than actually flattening the
1319   * structures.
1320   */
1321  iov[0].iov_len = strlen(Version) + 1;
1322  iov[0].iov_base = NULL;
1323  niov = 1;
1324  if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1325    log_Printf(LogERROR, "Cannot determine space required for link\n");
1326    return;
1327  }
1328
1329  /* Allocate the scatter/gather array for recvmsg() */
1330  for (f = expect = 0; f < niov; f++) {
1331    if ((iov[f].iov_base = malloc(iov[f].iov_len)) == NULL) {
1332      log_Printf(LogERROR, "Cannot allocate space to receive link\n");
1333      return;
1334    }
1335    if (f)
1336      expect += iov[f].iov_len;
1337  }
1338
1339  /* Set up our message */
1340  cmsg = (struct cmsghdr *)cmsgbuf;
1341  cmsg->cmsg_len = sizeof cmsgbuf;
1342  cmsg->cmsg_level = SOL_SOCKET;
1343  cmsg->cmsg_type = 0;
1344
1345  memset(&msg, '\0', sizeof msg);
1346  msg.msg_name = NULL;
1347  msg.msg_namelen = 0;
1348  msg.msg_iov = iov;
1349  msg.msg_iovlen = 1;		/* Only send the version at the first pass */
1350  msg.msg_control = cmsgbuf;
1351  msg.msg_controllen = sizeof cmsgbuf;
1352
1353  log_Printf(LogDEBUG, "Expecting %u scatter/gather bytes\n",
1354             (unsigned)iov[0].iov_len);
1355
1356  if ((got = recvmsg(s, &msg, MSG_WAITALL)) != iov[0].iov_len) {
1357    if (got == -1)
1358      log_Printf(LogERROR, "Failed recvmsg: %s\n", strerror(errno));
1359    else
1360      log_Printf(LogERROR, "Failed recvmsg: Got %d, not %u\n",
1361                 got, (unsigned)iov[0].iov_len);
1362    while (niov--)
1363      free(iov[niov].iov_base);
1364    return;
1365  }
1366
1367  if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) {
1368    log_Printf(LogERROR, "Recvmsg: no descriptors received !\n");
1369    while (niov--)
1370      free(iov[niov].iov_base);
1371    return;
1372  }
1373
1374  fd = (int *)(cmsg + 1);
1375  nfd = (cmsg->cmsg_len - sizeof *cmsg) / sizeof(int);
1376
1377  if (nfd < 2) {
1378    log_Printf(LogERROR, "Recvmsg: %d descriptor%s received (too few) !\n",
1379               nfd, nfd == 1 ? "" : "s");
1380    while (nfd--)
1381      close(fd[nfd]);
1382    while (niov--)
1383      free(iov[niov].iov_base);
1384    return;
1385  }
1386
1387  /*
1388   * We've successfully received two or more open file descriptors
1389   * through our socket, plus a version string.  Make sure it's the
1390   * correct version, and drop the connection if it's not.
1391   */
1392  if (strncmp(Version, iov[0].iov_base, iov[0].iov_len)) {
1393    log_Printf(LogWARN, "Cannot receive datalink, incorrect version"
1394               " (\"%.*s\", not \"%s\")\n", (int)iov[0].iov_len,
1395               (char *)iov[0].iov_base, Version);
1396    while (nfd--)
1397      close(fd[nfd]);
1398    while (niov--)
1399      free(iov[niov].iov_base);
1400    return;
1401  }
1402
1403  /*
1404   * Everything looks good.  Send the other side our process id so that
1405   * they can transfer lock ownership, and wait for them to send the
1406   * actual link data.
1407   */
1408  pid = getpid();
1409  if ((got = write(fd[1], &pid, sizeof pid)) != sizeof pid) {
1410    if (got == -1)
1411      log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1412    else
1413      log_Printf(LogERROR, "Failed write: Got %d, not %d\n", got,
1414                 (int)(sizeof pid));
1415    while (nfd--)
1416      close(fd[nfd]);
1417    while (niov--)
1418      free(iov[niov].iov_base);
1419    return;
1420  }
1421
1422  if ((got = readv(fd[1], iov + 1, niov - 1)) != expect) {
1423    if (got == -1)
1424      log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1425    else
1426      log_Printf(LogERROR, "Failed write: Got %d, not %d\n", got, expect);
1427    while (nfd--)
1428      close(fd[nfd]);
1429    while (niov--)
1430      free(iov[niov].iov_base);
1431    return;
1432  }
1433  close(fd[1]);
1434
1435  onfd = nfd;	/* We've got this many in our array */
1436  nfd -= 2;	/* Don't include p->fd and our reply descriptor */
1437  niov = 1;	/* Skip the version id */
1438  dl = iov2datalink(bundle, iov, &niov, sizeof iov / sizeof *iov, fd[0],
1439                    fd + 2, &nfd);
1440  if (dl) {
1441
1442    if (nfd) {
1443      log_Printf(LogERROR, "bundle_ReceiveDatalink: Failed to handle %d "
1444                 "auxiliary file descriptors (%d remain)\n", onfd, nfd);
1445      datalink_Destroy(dl);
1446      while (nfd--)
1447        close(fd[onfd--]);
1448      close(fd[0]);
1449    } else {
1450      bundle_DatalinkLinkin(bundle, dl);
1451      datalink_AuthOk(dl);
1452      bundle_CalculateBandwidth(dl->bundle);
1453    }
1454  } else {
1455    while (nfd--)
1456      close(fd[onfd--]);
1457    close(fd[0]);
1458    close(fd[1]);
1459  }
1460
1461  free(iov[0].iov_base);
1462}
1463
1464void
1465bundle_SendDatalink(struct datalink *dl, int s, struct sockaddr_un *sun)
1466{
1467  char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int) * SEND_MAXFD];
1468  const char *constlock;
1469  char *lock;
1470  struct cmsghdr *cmsg;
1471  struct msghdr msg;
1472  struct iovec iov[SCATTER_SEGMENTS];
1473  int niov, f, expect, newsid, fd[SEND_MAXFD], nfd, reply[2], got;
1474  pid_t newpid;
1475
1476  log_Printf(LogPHASE, "Transmitting datalink %s\n", dl->name);
1477
1478  /* Record the base device name for a lock transfer later */
1479  constlock = physical_LockedDevice(dl->physical);
1480  if (constlock) {
1481    lock = alloca(strlen(constlock) + 1);
1482    strcpy(lock, constlock);
1483  } else
1484    lock = NULL;
1485
1486  bundle_LinkClosed(dl->bundle, dl);
1487  bundle_DatalinkLinkout(dl->bundle, dl);
1488
1489  /* Build our scatter/gather array */
1490  iov[0].iov_len = strlen(Version) + 1;
1491  iov[0].iov_base = strdup(Version);
1492  niov = 1;
1493  nfd = 0;
1494
1495  fd[0] = datalink2iov(dl, iov, &niov, SCATTER_SEGMENTS, fd + 2, &nfd);
1496
1497  if (fd[0] != -1 && socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, reply) != -1) {
1498    /*
1499     * fd[1] is used to get the peer process id back, then to confirm that
1500     * we've transferred any device locks to that process id.
1501     */
1502    fd[1] = reply[1];
1503
1504    nfd += 2;			/* Include fd[0] and fd[1] */
1505    memset(&msg, '\0', sizeof msg);
1506
1507    msg.msg_name = NULL;
1508    msg.msg_namelen = 0;
1509    /*
1510     * Only send the version to start...  We used to send the whole lot, but
1511     * this caused problems with our RECVBUF size as a single link is about
1512     * 22k !  This way, we should bump into no limits.
1513     */
1514    msg.msg_iovlen = 1;
1515    msg.msg_iov = iov;
1516    msg.msg_control = cmsgbuf;
1517    msg.msg_controllen = sizeof *cmsg + sizeof(int) * nfd;
1518    msg.msg_flags = 0;
1519
1520    cmsg = (struct cmsghdr *)cmsgbuf;
1521    cmsg->cmsg_len = msg.msg_controllen;
1522    cmsg->cmsg_level = SOL_SOCKET;
1523    cmsg->cmsg_type = SCM_RIGHTS;
1524
1525    for (f = 0; f < nfd; f++)
1526      *((int *)(cmsg + 1) + f) = fd[f];
1527
1528    for (f = 1, expect = 0; f < niov; f++)
1529      expect += iov[f].iov_len;
1530
1531    if (setsockopt(reply[0], SOL_SOCKET, SO_SNDBUF, &expect, sizeof(int)) == -1)
1532      log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1533                 strerror(errno));
1534    if (setsockopt(reply[1], SOL_SOCKET, SO_RCVBUF, &expect, sizeof(int)) == -1)
1535      log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1536                 strerror(errno));
1537
1538    log_Printf(LogDEBUG, "Sending %d descriptor%s and %u bytes in scatter"
1539               "/gather array\n", nfd, nfd == 1 ? "" : "s",
1540               (unsigned)iov[0].iov_len);
1541
1542    if ((got = sendmsg(s, &msg, 0)) == -1)
1543      log_Printf(LogERROR, "Failed sendmsg: %s: %s\n",
1544                 sun->sun_path, strerror(errno));
1545    else if (got != iov[0].iov_len)
1546      log_Printf(LogERROR, "%s: Failed initial sendmsg: Only sent %d of %u\n",
1547                 sun->sun_path, got, (unsigned)iov[0].iov_len);
1548    else {
1549      /* We must get the ACK before closing the descriptor ! */
1550      int res;
1551
1552      if ((got = read(reply[0], &newpid, sizeof newpid)) == sizeof newpid) {
1553        log_Printf(LogDEBUG, "Received confirmation from pid %d\n",
1554                   (int)newpid);
1555        if (lock && (res = ID0uu_lock_txfr(lock, newpid)) != UU_LOCK_OK)
1556            log_Printf(LogERROR, "uu_lock_txfr: %s\n", uu_lockerr(res));
1557
1558        log_Printf(LogDEBUG, "Transmitting link (%d bytes)\n", expect);
1559        if ((got = writev(reply[0], iov + 1, niov - 1)) != expect) {
1560          if (got == -1)
1561            log_Printf(LogERROR, "%s: Failed writev: %s\n",
1562                       sun->sun_path, strerror(errno));
1563          else
1564            log_Printf(LogERROR, "%s: Failed writev: Wrote %d of %d\n",
1565                       sun->sun_path, got, expect);
1566        }
1567      } else if (got == -1)
1568        log_Printf(LogERROR, "%s: Failed socketpair read: %s\n",
1569                   sun->sun_path, strerror(errno));
1570      else
1571        log_Printf(LogERROR, "%s: Failed socketpair read: Got %d of %d\n",
1572                   sun->sun_path, got, (int)(sizeof newpid));
1573    }
1574
1575    close(reply[0]);
1576    close(reply[1]);
1577
1578    newsid = Enabled(dl->bundle, OPT_KEEPSESSION) ||
1579             tcgetpgrp(fd[0]) == getpgrp();
1580    while (nfd)
1581      close(fd[--nfd]);
1582    if (newsid)
1583      bundle_setsid(dl->bundle, got != -1);
1584  }
1585  close(s);
1586
1587  while (niov--)
1588    free(iov[niov].iov_base);
1589}
1590
1591int
1592bundle_RenameDatalink(struct bundle *bundle, struct datalink *ndl,
1593                      const char *name)
1594{
1595  struct datalink *dl;
1596
1597  if (!strcasecmp(ndl->name, name))
1598    return 1;
1599
1600  for (dl = bundle->links; dl; dl = dl->next)
1601    if (!strcasecmp(dl->name, name))
1602      return 0;
1603
1604  datalink_Rename(ndl, name);
1605  return 1;
1606}
1607
1608int
1609bundle_SetMode(struct bundle *bundle, struct datalink *dl, int mode)
1610{
1611  int omode;
1612
1613  omode = dl->physical->type;
1614  if (omode == mode)
1615    return 1;
1616
1617  if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO))
1618    /* First auto link */
1619    if (bundle->ncp.ipcp.peer_ip.s_addr == INADDR_ANY) {
1620      log_Printf(LogWARN, "You must `set ifaddr' or `open' before"
1621                 " changing mode to %s\n", mode2Nam(mode));
1622      return 0;
1623    }
1624
1625  if (!datalink_SetMode(dl, mode))
1626    return 0;
1627
1628  if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO) &&
1629      bundle->phase != PHASE_NETWORK)
1630    /* First auto link, we need an interface */
1631    ipcp_InterfaceUp(&bundle->ncp.ipcp);
1632
1633  /* Regenerate phys_type and adjust idle timer */
1634  bundle_LinksRemoved(bundle);
1635
1636  return 1;
1637}
1638
1639void
1640bundle_setsid(struct bundle *bundle, int holdsession)
1641{
1642  /*
1643   * Lose the current session.  This means getting rid of our pid
1644   * too so that the tty device will really go away, and any getty
1645   * etc will be allowed to restart.
1646   */
1647  pid_t pid, orig;
1648  int fds[2];
1649  char done;
1650  struct datalink *dl;
1651
1652  if (!holdsession && bundle_IsDead(bundle)) {
1653    /*
1654     * No need to lose our session after all... we're going away anyway
1655     *
1656     * We should really stop the timer and pause if holdsession is set and
1657     * the bundle's dead, but that leaves other resources lying about :-(
1658     */
1659    return;
1660  }
1661
1662  orig = getpid();
1663  if (pipe(fds) == -1) {
1664    log_Printf(LogERROR, "pipe: %s\n", strerror(errno));
1665    return;
1666  }
1667  switch ((pid = fork())) {
1668    case -1:
1669      log_Printf(LogERROR, "fork: %s\n", strerror(errno));
1670      close(fds[0]);
1671      close(fds[1]);
1672      return;
1673    case 0:
1674      close(fds[1]);
1675      read(fds[0], &done, 1);		/* uu_locks are mine ! */
1676      close(fds[0]);
1677      if (pipe(fds) == -1) {
1678        log_Printf(LogERROR, "pipe(2): %s\n", strerror(errno));
1679        return;
1680      }
1681      switch ((pid = fork())) {
1682        case -1:
1683          log_Printf(LogERROR, "fork(2): %s\n", strerror(errno));
1684          close(fds[0]);
1685          close(fds[1]);
1686          return;
1687        case 0:
1688          close(fds[1]);
1689          bundle_LockTun(bundle);	/* update pid */
1690          read(fds[0], &done, 1);	/* uu_locks are mine ! */
1691          close(fds[0]);
1692          setsid();
1693          bundle_ChangedPID(bundle);
1694          log_Printf(LogDEBUG, "%d -> %d: %s session control\n",
1695                     (int)orig, (int)getpid(),
1696                     holdsession ? "Passed" : "Dropped");
1697          timer_InitService(0);		/* Start the Timer Service */
1698          break;
1699        default:
1700          close(fds[0]);
1701          /* Give away all our physical locks (to the final process) */
1702          for (dl = bundle->links; dl; dl = dl->next)
1703            if (dl->state != DATALINK_CLOSED)
1704              physical_ChangedPid(dl->physical, pid);
1705          write(fds[1], "!", 1);	/* done */
1706          close(fds[1]);
1707          _exit(0);
1708          break;
1709      }
1710      break;
1711    default:
1712      close(fds[0]);
1713      /* Give away all our physical locks (to the intermediate process) */
1714      for (dl = bundle->links; dl; dl = dl->next)
1715        if (dl->state != DATALINK_CLOSED)
1716          physical_ChangedPid(dl->physical, pid);
1717      write(fds[1], "!", 1);	/* done */
1718      close(fds[1]);
1719      if (holdsession) {
1720        int fd, status;
1721
1722        timer_TermService();
1723        signal(SIGPIPE, SIG_DFL);
1724        signal(SIGALRM, SIG_DFL);
1725        signal(SIGHUP, SIG_DFL);
1726        signal(SIGTERM, SIG_DFL);
1727        signal(SIGINT, SIG_DFL);
1728        signal(SIGQUIT, SIG_DFL);
1729        for (fd = getdtablesize(); fd >= 0; fd--)
1730          close(fd);
1731        /*
1732         * Reap the intermediate process.  As we're not exiting but the
1733         * intermediate is, we don't want it to become defunct.
1734         */
1735        waitpid(pid, &status, 0);
1736        /* Tweak our process arguments.... */
1737        SetTitle("session owner");
1738#ifndef NOSUID
1739        setuid(ID0realuid());
1740#endif
1741        /*
1742         * Hang around for a HUP.  This should happen as soon as the
1743         * ppp that we passed our ctty descriptor to closes it.
1744         * NOTE: If this process dies, the passed descriptor becomes
1745         *       invalid and will give a select() error by setting one
1746         *       of the error fds, aborting the other ppp.  We don't
1747         *       want that to happen !
1748         */
1749        pause();
1750      }
1751      _exit(0);
1752      break;
1753  }
1754}
1755
1756int
1757bundle_HighestState(struct bundle *bundle)
1758{
1759  struct datalink *dl;
1760  int result = DATALINK_CLOSED;
1761
1762  for (dl = bundle->links; dl; dl = dl->next)
1763    if (result < dl->state)
1764      result = dl->state;
1765
1766  return result;
1767}
1768
1769int
1770bundle_Exception(struct bundle *bundle, int fd)
1771{
1772  struct datalink *dl;
1773
1774  for (dl = bundle->links; dl; dl = dl->next)
1775    if (dl->physical->fd == fd) {
1776      datalink_Down(dl, CLOSE_NORMAL);
1777      return 1;
1778    }
1779
1780  return 0;
1781}
1782
1783void
1784bundle_AdjustFilters(struct bundle *bundle, struct ncpaddr *local,
1785                     struct ncpaddr *remote)
1786{
1787  filter_AdjustAddr(&bundle->filter.in, local, remote, NULL);
1788  filter_AdjustAddr(&bundle->filter.out, local, remote, NULL);
1789  filter_AdjustAddr(&bundle->filter.dial, local, remote, NULL);
1790  filter_AdjustAddr(&bundle->filter.alive, local, remote, NULL);
1791}
1792
1793void
1794bundle_AdjustDNS(struct bundle *bundle)
1795{
1796  struct in_addr *dns = bundle->ncp.ipcp.ns.dns;
1797
1798  filter_AdjustAddr(&bundle->filter.in, NULL, NULL, dns);
1799  filter_AdjustAddr(&bundle->filter.out, NULL, NULL, dns);
1800  filter_AdjustAddr(&bundle->filter.dial, NULL, NULL, dns);
1801  filter_AdjustAddr(&bundle->filter.alive, NULL, NULL, dns);
1802}
1803
1804void
1805bundle_CalculateBandwidth(struct bundle *bundle)
1806{
1807  struct datalink *dl;
1808  int sp, overhead, maxoverhead;
1809
1810  bundle->bandwidth = 0;
1811  bundle->iface->mtu = 0;
1812  maxoverhead = 0;
1813
1814  for (dl = bundle->links; dl; dl = dl->next) {
1815    overhead = ccp_MTUOverhead(&dl->physical->link.ccp);
1816    if (maxoverhead < overhead)
1817      maxoverhead = overhead;
1818    if (dl->state == DATALINK_OPEN) {
1819      if ((sp = dl->mp.bandwidth) == 0 &&
1820          (sp = physical_GetSpeed(dl->physical)) == 0)
1821        log_Printf(LogDEBUG, "%s: %s: Cannot determine bandwidth\n",
1822                   dl->name, dl->physical->name.full);
1823      else
1824        bundle->bandwidth += sp;
1825      if (!bundle->ncp.mp.active) {
1826        bundle->iface->mtu = dl->physical->link.lcp.his_mru;
1827        break;
1828      }
1829    }
1830  }
1831
1832  if(bundle->bandwidth == 0)
1833    bundle->bandwidth = 115200;		/* Shrug */
1834
1835  if (bundle->ncp.mp.active) {
1836    bundle->iface->mtu = bundle->ncp.mp.peer_mrru;
1837    overhead = ccp_MTUOverhead(&bundle->ncp.mp.link.ccp);
1838    if (maxoverhead < overhead)
1839      maxoverhead = overhead;
1840  } else if (!bundle->iface->mtu)
1841    bundle->iface->mtu = DEF_MRU;
1842
1843#ifndef NORADIUS
1844  if (bundle->radius.valid && bundle->radius.mtu &&
1845      bundle->radius.mtu < bundle->iface->mtu) {
1846    log_Printf(LogLCP, "Reducing MTU to radius value %lu\n",
1847               bundle->radius.mtu);
1848    bundle->iface->mtu = bundle->radius.mtu;
1849  }
1850#endif
1851
1852  if (maxoverhead) {
1853    log_Printf(LogLCP, "Reducing MTU from %d to %d (CCP requirement)\n",
1854               bundle->iface->mtu, bundle->iface->mtu - maxoverhead);
1855    bundle->iface->mtu -= maxoverhead;
1856  }
1857
1858  tun_configure(bundle);
1859
1860  route_UpdateMTU(bundle);
1861}
1862
1863void
1864bundle_AutoAdjust(struct bundle *bundle, int percent, int what)
1865{
1866  struct datalink *dl, *choice, *otherlinkup;
1867
1868  choice = otherlinkup = NULL;
1869  for (dl = bundle->links; dl; dl = dl->next)
1870    if (dl->physical->type == PHYS_AUTO) {
1871      if (dl->state == DATALINK_OPEN) {
1872        if (what == AUTO_DOWN) {
1873          if (choice)
1874            otherlinkup = choice;
1875          choice = dl;
1876        }
1877      } else if (dl->state == DATALINK_CLOSED) {
1878        if (what == AUTO_UP) {
1879          choice = dl;
1880          break;
1881        }
1882      } else {
1883        /* An auto link in an intermediate state - forget it for the moment */
1884        choice = NULL;
1885        break;
1886      }
1887    } else if (dl->state == DATALINK_OPEN && what == AUTO_DOWN)
1888      otherlinkup = dl;
1889
1890  if (choice) {
1891    if (what == AUTO_UP) {
1892      log_Printf(LogPHASE, "%d%% saturation -> Opening link ``%s''\n",
1893                 percent, choice->name);
1894      datalink_Up(choice, 1, 1);
1895      mp_CheckAutoloadTimer(&bundle->ncp.mp);
1896    } else if (otherlinkup) {	/* Only bring the second-last link down */
1897      log_Printf(LogPHASE, "%d%% saturation -> Closing link ``%s''\n",
1898                 percent, choice->name);
1899      datalink_Close(choice, CLOSE_STAYDOWN);
1900      mp_CheckAutoloadTimer(&bundle->ncp.mp);
1901    }
1902  }
1903}
1904
1905int
1906bundle_WantAutoloadTimer(struct bundle *bundle)
1907{
1908  struct datalink *dl;
1909  int autolink, opened;
1910
1911  if (bundle->phase == PHASE_NETWORK) {
1912    for (autolink = opened = 0, dl = bundle->links; dl; dl = dl->next)
1913      if (dl->physical->type == PHYS_AUTO) {
1914        if (++autolink == 2 || (autolink == 1 && opened))
1915          /* Two auto links or one auto and one open in NETWORK phase */
1916          return 1;
1917      } else if (dl->state == DATALINK_OPEN) {
1918        opened++;
1919        if (autolink)
1920          /* One auto and one open link in NETWORK phase */
1921          return 1;
1922      }
1923  }
1924
1925  return 0;
1926}
1927
1928void
1929bundle_ChangedPID(struct bundle *bundle)
1930{
1931#ifdef TUNSIFPID
1932  ioctl(bundle->dev.fd, TUNSIFPID, 0);
1933#endif
1934}
1935