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