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