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