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