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