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