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