bundle.c revision 42321
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 *	$Id: bundle.c,v 1.42 1998/12/14 19:24:28 brian Exp $
27 */
28
29#include <sys/param.h>
30#include <sys/socket.h>
31#include <netinet/in.h>
32#include <net/if.h>
33#include <arpa/inet.h>
34#include <net/route.h>
35#include <net/if_dl.h>
36#include <netinet/in_systm.h>
37#include <netinet/ip.h>
38#include <sys/un.h>
39
40#include <errno.h>
41#include <fcntl.h>
42#include <paths.h>
43#include <stdio.h>
44#include <stdlib.h>
45#include <string.h>
46#include <sys/ioctl.h>
47#include <sys/uio.h>
48#include <sys/wait.h>
49#include <termios.h>
50#include <unistd.h>
51
52#ifndef NOALIAS
53#ifdef __OpenBSD__
54#include "alias.h"
55#else
56#include <alias.h>
57#endif
58#endif
59#include "defs.h"
60#include "command.h"
61#include "mbuf.h"
62#include "log.h"
63#include "id.h"
64#include "timer.h"
65#include "fsm.h"
66#include "iplist.h"
67#include "lqr.h"
68#include "hdlc.h"
69#include "throughput.h"
70#include "slcompress.h"
71#include "ipcp.h"
72#include "filter.h"
73#include "descriptor.h"
74#include "route.h"
75#include "lcp.h"
76#include "ccp.h"
77#include "link.h"
78#include "mp.h"
79#include "bundle.h"
80#include "async.h"
81#include "physical.h"
82#include "modem.h"
83#include "auth.h"
84#include "lcpproto.h"
85#include "chap.h"
86#include "tun.h"
87#include "prompt.h"
88#include "chat.h"
89#include "cbcp.h"
90#include "datalink.h"
91#include "ip.h"
92#include "iface.h"
93
94#define SCATTER_SEGMENTS 4	/* version, datalink, name, physical */
95#define SOCKET_OVERHEAD	100	/* additional buffer space for large */
96                                /* {recv,send}msg() calls            */
97
98static int bundle_RemainingIdleTime(struct bundle *);
99static int bundle_RemainingAutoLoadTime(struct bundle *);
100
101static const char *PhaseNames[] = {
102  "Dead", "Establish", "Authenticate", "Network", "Terminate"
103};
104
105const char *
106bundle_PhaseName(struct bundle *bundle)
107{
108  return bundle->phase <= PHASE_TERMINATE ?
109    PhaseNames[bundle->phase] : "unknown";
110}
111
112void
113bundle_NewPhase(struct bundle *bundle, u_int new)
114{
115  if (new == bundle->phase)
116    return;
117
118  if (new <= PHASE_TERMINATE)
119    log_Printf(LogPHASE, "bundle: %s\n", PhaseNames[new]);
120
121  switch (new) {
122  case PHASE_DEAD:
123    log_DisplayPrompts();
124    bundle->phase = new;
125    break;
126
127  case PHASE_ESTABLISH:
128    bundle->phase = new;
129    break;
130
131  case PHASE_AUTHENTICATE:
132    bundle->phase = new;
133    log_DisplayPrompts();
134    break;
135
136  case PHASE_NETWORK:
137    ipcp_Setup(&bundle->ncp.ipcp);
138    fsm_Up(&bundle->ncp.ipcp.fsm);
139    fsm_Open(&bundle->ncp.ipcp.fsm);
140    bundle->phase = new;
141    log_DisplayPrompts();
142    break;
143
144  case PHASE_TERMINATE:
145    bundle->phase = new;
146    mp_Down(&bundle->ncp.mp);
147    log_DisplayPrompts();
148    break;
149  }
150}
151
152static void
153bundle_LayerStart(void *v, struct fsm *fp)
154{
155  /* The given FSM is about to start up ! */
156}
157
158
159static void
160bundle_Notify(struct bundle *bundle, char c)
161{
162  if (bundle->notify.fd != -1) {
163    if (write(bundle->notify.fd, &c, 1) == 1)
164      log_Printf(LogPHASE, "Parent notified of success.\n");
165    else
166      log_Printf(LogPHASE, "Failed to notify parent of success.\n");
167    close(bundle->notify.fd);
168    bundle->notify.fd = -1;
169  }
170}
171
172static void
173bundle_ClearQueues(void *v)
174{
175  struct bundle *bundle = (struct bundle *)v;
176  struct datalink *dl;
177
178  log_Printf(LogPHASE, "Clearing choked output queue\n");
179  timer_Stop(&bundle->choked.timer);
180
181  /*
182   * Emergency time:
183   *
184   * We've had a full queue for PACKET_DEL_SECS seconds without being
185   * able to get rid of any of the packets.  We've probably given up
186   * on the redials at this point, and the queued data has almost
187   * definitely been timed out by the layer above.  As this is preventing
188   * us from reading the TUN_NAME device (we don't want to buffer stuff
189   * indefinitely), we may as well nuke this data and start with a clean
190   * slate !
191   *
192   * Unfortunately, this has the side effect of shafting any compression
193   * dictionaries in use (causing the relevant RESET_REQ/RESET_ACK).
194   */
195
196  ip_DeleteQueue(&bundle->ncp.ipcp);
197  mp_DeleteQueue(&bundle->ncp.mp);
198  for (dl = bundle->links; dl; dl = dl->next)
199    physical_DeleteQueue(dl->physical);
200}
201
202static void
203bundle_AutoLoadTimeout(void *v)
204{
205  struct bundle *bundle = (struct bundle *)v;
206
207  if (bundle->autoload.comingup) {
208    log_Printf(LogPHASE, "autoload: Another link is required\n");
209    /* bundle_Open() stops the timer */
210    bundle_Open(bundle, NULL, PHYS_AUTO, 0);
211  } else {
212    struct datalink *dl, *last;
213
214    timer_Stop(&bundle->autoload.timer);
215    for (last = NULL, dl = bundle->links; dl; dl = dl->next)
216      if (dl->physical->type == PHYS_AUTO && dl->state == DATALINK_OPEN)
217        last = dl;
218
219    if (last)
220      datalink_Close(last, CLOSE_STAYDOWN);
221  }
222}
223
224static void
225bundle_StartAutoLoadTimer(struct bundle *bundle, int up)
226{
227  struct datalink *dl;
228
229  timer_Stop(&bundle->autoload.timer);
230
231  if (bundle->CleaningUp || bundle->phase != PHASE_NETWORK) {
232    dl = NULL;
233    bundle->autoload.running = 0;
234  } else if (up) {
235    for (dl = bundle->links; dl; dl = dl->next)
236      if (dl->state == DATALINK_CLOSED && dl->physical->type == PHYS_AUTO) {
237        if (bundle->cfg.autoload.max.timeout) {
238          bundle->autoload.timer.func = bundle_AutoLoadTimeout;
239          bundle->autoload.timer.name = "autoload up";
240          bundle->autoload.timer.load =
241            bundle->cfg.autoload.max.timeout * SECTICKS;
242          bundle->autoload.timer.arg = bundle;
243          timer_Start(&bundle->autoload.timer);
244          bundle->autoload.done = time(NULL) + bundle->cfg.autoload.max.timeout;
245        } else
246          bundle_AutoLoadTimeout(bundle);
247        break;
248      }
249    bundle->autoload.running = (dl || bundle->cfg.autoload.min.timeout) ? 1 : 0;
250  } else {
251    int nlinks;
252    struct datalink *adl;
253
254    for (nlinks = 0, adl = NULL, dl = bundle->links; dl; dl = dl->next)
255      if (dl->state == DATALINK_OPEN) {
256        if (dl->physical->type == PHYS_AUTO)
257          adl = dl;
258        if (++nlinks > 1 && adl) {
259          if (bundle->cfg.autoload.min.timeout) {
260            bundle->autoload.timer.func = bundle_AutoLoadTimeout;
261            bundle->autoload.timer.name = "autoload down";
262            bundle->autoload.timer.load =
263              bundle->cfg.autoload.min.timeout * SECTICKS;
264            bundle->autoload.timer.arg = bundle;
265            timer_Start(&bundle->autoload.timer);
266            bundle->autoload.done =
267              time(NULL) + bundle->cfg.autoload.min.timeout;
268          }
269          break;
270        }
271      }
272
273    bundle->autoload.running = 1;
274  }
275
276  bundle->autoload.comingup = up ? 1 : 0;
277}
278
279static void
280bundle_StopAutoLoadTimer(struct bundle *bundle)
281{
282  timer_Stop(&bundle->autoload.timer);
283  bundle->autoload.done = 0;
284}
285
286static int
287bundle_RemainingAutoLoadTime(struct bundle *bundle)
288{
289  if (bundle->autoload.done)
290    return bundle->autoload.done - time(NULL);
291  return -1;
292}
293
294static void
295bundle_LinkAdded(struct bundle *bundle, struct datalink *dl)
296{
297  bundle->phys_type.all |= dl->physical->type;
298  if (dl->state == DATALINK_OPEN)
299    bundle->phys_type.open |= dl->physical->type;
300
301  /* Note: We only re-add links that are DATALINK_OPEN */
302  if (dl->physical->type == PHYS_AUTO &&
303      bundle->autoload.timer.state == TIMER_STOPPED &&
304      dl->state != DATALINK_OPEN &&
305      bundle->phase == PHASE_NETWORK)
306    bundle->autoload.running = 1;
307
308  if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
309      != bundle->phys_type.open && bundle->idle.timer.state == TIMER_STOPPED)
310    /* We may need to start our idle timer */
311    bundle_StartIdleTimer(bundle);
312}
313
314void
315bundle_LinksRemoved(struct bundle *bundle)
316{
317  struct datalink *dl;
318
319  bundle->phys_type.all = bundle->phys_type.open = 0;
320  for (dl = bundle->links; dl; dl = dl->next)
321    bundle_LinkAdded(bundle, dl);
322
323  if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
324      == bundle->phys_type.open)
325    bundle_StopIdleTimer(bundle);
326}
327
328static void
329bundle_LayerUp(void *v, struct fsm *fp)
330{
331  /*
332   * The given fsm is now up
333   * If it's an LCP, adjust our phys_mode.open value.
334   * If it's an LCP set our mtu (if we're multilink, add up the link
335   * speeds and set the MRRU) and start our autoload timer.
336   * If it's an NCP, tell our -background parent to go away.
337   * If it's the first NCP, start the idle timer.
338   */
339  struct bundle *bundle = (struct bundle *)v;
340
341  if (fp->proto == PROTO_LCP) {
342    struct physical *p = link2physical(fp->link);
343
344    bundle_LinkAdded(bundle, p->dl);
345    if (bundle->ncp.mp.active) {
346      struct datalink *dl;
347
348      bundle->ifSpeed = 0;
349      for (dl = bundle->links; dl; dl = dl->next)
350        if (dl->state == DATALINK_OPEN)
351          bundle->ifSpeed += modem_Speed(dl->physical);
352      tun_configure(bundle, bundle->ncp.mp.peer_mrru);
353      bundle->autoload.running = 1;
354    } else {
355      bundle->ifSpeed = modem_Speed(p);
356      tun_configure(bundle, fsm2lcp(fp)->his_mru);
357    }
358  } else if (fp->proto == PROTO_IPCP) {
359    bundle_StartIdleTimer(bundle);
360    bundle_Notify(bundle, EX_NORMAL);
361  }
362}
363
364static void
365bundle_LayerDown(void *v, struct fsm *fp)
366{
367  /*
368   * The given FSM has been told to come down.
369   * If it's our last NCP, stop the idle timer.
370   * If it's an LCP, adjust our phys_type.open value and any timers.
371   * If it's an LCP and we're in multilink mode, adjust our tun
372   * speed and make sure our minimum sequence number is adjusted.
373   */
374
375  struct bundle *bundle = (struct bundle *)v;
376
377  if (fp->proto == PROTO_IPCP)
378    bundle_StopIdleTimer(bundle);
379  else if (fp->proto == PROTO_LCP) {
380    bundle_LinksRemoved(bundle);  /* adjust timers & phys_type values */
381    if (bundle->ncp.mp.active) {
382      struct datalink *dl;
383      struct datalink *lost;
384
385      bundle->ifSpeed = 0;
386      lost = NULL;
387      for (dl = bundle->links; dl; dl = dl->next)
388        if (fp == &dl->physical->link.lcp.fsm)
389          lost = dl;
390        else if (dl->state == DATALINK_OPEN)
391          bundle->ifSpeed += modem_Speed(dl->physical);
392
393      if (bundle->ifSpeed)
394        /* Don't configure down to a speed of 0 */
395        tun_configure(bundle, bundle->ncp.mp.link.lcp.his_mru);
396
397      if (lost)
398        mp_LinkLost(&bundle->ncp.mp, lost);
399      else
400        log_Printf(LogALERT, "Oops, lost an unrecognised datalink (%s) !\n",
401                   fp->link->name);
402    }
403  }
404}
405
406static void
407bundle_LayerFinish(void *v, struct fsm *fp)
408{
409  /* The given fsm is now down (fp cannot be NULL)
410   *
411   * If it's the last LCP, fsm_Down all NCPs
412   * If it's the last NCP, fsm_Close all LCPs
413   */
414
415  struct bundle *bundle = (struct bundle *)v;
416  struct datalink *dl;
417
418  if (fp->proto == PROTO_IPCP) {
419    if (bundle_Phase(bundle) != PHASE_DEAD)
420      bundle_NewPhase(bundle, PHASE_TERMINATE);
421    for (dl = bundle->links; dl; dl = dl->next)
422      datalink_Close(dl, CLOSE_NORMAL);
423    fsm2initial(fp);
424  } else if (fp->proto == PROTO_LCP) {
425    int others_active;
426
427    others_active = 0;
428    for (dl = bundle->links; dl; dl = dl->next)
429      if (fp != &dl->physical->link.lcp.fsm &&
430          dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
431        others_active++;
432
433    if (!others_active)
434      fsm2initial(&bundle->ncp.ipcp.fsm);
435  }
436}
437
438int
439bundle_LinkIsUp(const struct bundle *bundle)
440{
441  return bundle->ncp.ipcp.fsm.state == ST_OPENED;
442}
443
444void
445bundle_Close(struct bundle *bundle, const char *name, int how)
446{
447  /*
448   * Please close the given datalink.
449   * If name == NULL or name is the last datalink, fsm_Close all NCPs
450   * (except our MP)
451   * If it isn't the last datalink, just Close that datalink.
452   */
453
454  struct datalink *dl, *this_dl;
455  int others_active;
456
457  others_active = 0;
458  this_dl = NULL;
459
460  for (dl = bundle->links; dl; dl = dl->next) {
461    if (name && !strcasecmp(name, dl->name))
462      this_dl = dl;
463    if (name == NULL || this_dl == dl) {
464      switch (how) {
465        case CLOSE_LCP:
466          datalink_DontHangup(dl);
467          /* fall through */
468        case CLOSE_STAYDOWN:
469          datalink_StayDown(dl);
470          break;
471      }
472    } else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
473      others_active++;
474  }
475
476  if (name && this_dl == NULL) {
477    log_Printf(LogWARN, "%s: Invalid datalink name\n", name);
478    return;
479  }
480
481  if (!others_active) {
482    bundle_StopIdleTimer(bundle);
483    bundle_StopAutoLoadTimer(bundle);
484    if (bundle->ncp.ipcp.fsm.state > ST_CLOSED ||
485        bundle->ncp.ipcp.fsm.state == ST_STARTING)
486      fsm_Close(&bundle->ncp.ipcp.fsm);
487    else {
488      fsm2initial(&bundle->ncp.ipcp.fsm);
489      for (dl = bundle->links; dl; dl = dl->next)
490        datalink_Close(dl, how);
491    }
492  } else if (this_dl && this_dl->state != DATALINK_CLOSED &&
493             this_dl->state != DATALINK_HANGUP)
494    datalink_Close(this_dl, how);
495}
496
497void
498bundle_Down(struct bundle *bundle, int how)
499{
500  struct datalink *dl;
501
502  for (dl = bundle->links; dl; dl = dl->next)
503    datalink_Down(dl, how);
504}
505
506static int
507bundle_UpdateSet(struct descriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
508{
509  struct bundle *bundle = descriptor2bundle(d);
510  struct datalink *dl;
511  int result, want, queued, nlinks;
512
513  result = 0;
514
515  /* If there are aren't many packets queued, look for some more. */
516  for (nlinks = 0, dl = bundle->links; dl; dl = dl->next)
517    nlinks++;
518
519  if (nlinks) {
520    queued = r ? bundle_FillQueues(bundle) : ip_QueueLen(&bundle->ncp.ipcp);
521    if (bundle->autoload.running) {
522      if (queued < bundle->cfg.autoload.max.packets) {
523        if (queued > bundle->cfg.autoload.min.packets)
524          bundle_StopAutoLoadTimer(bundle);
525        else if (bundle->autoload.timer.state != TIMER_RUNNING ||
526                 bundle->autoload.comingup)
527          bundle_StartAutoLoadTimer(bundle, 0);
528      } else if (bundle->autoload.timer.state != TIMER_RUNNING ||
529                 !bundle->autoload.comingup)
530        bundle_StartAutoLoadTimer(bundle, 1);
531    }
532
533    if (r && (bundle->phase == PHASE_NETWORK ||
534              bundle->phys_type.all & PHYS_AUTO)) {
535      /* enough surplus so that we can tell if we're getting swamped */
536      want = bundle->cfg.autoload.max.packets + nlinks * 2;
537      /* but at least 20 packets ! */
538      if (want < 20)
539        want = 20;
540      if (queued < want) {
541        /* Not enough - select() for more */
542        if (bundle->choked.timer.state == TIMER_RUNNING)
543          timer_Stop(&bundle->choked.timer);	/* Not needed any more */
544        FD_SET(bundle->dev.fd, r);
545        if (*n < bundle->dev.fd + 1)
546          *n = bundle->dev.fd + 1;
547        log_Printf(LogTIMER, "%s: fdset(r) %d\n", TUN_NAME, bundle->dev.fd);
548        result++;
549      } else if (bundle->choked.timer.state == TIMER_STOPPED) {
550        bundle->choked.timer.func = bundle_ClearQueues;
551        bundle->choked.timer.name = "output choke";
552        bundle->choked.timer.load = bundle->cfg.choked.timeout * SECTICKS;
553        bundle->choked.timer.arg = bundle;
554        timer_Start(&bundle->choked.timer);
555      }
556    }
557  }
558
559  /* Which links need a select() ? */
560  for (dl = bundle->links; dl; dl = dl->next)
561    result += descriptor_UpdateSet(&dl->desc, r, w, e, n);
562
563  /*
564   * This *MUST* be called after the datalink UpdateSet()s as it
565   * might be ``holding'' one of the datalinks (death-row) and
566   * wants to be able to de-select() it from the descriptor set.
567   */
568  result += descriptor_UpdateSet(&bundle->ncp.mp.server.desc, r, w, e, n);
569
570  return result;
571}
572
573static int
574bundle_IsSet(struct descriptor *d, const fd_set *fdset)
575{
576  struct bundle *bundle = descriptor2bundle(d);
577  struct datalink *dl;
578
579  for (dl = bundle->links; dl; dl = dl->next)
580    if (descriptor_IsSet(&dl->desc, fdset))
581      return 1;
582
583  if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
584    return 1;
585
586  return FD_ISSET(bundle->dev.fd, fdset);
587}
588
589static void
590bundle_DescriptorRead(struct descriptor *d, struct bundle *bundle,
591                      const fd_set *fdset)
592{
593  struct datalink *dl;
594
595  if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
596    descriptor_Read(&bundle->ncp.mp.server.desc, bundle, fdset);
597
598  for (dl = bundle->links; dl; dl = dl->next)
599    if (descriptor_IsSet(&dl->desc, fdset))
600      descriptor_Read(&dl->desc, bundle, fdset);
601
602  if (FD_ISSET(bundle->dev.fd, fdset)) {
603    struct tun_data tun;
604    int n, pri;
605
606    /* something to read from tun */
607    n = read(bundle->dev.fd, &tun, sizeof tun);
608    if (n < 0) {
609      log_Printf(LogWARN, "read from %s: %s\n", TUN_NAME, strerror(errno));
610      return;
611    }
612    n -= sizeof tun - sizeof tun.data;
613    if (n <= 0) {
614      log_Printf(LogERROR, "read from %s: Only %d bytes read ?\n", TUN_NAME, n);
615      return;
616    }
617    if (!tun_check_header(tun, AF_INET))
618      return;
619
620    if (((struct ip *)tun.data)->ip_dst.s_addr ==
621        bundle->ncp.ipcp.my_ip.s_addr) {
622      /* we've been asked to send something addressed *to* us :( */
623      if (Enabled(bundle, OPT_LOOPBACK)) {
624        pri = PacketCheck(bundle, tun.data, n, &bundle->filter.in);
625        if (pri >= 0) {
626          struct mbuf *bp;
627
628          bp = mbuf_Alloc(n, MB_IPIN);
629          memcpy(MBUF_CTOP(bp), tun.data, n);
630          ip_Input(bundle, bp);
631          log_Printf(LogDEBUG, "Looped back packet addressed to myself\n");
632        }
633        return;
634      } else
635        log_Printf(LogDEBUG, "Oops - forwarding packet addressed to myself\n");
636    }
637
638    /*
639     * Process on-demand dialup. Output packets are queued within tunnel
640     * device until IPCP is opened.
641     */
642
643    if (bundle_Phase(bundle) == PHASE_DEAD) {
644      /*
645       * Note, we must be in AUTO mode :-/ otherwise our interface should
646       * *not* be UP and we can't receive data
647       */
648      if ((pri = PacketCheck(bundle, tun.data, n, &bundle->filter.dial)) >= 0)
649        bundle_Open(bundle, NULL, PHYS_AUTO, 0);
650      else
651        /*
652         * Drop the packet.  If we were to queue it, we'd just end up with
653         * a pile of timed-out data in our output queue by the time we get
654         * around to actually dialing.  We'd also prematurely reach the
655         * threshold at which we stop select()ing to read() the tun
656         * device - breaking auto-dial.
657         */
658        return;
659    }
660
661    pri = PacketCheck(bundle, tun.data, n, &bundle->filter.out);
662    if (pri >= 0) {
663#ifndef NOALIAS
664      if (bundle->AliasEnabled) {
665        PacketAliasOut(tun.data, sizeof tun.data);
666        n = ntohs(((struct ip *)tun.data)->ip_len);
667      }
668#endif
669      ip_Enqueue(&bundle->ncp.ipcp, pri, tun.data, n);
670    }
671  }
672}
673
674static int
675bundle_DescriptorWrite(struct descriptor *d, struct bundle *bundle,
676                       const fd_set *fdset)
677{
678  struct datalink *dl;
679  int result = 0;
680
681  /* This is not actually necessary as struct mpserver doesn't Write() */
682  if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
683    descriptor_Write(&bundle->ncp.mp.server.desc, bundle, fdset);
684
685  for (dl = bundle->links; dl; dl = dl->next)
686    if (descriptor_IsSet(&dl->desc, fdset))
687      result += descriptor_Write(&dl->desc, bundle, fdset);
688
689  return result;
690}
691
692void
693bundle_LockTun(struct bundle *bundle)
694{
695  FILE *lockfile;
696  char pidfile[MAXPATHLEN];
697
698  snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
699  lockfile = ID0fopen(pidfile, "w");
700  if (lockfile != NULL) {
701    fprintf(lockfile, "%d\n", (int)getpid());
702    fclose(lockfile);
703  }
704#ifndef RELEASE_CRUNCH
705  else
706    log_Printf(LogERROR, "Warning: Can't create %s: %s\n",
707               pidfile, strerror(errno));
708#endif
709}
710
711static void
712bundle_UnlockTun(struct bundle *bundle)
713{
714  char pidfile[MAXPATHLEN];
715
716  snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
717  ID0unlink(pidfile);
718}
719
720struct bundle *
721bundle_Create(const char *prefix, int type, const char **argv)
722{
723  int s, enoentcount, err;
724  const char *ifname;
725  struct ifreq ifrq;
726  static struct bundle bundle;		/* there can be only one */
727
728  if (bundle.iface != NULL) {	/* Already allocated ! */
729    log_Printf(LogALERT, "bundle_Create:  There's only one BUNDLE !\n");
730    return NULL;
731  }
732
733  err = ENOENT;
734  enoentcount = 0;
735  for (bundle.unit = 0; ; bundle.unit++) {
736    snprintf(bundle.dev.Name, sizeof bundle.dev.Name, "%s%d",
737             prefix, bundle.unit);
738    bundle.dev.fd = ID0open(bundle.dev.Name, O_RDWR);
739    if (bundle.dev.fd >= 0)
740      break;
741    else if (errno == ENXIO) {
742      err = errno;
743      break;
744    } else if (errno == ENOENT) {
745      if (++enoentcount > 2)
746	break;
747    } else
748      err = errno;
749  }
750
751  if (bundle.dev.fd < 0) {
752    log_Printf(LogWARN, "No available tunnel devices found (%s).\n",
753              strerror(err));
754    return NULL;
755  }
756
757  log_SetTun(bundle.unit);
758  bundle.argv = argv;
759  bundle.argv0 = argv[0];
760  bundle.argv1 = argv[1];
761
762  s = socket(AF_INET, SOCK_DGRAM, 0);
763  if (s < 0) {
764    log_Printf(LogERROR, "bundle_Create: socket(): %s\n", strerror(errno));
765    close(bundle.dev.fd);
766    return NULL;
767  }
768
769  ifname = strrchr(bundle.dev.Name, '/');
770  if (ifname == NULL)
771    ifname = bundle.dev.Name;
772  else
773    ifname++;
774
775  bundle.iface = iface_Create(ifname);
776  if (bundle.iface == NULL) {
777    close(s);
778    close(bundle.dev.fd);
779    return NULL;
780  }
781
782  /*
783   * Now, bring up the interface.
784   */
785  memset(&ifrq, '\0', sizeof ifrq);
786  strncpy(ifrq.ifr_name, ifname, sizeof ifrq.ifr_name - 1);
787  ifrq.ifr_name[sizeof ifrq.ifr_name - 1] = '\0';
788  if (ID0ioctl(s, SIOCGIFFLAGS, &ifrq) < 0) {
789    log_Printf(LogERROR, "bundle_Create: ioctl(SIOCGIFFLAGS): %s\n",
790	      strerror(errno));
791    close(s);
792    iface_Destroy(bundle.iface);
793    bundle.iface = NULL;
794    close(bundle.dev.fd);
795    return NULL;
796  }
797  ifrq.ifr_flags |= IFF_UP;
798  if (ID0ioctl(s, SIOCSIFFLAGS, &ifrq) < 0) {
799    log_Printf(LogERROR, "bundle_Create: ioctl(SIOCSIFFLAGS): %s\n",
800	      strerror(errno));
801    close(s);
802    iface_Destroy(bundle.iface);
803    bundle.iface = NULL;
804    close(bundle.dev.fd);
805    return NULL;
806  }
807
808  close(s);
809
810  log_Printf(LogPHASE, "Using interface: %s\n", ifname);
811
812  bundle.ifSpeed = 0;
813
814  bundle.routing_seq = 0;
815  bundle.phase = PHASE_DEAD;
816  bundle.CleaningUp = 0;
817  bundle.AliasEnabled = 0;
818
819  bundle.fsm.LayerStart = bundle_LayerStart;
820  bundle.fsm.LayerUp = bundle_LayerUp;
821  bundle.fsm.LayerDown = bundle_LayerDown;
822  bundle.fsm.LayerFinish = bundle_LayerFinish;
823  bundle.fsm.object = &bundle;
824
825  bundle.cfg.idle_timeout = NCP_IDLE_TIMEOUT;
826  *bundle.cfg.auth.name = '\0';
827  *bundle.cfg.auth.key = '\0';
828  bundle.cfg.opt = OPT_SROUTES | OPT_IDCHECK | OPT_LOOPBACK |
829                   OPT_THROUGHPUT | OPT_UTMP;
830  *bundle.cfg.label = '\0';
831  bundle.cfg.mtu = DEF_MTU;
832  bundle.cfg.autoload.max.packets = 0;
833  bundle.cfg.autoload.max.timeout = 0;
834  bundle.cfg.autoload.min.packets = 0;
835  bundle.cfg.autoload.min.timeout = 0;
836  bundle.cfg.choked.timeout = CHOKED_TIMEOUT;
837  bundle.phys_type.all = type;
838  bundle.phys_type.open = 0;
839
840  bundle.links = datalink_Create("deflink", &bundle, type);
841  if (bundle.links == NULL) {
842    log_Printf(LogALERT, "Cannot create data link: %s\n", strerror(errno));
843    iface_Destroy(bundle.iface);
844    bundle.iface = NULL;
845    close(bundle.dev.fd);
846    return NULL;
847  }
848
849  bundle.desc.type = BUNDLE_DESCRIPTOR;
850  bundle.desc.UpdateSet = bundle_UpdateSet;
851  bundle.desc.IsSet = bundle_IsSet;
852  bundle.desc.Read = bundle_DescriptorRead;
853  bundle.desc.Write = bundle_DescriptorWrite;
854
855  mp_Init(&bundle.ncp.mp, &bundle);
856
857  /* Send over the first physical link by default */
858  ipcp_Init(&bundle.ncp.ipcp, &bundle, &bundle.links->physical->link,
859            &bundle.fsm);
860
861  memset(&bundle.filter, '\0', sizeof bundle.filter);
862  bundle.filter.in.fragok = bundle.filter.in.logok = 1;
863  bundle.filter.in.name = "IN";
864  bundle.filter.out.fragok = bundle.filter.out.logok = 1;
865  bundle.filter.out.name = "OUT";
866  bundle.filter.dial.name = "DIAL";
867  bundle.filter.dial.logok = 1;
868  bundle.filter.alive.name = "ALIVE";
869  bundle.filter.alive.logok = 1;
870  memset(&bundle.idle.timer, '\0', sizeof bundle.idle.timer);
871  bundle.idle.done = 0;
872  bundle.notify.fd = -1;
873  memset(&bundle.autoload.timer, '\0', sizeof bundle.autoload.timer);
874  bundle.autoload.done = 0;
875  bundle.autoload.running = 0;
876  memset(&bundle.choked.timer, '\0', sizeof bundle.choked.timer);
877
878  /* Clean out any leftover crud */
879  iface_Clear(bundle.iface, IFACE_CLEAR_ALL);
880
881  bundle_LockTun(&bundle);
882
883  return &bundle;
884}
885
886static void
887bundle_DownInterface(struct bundle *bundle)
888{
889  struct ifreq ifrq;
890  int s;
891
892  route_IfDelete(bundle, 1);
893
894  s = ID0socket(AF_INET, SOCK_DGRAM, 0);
895  if (s < 0) {
896    log_Printf(LogERROR, "bundle_DownInterface: socket: %s\n", strerror(errno));
897    return;
898  }
899
900  memset(&ifrq, '\0', sizeof ifrq);
901  strncpy(ifrq.ifr_name, bundle->iface->name, sizeof ifrq.ifr_name - 1);
902  ifrq.ifr_name[sizeof ifrq.ifr_name - 1] = '\0';
903  if (ID0ioctl(s, SIOCGIFFLAGS, &ifrq) < 0) {
904    log_Printf(LogERROR, "bundle_DownInterface: ioctl(SIOCGIFFLAGS): %s\n",
905       strerror(errno));
906    close(s);
907    return;
908  }
909  ifrq.ifr_flags &= ~IFF_UP;
910  if (ID0ioctl(s, SIOCSIFFLAGS, &ifrq) < 0) {
911    log_Printf(LogERROR, "bundle_DownInterface: ioctl(SIOCSIFFLAGS): %s\n",
912       strerror(errno));
913    close(s);
914    return;
915  }
916  close(s);
917}
918
919void
920bundle_Destroy(struct bundle *bundle)
921{
922  struct datalink *dl;
923
924  /*
925   * Clean up the interface.  We don't need to timer_Stop()s, mp_Down(),
926   * ipcp_CleanInterface() and bundle_DownInterface() unless we're getting
927   * out under exceptional conditions such as a descriptor exception.
928   */
929  timer_Stop(&bundle->idle.timer);
930  timer_Stop(&bundle->choked.timer);
931  timer_Stop(&bundle->autoload.timer);
932  mp_Down(&bundle->ncp.mp);
933  ipcp_CleanInterface(&bundle->ncp.ipcp);
934  bundle_DownInterface(bundle);
935
936  /* Again, these are all DATALINK_CLOSED unless we're abending */
937  dl = bundle->links;
938  while (dl)
939    dl = datalink_Destroy(dl);
940
941  close(bundle->dev.fd);
942  bundle_UnlockTun(bundle);
943
944  /* In case we never made PHASE_NETWORK */
945  bundle_Notify(bundle, EX_ERRDEAD);
946
947  iface_Destroy(bundle->iface);
948  bundle->iface = NULL;
949}
950
951struct rtmsg {
952  struct rt_msghdr m_rtm;
953  char m_space[64];
954};
955
956int
957bundle_SetRoute(struct bundle *bundle, int cmd, struct in_addr dst,
958                struct in_addr gateway, struct in_addr mask, int bang, int ssh)
959{
960  struct rtmsg rtmes;
961  int s, nb, wb;
962  char *cp;
963  const char *cmdstr;
964  struct sockaddr_in rtdata;
965  int result = 1;
966
967  if (bang)
968    cmdstr = (cmd == RTM_ADD ? "Add!" : "Delete!");
969  else
970    cmdstr = (cmd == RTM_ADD ? "Add" : "Delete");
971  s = ID0socket(PF_ROUTE, SOCK_RAW, 0);
972  if (s < 0) {
973    log_Printf(LogERROR, "bundle_SetRoute: socket(): %s\n", strerror(errno));
974    return result;
975  }
976  memset(&rtmes, '\0', sizeof rtmes);
977  rtmes.m_rtm.rtm_version = RTM_VERSION;
978  rtmes.m_rtm.rtm_type = cmd;
979  rtmes.m_rtm.rtm_addrs = RTA_DST;
980  rtmes.m_rtm.rtm_seq = ++bundle->routing_seq;
981  rtmes.m_rtm.rtm_pid = getpid();
982  rtmes.m_rtm.rtm_flags = RTF_UP | RTF_GATEWAY | RTF_STATIC;
983
984  if (cmd == RTM_ADD || cmd == RTM_CHANGE) {
985    if (bundle->ncp.ipcp.cfg.sendpipe > 0) {
986      rtmes.m_rtm.rtm_rmx.rmx_sendpipe = bundle->ncp.ipcp.cfg.sendpipe;
987      rtmes.m_rtm.rtm_inits |= RTV_SPIPE;
988    }
989    if (bundle->ncp.ipcp.cfg.recvpipe > 0) {
990      rtmes.m_rtm.rtm_rmx.rmx_recvpipe = bundle->ncp.ipcp.cfg.recvpipe;
991      rtmes.m_rtm.rtm_inits |= RTV_RPIPE;
992    }
993  }
994
995  memset(&rtdata, '\0', sizeof rtdata);
996  rtdata.sin_len = sizeof rtdata;
997  rtdata.sin_family = AF_INET;
998  rtdata.sin_port = 0;
999  rtdata.sin_addr = dst;
1000
1001  cp = rtmes.m_space;
1002  memcpy(cp, &rtdata, rtdata.sin_len);
1003  cp += rtdata.sin_len;
1004  if (cmd == RTM_ADD) {
1005    if (gateway.s_addr == INADDR_ANY) {
1006      if (!ssh)
1007        log_Printf(LogERROR, "bundle_SetRoute: Cannot add a route with"
1008                   " destination 0.0.0.0\n");
1009      close(s);
1010      return result;
1011    } else {
1012      rtdata.sin_addr = gateway;
1013      memcpy(cp, &rtdata, rtdata.sin_len);
1014      cp += rtdata.sin_len;
1015      rtmes.m_rtm.rtm_addrs |= RTA_GATEWAY;
1016    }
1017  }
1018
1019  if (dst.s_addr == INADDR_ANY)
1020    mask.s_addr = INADDR_ANY;
1021
1022  if (cmd == RTM_ADD || dst.s_addr == INADDR_ANY) {
1023    rtdata.sin_addr = mask;
1024    memcpy(cp, &rtdata, rtdata.sin_len);
1025    cp += rtdata.sin_len;
1026    rtmes.m_rtm.rtm_addrs |= RTA_NETMASK;
1027  }
1028
1029  nb = cp - (char *) &rtmes;
1030  rtmes.m_rtm.rtm_msglen = nb;
1031  wb = ID0write(s, &rtmes, nb);
1032  if (wb < 0) {
1033    log_Printf(LogTCPIP, "bundle_SetRoute failure:\n");
1034    log_Printf(LogTCPIP, "bundle_SetRoute:  Cmd = %s\n", cmdstr);
1035    log_Printf(LogTCPIP, "bundle_SetRoute:  Dst = %s\n", inet_ntoa(dst));
1036    log_Printf(LogTCPIP, "bundle_SetRoute:  Gateway = %s\n", inet_ntoa(gateway));
1037    log_Printf(LogTCPIP, "bundle_SetRoute:  Mask = %s\n", inet_ntoa(mask));
1038failed:
1039    if (cmd == RTM_ADD && (rtmes.m_rtm.rtm_errno == EEXIST ||
1040                           (rtmes.m_rtm.rtm_errno == 0 && errno == EEXIST))) {
1041      if (!bang) {
1042        log_Printf(LogWARN, "Add route failed: %s already exists\n",
1043		  dst.s_addr == 0 ? "default" : inet_ntoa(dst));
1044        result = 0;	/* Don't add to our dynamic list */
1045      } else {
1046        rtmes.m_rtm.rtm_type = cmd = RTM_CHANGE;
1047        if ((wb = ID0write(s, &rtmes, nb)) < 0)
1048          goto failed;
1049      }
1050    } else if (cmd == RTM_DELETE &&
1051             (rtmes.m_rtm.rtm_errno == ESRCH ||
1052              (rtmes.m_rtm.rtm_errno == 0 && errno == ESRCH))) {
1053      if (!bang)
1054        log_Printf(LogWARN, "Del route failed: %s: Non-existent\n",
1055                  inet_ntoa(dst));
1056    } else if (rtmes.m_rtm.rtm_errno == 0) {
1057      if (!ssh || errno != ENETUNREACH)
1058        log_Printf(LogWARN, "%s route failed: %s: errno: %s\n", cmdstr,
1059                   inet_ntoa(dst), strerror(errno));
1060    } else
1061      log_Printf(LogWARN, "%s route failed: %s: %s\n",
1062		 cmdstr, inet_ntoa(dst), strerror(rtmes.m_rtm.rtm_errno));
1063  }
1064  log_Printf(LogDEBUG, "wrote %d: cmd = %s, dst = %x, gateway = %x\n",
1065            wb, cmdstr, (unsigned)dst.s_addr, (unsigned)gateway.s_addr);
1066  close(s);
1067
1068  return result;
1069}
1070
1071void
1072bundle_LinkClosed(struct bundle *bundle, struct datalink *dl)
1073{
1074  /*
1075   * Our datalink has closed.
1076   * CleanDatalinks() (called from DoLoop()) will remove closed
1077   * BACKGROUND and DIRECT links.
1078   * If it's the last data link, enter phase DEAD.
1079   *
1080   * NOTE: dl may not be in our list (bundle_SendDatalink()) !
1081   */
1082
1083  struct datalink *odl;
1084  int other_links;
1085
1086  log_SetTtyCommandMode(dl);
1087
1088  other_links = 0;
1089  for (odl = bundle->links; odl; odl = odl->next)
1090    if (odl != dl && odl->state != DATALINK_CLOSED)
1091      other_links++;
1092
1093  if (!other_links) {
1094    if (dl->physical->type != PHYS_AUTO)	/* Not in -auto mode */
1095      bundle_DownInterface(bundle);
1096    fsm2initial(&bundle->ncp.ipcp.fsm);
1097    bundle_NewPhase(bundle, PHASE_DEAD);
1098    bundle_StopIdleTimer(bundle);
1099    bundle_StopAutoLoadTimer(bundle);
1100    bundle->autoload.running = 0;
1101  } else
1102    bundle->autoload.running = 1;
1103}
1104
1105void
1106bundle_Open(struct bundle *bundle, const char *name, int mask, int force)
1107{
1108  /*
1109   * Please open the given datalink, or all if name == NULL
1110   */
1111  struct datalink *dl;
1112
1113  timer_Stop(&bundle->autoload.timer);
1114  for (dl = bundle->links; dl; dl = dl->next)
1115    if (name == NULL || !strcasecmp(dl->name, name)) {
1116      if ((mask & dl->physical->type) &&
1117          (dl->state == DATALINK_CLOSED ||
1118           (force && dl->state == DATALINK_OPENING &&
1119            dl->dial_timer.state == TIMER_RUNNING))) {
1120        if (force)
1121          timer_Stop(&dl->dial_timer);
1122        datalink_Up(dl, 1, 1);
1123        if (mask == PHYS_AUTO)
1124          /* Only one AUTO link at a time (see the AutoLoad timer) */
1125          break;
1126      }
1127      if (name != NULL)
1128        break;
1129    }
1130}
1131
1132struct datalink *
1133bundle2datalink(struct bundle *bundle, const char *name)
1134{
1135  struct datalink *dl;
1136
1137  if (name != NULL) {
1138    for (dl = bundle->links; dl; dl = dl->next)
1139      if (!strcasecmp(dl->name, name))
1140        return dl;
1141  } else if (bundle->links && !bundle->links->next)
1142    return bundle->links;
1143
1144  return NULL;
1145}
1146
1147int
1148bundle_FillQueues(struct bundle *bundle)
1149{
1150  int total;
1151
1152  if (bundle->ncp.mp.active)
1153    total = mp_FillQueues(bundle);
1154  else {
1155    struct datalink *dl;
1156    int add;
1157
1158    for (total = 0, dl = bundle->links; dl; dl = dl->next)
1159      if (dl->state == DATALINK_OPEN) {
1160        add = link_QueueLen(&dl->physical->link);
1161        if (add == 0 && dl->physical->out == NULL)
1162          add = ip_FlushPacket(&dl->physical->link, bundle);
1163        total += add;
1164      }
1165  }
1166
1167  return total + ip_QueueLen(&bundle->ncp.ipcp);
1168}
1169
1170int
1171bundle_ShowLinks(struct cmdargs const *arg)
1172{
1173  struct datalink *dl;
1174
1175  for (dl = arg->bundle->links; dl; dl = dl->next) {
1176    prompt_Printf(arg->prompt, "Name: %s [%s, %s]",
1177                  dl->name, mode2Nam(dl->physical->type), datalink_State(dl));
1178    if (dl->physical->link.throughput.rolling && dl->state == DATALINK_OPEN)
1179      prompt_Printf(arg->prompt, " weight %d, %d bytes/sec",
1180                    dl->mp.weight,
1181                    dl->physical->link.throughput.OctetsPerSecond);
1182    prompt_Printf(arg->prompt, "\n");
1183  }
1184
1185  return 0;
1186}
1187
1188static const char *
1189optval(struct bundle *bundle, int bit)
1190{
1191  return (bundle->cfg.opt & bit) ? "enabled" : "disabled";
1192}
1193
1194int
1195bundle_ShowStatus(struct cmdargs const *arg)
1196{
1197  int remaining;
1198
1199  prompt_Printf(arg->prompt, "Phase %s\n", bundle_PhaseName(arg->bundle));
1200  prompt_Printf(arg->prompt, " Title:         %s\n", arg->bundle->argv[0]);
1201  prompt_Printf(arg->prompt, " Device:        %s\n", arg->bundle->dev.Name);
1202  prompt_Printf(arg->prompt, " Interface:     %s @ %lubps\n",
1203                arg->bundle->iface->name, arg->bundle->ifSpeed);
1204
1205  prompt_Printf(arg->prompt, "\nDefaults:\n");
1206  prompt_Printf(arg->prompt, " Label:         %s\n", arg->bundle->cfg.label);
1207  prompt_Printf(arg->prompt, " Auth name:     %s\n",
1208                arg->bundle->cfg.auth.name);
1209  prompt_Printf(arg->prompt, " Auto Load:     Up after %ds of >= %d packets\n",
1210                arg->bundle->cfg.autoload.max.timeout,
1211                arg->bundle->cfg.autoload.max.packets);
1212  prompt_Printf(arg->prompt, "                Down after %ds of <= %d"
1213                " packets\n", arg->bundle->cfg.autoload.min.timeout,
1214                arg->bundle->cfg.autoload.min.packets);
1215  if (arg->bundle->autoload.timer.state == TIMER_RUNNING)
1216    prompt_Printf(arg->prompt, "                %ds remaining 'till "
1217                  "a link comes %s\n",
1218                  bundle_RemainingAutoLoadTime(arg->bundle),
1219                  arg->bundle->autoload.comingup ? "up" : "down");
1220  else
1221    prompt_Printf(arg->prompt, "                %srunning with %d"
1222                  " packets queued\n", arg->bundle->autoload.running ?
1223                  "" : "not ", ip_QueueLen(&arg->bundle->ncp.ipcp));
1224
1225  prompt_Printf(arg->prompt, " Choked Timer:  %ds\n",
1226                arg->bundle->cfg.choked.timeout);
1227  prompt_Printf(arg->prompt, " Idle Timer:    ");
1228  if (arg->bundle->cfg.idle_timeout) {
1229    prompt_Printf(arg->prompt, "%ds", arg->bundle->cfg.idle_timeout);
1230    remaining = bundle_RemainingIdleTime(arg->bundle);
1231    if (remaining != -1)
1232      prompt_Printf(arg->prompt, " (%ds remaining)", remaining);
1233    prompt_Printf(arg->prompt, "\n");
1234  } else
1235    prompt_Printf(arg->prompt, "disabled\n");
1236  prompt_Printf(arg->prompt, " MTU:           ");
1237  if (arg->bundle->cfg.mtu)
1238    prompt_Printf(arg->prompt, "%d\n", arg->bundle->cfg.mtu);
1239  else
1240    prompt_Printf(arg->prompt, "unspecified\n");
1241
1242  prompt_Printf(arg->prompt, " sendpipe:      ");
1243  if (arg->bundle->ncp.ipcp.cfg.sendpipe > 0)
1244    prompt_Printf(arg->prompt, "%ld\n", arg->bundle->ncp.ipcp.cfg.sendpipe);
1245  else
1246    prompt_Printf(arg->prompt, "unspecified\n");
1247  prompt_Printf(arg->prompt, " recvpipe:      ");
1248  if (arg->bundle->ncp.ipcp.cfg.recvpipe > 0)
1249    prompt_Printf(arg->prompt, "%ld\n", arg->bundle->ncp.ipcp.cfg.recvpipe);
1250  else
1251    prompt_Printf(arg->prompt, "unspecified\n");
1252
1253  prompt_Printf(arg->prompt, " Sticky Routes: %s\n",
1254                optval(arg->bundle, OPT_SROUTES));
1255  prompt_Printf(arg->prompt, " ID check:      %s\n",
1256                optval(arg->bundle, OPT_IDCHECK));
1257  prompt_Printf(arg->prompt, " Loopback:      %s\n",
1258                optval(arg->bundle, OPT_LOOPBACK));
1259  prompt_Printf(arg->prompt, " PasswdAuth:    %s\n",
1260                optval(arg->bundle, OPT_PASSWDAUTH));
1261  prompt_Printf(arg->prompt, " Proxy:         %s\n",
1262                optval(arg->bundle, OPT_PROXY));
1263  prompt_Printf(arg->prompt, " Proxyall:      %s\n",
1264                optval(arg->bundle, OPT_PROXYALL));
1265  prompt_Printf(arg->prompt, " Throughput:    %s\n",
1266                optval(arg->bundle, OPT_THROUGHPUT));
1267  prompt_Printf(arg->prompt, " Utmp Logging:  %s\n",
1268                optval(arg->bundle, OPT_UTMP));
1269  prompt_Printf(arg->prompt, " Iface-Alias:   %s\n",
1270                optval(arg->bundle, OPT_IFACEALIAS));
1271
1272  return 0;
1273}
1274
1275static void
1276bundle_IdleTimeout(void *v)
1277{
1278  struct bundle *bundle = (struct bundle *)v;
1279
1280  log_Printf(LogPHASE, "Idle timer expired.\n");
1281  bundle_StopIdleTimer(bundle);
1282  bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
1283}
1284
1285/*
1286 *  Start Idle timer. If timeout is reached, we call bundle_Close() to
1287 *  close LCP and link.
1288 */
1289void
1290bundle_StartIdleTimer(struct bundle *bundle)
1291{
1292  timer_Stop(&bundle->idle.timer);
1293  if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) !=
1294      bundle->phys_type.open && bundle->cfg.idle_timeout) {
1295    bundle->idle.timer.func = bundle_IdleTimeout;
1296    bundle->idle.timer.name = "idle";
1297    bundle->idle.timer.load = bundle->cfg.idle_timeout * SECTICKS;
1298    bundle->idle.timer.arg = bundle;
1299    timer_Start(&bundle->idle.timer);
1300    bundle->idle.done = time(NULL) + bundle->cfg.idle_timeout;
1301  }
1302}
1303
1304void
1305bundle_SetIdleTimer(struct bundle *bundle, int value)
1306{
1307  bundle->cfg.idle_timeout = value;
1308  if (bundle_LinkIsUp(bundle))
1309    bundle_StartIdleTimer(bundle);
1310}
1311
1312void
1313bundle_StopIdleTimer(struct bundle *bundle)
1314{
1315  timer_Stop(&bundle->idle.timer);
1316  bundle->idle.done = 0;
1317}
1318
1319static int
1320bundle_RemainingIdleTime(struct bundle *bundle)
1321{
1322  if (bundle->idle.done)
1323    return bundle->idle.done - time(NULL);
1324  return -1;
1325}
1326
1327int
1328bundle_IsDead(struct bundle *bundle)
1329{
1330  return !bundle->links || (bundle->phase == PHASE_DEAD && bundle->CleaningUp);
1331}
1332
1333static struct datalink *
1334bundle_DatalinkLinkout(struct bundle *bundle, struct datalink *dl)
1335{
1336  struct datalink **dlp;
1337
1338  for (dlp = &bundle->links; *dlp; dlp = &(*dlp)->next)
1339    if (*dlp == dl) {
1340      *dlp = dl->next;
1341      dl->next = NULL;
1342      bundle_LinksRemoved(bundle);
1343      return dl;
1344    }
1345
1346  return NULL;
1347}
1348
1349static void
1350bundle_DatalinkLinkin(struct bundle *bundle, struct datalink *dl)
1351{
1352  struct datalink **dlp = &bundle->links;
1353
1354  while (*dlp)
1355    dlp = &(*dlp)->next;
1356
1357  *dlp = dl;
1358  dl->next = NULL;
1359
1360  bundle_LinkAdded(bundle, dl);
1361}
1362
1363void
1364bundle_CleanDatalinks(struct bundle *bundle)
1365{
1366  struct datalink **dlp = &bundle->links;
1367  int found = 0;
1368
1369  while (*dlp)
1370    if ((*dlp)->state == DATALINK_CLOSED &&
1371        (*dlp)->physical->type & (PHYS_DIRECT|PHYS_BACKGROUND)) {
1372      *dlp = datalink_Destroy(*dlp);
1373      found++;
1374    } else
1375      dlp = &(*dlp)->next;
1376
1377  if (found)
1378    bundle_LinksRemoved(bundle);
1379}
1380
1381int
1382bundle_DatalinkClone(struct bundle *bundle, struct datalink *dl,
1383                     const char *name)
1384{
1385  if (bundle2datalink(bundle, name)) {
1386    log_Printf(LogWARN, "Clone: %s: name already exists\n", name);
1387    return 0;
1388  }
1389
1390  bundle_DatalinkLinkin(bundle, datalink_Clone(dl, name));
1391  return 1;
1392}
1393
1394void
1395bundle_DatalinkRemove(struct bundle *bundle, struct datalink *dl)
1396{
1397  dl = bundle_DatalinkLinkout(bundle, dl);
1398  if (dl)
1399    datalink_Destroy(dl);
1400}
1401
1402void
1403bundle_SetLabel(struct bundle *bundle, const char *label)
1404{
1405  if (label)
1406    strncpy(bundle->cfg.label, label, sizeof bundle->cfg.label - 1);
1407  else
1408    *bundle->cfg.label = '\0';
1409}
1410
1411const char *
1412bundle_GetLabel(struct bundle *bundle)
1413{
1414  return *bundle->cfg.label ? bundle->cfg.label : NULL;
1415}
1416
1417void
1418bundle_ReceiveDatalink(struct bundle *bundle, int s, struct sockaddr_un *sun)
1419{
1420  char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int)];
1421  struct cmsghdr *cmsg = (struct cmsghdr *)cmsgbuf;
1422  struct msghdr msg;
1423  struct iovec iov[SCATTER_SEGMENTS];
1424  struct datalink *dl;
1425  int niov, link_fd, expect, f;
1426  pid_t pid;
1427
1428  log_Printf(LogPHASE, "Receiving datalink\n");
1429
1430  /* Create our scatter/gather array */
1431  niov = 1;
1432  iov[0].iov_len = strlen(Version) + 1;
1433  iov[0].iov_base = (char *)malloc(iov[0].iov_len);
1434  if (datalink2iov(NULL, iov, &niov, sizeof iov / sizeof *iov, 0) == -1) {
1435    close(s);
1436    return;
1437  }
1438
1439  pid = getpid();
1440  write(s, &pid, sizeof pid);
1441
1442  for (f = expect = 0; f < niov; f++)
1443    expect += iov[f].iov_len;
1444
1445  /* Set up our message */
1446  cmsg->cmsg_len = sizeof cmsgbuf;
1447  cmsg->cmsg_level = SOL_SOCKET;
1448  cmsg->cmsg_type = 0;
1449
1450  memset(&msg, '\0', sizeof msg);
1451  msg.msg_name = (caddr_t)sun;
1452  msg.msg_namelen = sizeof *sun;
1453  msg.msg_iov = iov;
1454  msg.msg_iovlen = niov;
1455  msg.msg_control = cmsgbuf;
1456  msg.msg_controllen = sizeof cmsgbuf;
1457
1458  log_Printf(LogDEBUG, "Expecting %d scatter/gather bytes\n", expect);
1459  f = expect + 100;
1460  setsockopt(s, SOL_SOCKET, SO_RCVBUF, &f, sizeof f);
1461  if ((f = recvmsg(s, &msg, MSG_WAITALL)) != expect) {
1462    if (f == -1)
1463      log_Printf(LogERROR, "Failed recvmsg: %s\n", strerror(errno));
1464    else
1465      log_Printf(LogERROR, "Failed recvmsg: Got %d, not %d\n", f, expect);
1466    while (niov--)
1467      free(iov[niov].iov_base);
1468    close(s);
1469    return;
1470  }
1471
1472  write(s, "!", 1);	/* ACK */
1473  close(s);
1474
1475  if (cmsg->cmsg_type != SCM_RIGHTS) {
1476    log_Printf(LogERROR, "Recvmsg: no descriptor received !\n");
1477    while (niov--)
1478      free(iov[niov].iov_base);
1479    return;
1480  }
1481
1482  /* We've successfully received an open file descriptor through our socket */
1483  log_Printf(LogDEBUG, "Receiving device descriptor\n");
1484  link_fd = *(int *)CMSG_DATA(cmsg);
1485
1486  if (strncmp(Version, iov[0].iov_base, iov[0].iov_len)) {
1487    log_Printf(LogWARN, "Cannot receive datalink, incorrect version"
1488               " (\"%.*s\", not \"%s\")\n", (int)iov[0].iov_len,
1489               (char *)iov[0].iov_base, Version);
1490    close(link_fd);
1491    while (niov--)
1492      free(iov[niov].iov_base);
1493    return;
1494  }
1495
1496  niov = 1;
1497  dl = iov2datalink(bundle, iov, &niov, sizeof iov / sizeof *iov, link_fd);
1498  if (dl) {
1499    bundle_DatalinkLinkin(bundle, dl);
1500    datalink_AuthOk(dl);
1501  } else
1502    close(link_fd);
1503
1504  free(iov[0].iov_base);
1505}
1506
1507void
1508bundle_SendDatalink(struct datalink *dl, int s, struct sockaddr_un *sun)
1509{
1510  char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int)], ack;
1511  struct cmsghdr *cmsg = (struct cmsghdr *)cmsgbuf;
1512  struct msghdr msg;
1513  struct iovec iov[SCATTER_SEGMENTS];
1514  int niov, link_fd, f, expect, newsid;
1515  pid_t newpid;
1516
1517  log_Printf(LogPHASE, "Transmitting datalink %s\n", dl->name);
1518
1519  bundle_LinkClosed(dl->bundle, dl);
1520  bundle_DatalinkLinkout(dl->bundle, dl);
1521
1522  /* Build our scatter/gather array */
1523  iov[0].iov_len = strlen(Version) + 1;
1524  iov[0].iov_base = strdup(Version);
1525  niov = 1;
1526
1527  read(s, &newpid, sizeof newpid);
1528  link_fd = datalink2iov(dl, iov, &niov, sizeof iov / sizeof *iov, newpid);
1529
1530  if (link_fd != -1) {
1531    memset(&msg, '\0', sizeof msg);
1532
1533    msg.msg_name = (caddr_t)sun;
1534    msg.msg_namelen = sizeof *sun;
1535    msg.msg_iov = iov;
1536    msg.msg_iovlen = niov;
1537
1538    cmsg->cmsg_len = sizeof cmsgbuf;
1539    cmsg->cmsg_level = SOL_SOCKET;
1540    cmsg->cmsg_type = SCM_RIGHTS;
1541    *(int *)CMSG_DATA(cmsg) = link_fd;
1542    msg.msg_control = cmsgbuf;
1543    msg.msg_controllen = sizeof cmsgbuf;
1544
1545    for (f = expect = 0; f < niov; f++)
1546      expect += iov[f].iov_len;
1547
1548    log_Printf(LogDEBUG, "Sending %d bytes in scatter/gather array\n", expect);
1549
1550    f = expect + SOCKET_OVERHEAD;
1551    setsockopt(s, SOL_SOCKET, SO_SNDBUF, &f, sizeof f);
1552    if (sendmsg(s, &msg, 0) == -1)
1553      log_Printf(LogERROR, "Failed sendmsg: %s\n", strerror(errno));
1554    /* We must get the ACK before closing the descriptor ! */
1555    read(s, &ack, 1);
1556
1557    newsid = tcgetpgrp(link_fd) == getpgrp();
1558    close(link_fd);
1559    if (newsid)
1560      bundle_setsid(dl->bundle, 1);
1561  }
1562  close(s);
1563
1564  while (niov--)
1565    free(iov[niov].iov_base);
1566}
1567
1568int
1569bundle_RenameDatalink(struct bundle *bundle, struct datalink *ndl,
1570                      const char *name)
1571{
1572  struct datalink *dl;
1573
1574  if (!strcasecmp(ndl->name, name))
1575    return 1;
1576
1577  for (dl = bundle->links; dl; dl = dl->next)
1578    if (!strcasecmp(dl->name, name))
1579      return 0;
1580
1581  datalink_Rename(ndl, name);
1582  return 1;
1583}
1584
1585int
1586bundle_SetMode(struct bundle *bundle, struct datalink *dl, int mode)
1587{
1588  int omode;
1589
1590  omode = dl->physical->type;
1591  if (omode == mode)
1592    return 1;
1593
1594  if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO))
1595    /* First auto link */
1596    if (bundle->ncp.ipcp.peer_ip.s_addr == INADDR_ANY) {
1597      log_Printf(LogWARN, "You must `set ifaddr' or `open' before"
1598                 " changing mode to %s\n", mode2Nam(mode));
1599      return 0;
1600    }
1601
1602  if (!datalink_SetMode(dl, mode))
1603    return 0;
1604
1605  if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO) &&
1606      bundle->phase != PHASE_NETWORK)
1607    /* First auto link, we need an interface */
1608    ipcp_InterfaceUp(&bundle->ncp.ipcp);
1609
1610  /* Regenerate phys_type and adjust autoload & idle timers */
1611  bundle_LinksRemoved(bundle);
1612
1613  return 1;
1614}
1615
1616void
1617bundle_setsid(struct bundle *bundle, int holdsession)
1618{
1619  /*
1620   * Lose the current session.  This means getting rid of our pid
1621   * too so that the tty device will really go away, and any getty
1622   * etc will be allowed to restart.
1623   */
1624  pid_t pid, orig;
1625  int fds[2];
1626  char done;
1627  struct datalink *dl;
1628
1629  orig = getpid();
1630  if (pipe(fds) == -1) {
1631    log_Printf(LogERROR, "pipe: %s\n", strerror(errno));
1632    return;
1633  }
1634  switch ((pid = fork())) {
1635    case -1:
1636      log_Printf(LogERROR, "fork: %s\n", strerror(errno));
1637      close(fds[0]);
1638      close(fds[1]);
1639      return;
1640    case 0:
1641      close(fds[0]);
1642      read(fds[1], &done, 1);		/* uu_locks are mine ! */
1643      close(fds[1]);
1644      if (pipe(fds) == -1) {
1645        log_Printf(LogERROR, "pipe(2): %s\n", strerror(errno));
1646        return;
1647      }
1648      switch ((pid = fork())) {
1649        case -1:
1650          log_Printf(LogERROR, "fork(2): %s\n", strerror(errno));
1651          close(fds[0]);
1652          close(fds[1]);
1653          return;
1654        case 0:
1655          close(fds[0]);
1656          bundle_LockTun(bundle);	/* update pid */
1657          read(fds[1], &done, 1);	/* uu_locks are mine ! */
1658          close(fds[1]);
1659          setsid();
1660          log_Printf(LogPHASE, "%d -> %d: %s session control\n",
1661                     (int)orig, (int)getpid(),
1662                     holdsession ? "Passed" : "Dropped");
1663          timer_InitService(0);		/* Start the Timer Service */
1664          break;
1665        default:
1666          close(fds[1]);
1667          /* Give away all our modem locks (to the final process) */
1668          for (dl = bundle->links; dl; dl = dl->next)
1669            if (dl->state != DATALINK_CLOSED)
1670              modem_ChangedPid(dl->physical, pid);
1671          write(fds[0], "!", 1);	/* done */
1672          close(fds[0]);
1673          exit(0);
1674          break;
1675      }
1676      break;
1677    default:
1678      close(fds[1]);
1679      /* Give away all our modem locks (to the intermediate process) */
1680      for (dl = bundle->links; dl; dl = dl->next)
1681        if (dl->state != DATALINK_CLOSED)
1682          modem_ChangedPid(dl->physical, pid);
1683      write(fds[0], "!", 1);	/* done */
1684      close(fds[0]);
1685      if (holdsession) {
1686        int fd, status;
1687
1688        timer_TermService();
1689        signal(SIGPIPE, SIG_DFL);
1690        signal(SIGALRM, SIG_DFL);
1691        signal(SIGHUP, SIG_DFL);
1692        signal(SIGTERM, SIG_DFL);
1693        signal(SIGINT, SIG_DFL);
1694        signal(SIGQUIT, SIG_DFL);
1695        for (fd = getdtablesize(); fd >= 0; fd--)
1696          close(fd);
1697        setuid(geteuid());
1698        /*
1699         * Reap the intermediate process.  As we're not exiting but the
1700         * intermediate is, we don't want it to become defunct.
1701         */
1702        waitpid(pid, &status, 0);
1703        /* Tweak our process arguments.... */
1704        bundle->argv[0] = "session owner";
1705        bundle->argv[1] = NULL;
1706        /*
1707         * Hang around for a HUP.  This should happen as soon as the
1708         * ppp that we passed our ctty descriptor to closes it.
1709         * NOTE: If this process dies, the passed descriptor becomes
1710         *       invalid and will give a select() error by setting one
1711         *       of the error fds, aborting the other ppp.  We don't
1712         *       want that to happen !
1713         */
1714        pause();
1715      }
1716      exit(0);
1717      break;
1718  }
1719}
1720
1721int
1722bundle_HighestState(struct bundle *bundle)
1723{
1724  struct datalink *dl;
1725  int result = DATALINK_CLOSED;
1726
1727  for (dl = bundle->links; dl; dl = dl->next)
1728    if (result < dl->state)
1729      result = dl->state;
1730
1731  return result;
1732}
1733
1734int
1735bundle_Exception(struct bundle *bundle, int fd)
1736{
1737  struct datalink *dl;
1738
1739  for (dl = bundle->links; dl; dl = dl->next)
1740    if (dl->physical->fd == fd) {
1741      datalink_Down(dl, CLOSE_NORMAL);
1742      return 1;
1743    }
1744
1745  return 0;
1746}
1747