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