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