xref: /dragonfly/usr.sbin/ppp/bundle.c (revision e62ef63c)
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  * $FreeBSD: src/usr.sbin/ppp/bundle.c,v 1.84.2.12 2002/09/01 02:12: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 <net/tun/if_tun.h>		/* For TUNS* ioctls */
34 #include <net/route.h>
35 #include <netinet/in_systm.h>
36 #include <netinet/ip.h>
37 #include <sys/un.h>
38 
39 #include <errno.h>
40 #include <fcntl.h>
41 #ifdef __OpenBSD__
42 #include <util.h>
43 #else
44 #include <libutil.h>
45 #endif
46 #include <paths.h>
47 #include <stdarg.h>
48 #include <stdio.h>
49 #include <stdlib.h>
50 #include <string.h>
51 #include <sys/uio.h>
52 #include <sys/wait.h>
53 #include <termios.h>
54 #include <unistd.h>
55 
56 #include "layer.h"
57 #include "defs.h"
58 #include "command.h"
59 #include "mbuf.h"
60 #include "log.h"
61 #include "id.h"
62 #include "timer.h"
63 #include "fsm.h"
64 #include "iplist.h"
65 #include "lqr.h"
66 #include "hdlc.h"
67 #include "throughput.h"
68 #include "slcompress.h"
69 #include "ncpaddr.h"
70 #include "ip.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 #ifndef NORADIUS
80 #include "radius.h"
81 #endif
82 #include "ipv6cp.h"
83 #include "ncp.h"
84 #include "bundle.h"
85 #include "async.h"
86 #include "physical.h"
87 #include "auth.h"
88 #include "proto.h"
89 #include "chap.h"
90 #include "tun.h"
91 #include "prompt.h"
92 #include "chat.h"
93 #include "cbcp.h"
94 #include "datalink.h"
95 #include "iface.h"
96 #include "server.h"
97 #include "probe.h"
98 #ifndef NODES
99 #include "mppe.h"
100 #endif
101 
102 #define SCATTER_SEGMENTS 7  /* version, datalink, name, physical,
103                                throughput, throughput, device       */
104 
105 #define SEND_MAXFD 3        /* Max file descriptors passed through
106                                the local domain socket              */
107 
108 static int bundle_RemainingIdleTime(struct bundle *);
109 
110 static const char * const PhaseNames[] = {
111   "Dead", "Establish", "Authenticate", "Network", "Terminate"
112 };
113 
114 const char *
bundle_PhaseName(struct bundle * bundle)115 bundle_PhaseName(struct bundle *bundle)
116 {
117   return bundle->phase <= PHASE_TERMINATE ?
118     PhaseNames[bundle->phase] : "unknown";
119 }
120 
121 void
bundle_NewPhase(struct bundle * bundle,u_int new)122 bundle_NewPhase(struct bundle *bundle, u_int new)
123 {
124   if (new == bundle->phase)
125     return;
126 
127   if (new <= PHASE_TERMINATE)
128     log_Printf(LogPHASE, "bundle: %s\n", PhaseNames[new]);
129 
130   switch (new) {
131   case PHASE_DEAD:
132     bundle->phase = new;
133 #ifndef NODES
134     MPPE_MasterKeyValid = 0;
135 #endif
136     log_DisplayPrompts();
137     break;
138 
139   case PHASE_ESTABLISH:
140     bundle->phase = new;
141     break;
142 
143   case PHASE_AUTHENTICATE:
144     bundle->phase = new;
145     log_DisplayPrompts();
146     break;
147 
148   case PHASE_NETWORK:
149     if (ncp_fsmStart(&bundle->ncp, bundle)) {
150       bundle->phase = new;
151       log_DisplayPrompts();
152     } else {
153       log_Printf(LogPHASE, "bundle: All NCPs are disabled\n");
154       bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
155     }
156     break;
157 
158   case PHASE_TERMINATE:
159     bundle->phase = new;
160     mp_Down(&bundle->ncp.mp);
161     log_DisplayPrompts();
162     break;
163   }
164 }
165 
166 static void
bundle_LayerStart(void * v __unused,struct fsm * fp __unused)167 bundle_LayerStart(void *v __unused, struct fsm *fp __unused)
168 {
169   /* The given FSM is about to start up ! */
170 }
171 
172 
173 void
bundle_Notify(struct bundle * bundle,char c)174 bundle_Notify(struct bundle *bundle, char c)
175 {
176   if (bundle->notify.fd != -1) {
177     int ret;
178 
179     ret = write(bundle->notify.fd, &c, 1);
180     if (c != EX_REDIAL && c != EX_RECONNECT) {
181       if (ret == 1)
182         log_Printf(LogCHAT, "Parent notified of %s\n",
183                    c == EX_NORMAL ? "success" : "failure");
184       else
185         log_Printf(LogERROR, "Failed to notify parent of success\n");
186       close(bundle->notify.fd);
187       bundle->notify.fd = -1;
188     } else if (ret == 1)
189       log_Printf(LogCHAT, "Parent notified of %s\n", ex_desc(c));
190     else
191       log_Printf(LogERROR, "Failed to notify parent of %s\n", ex_desc(c));
192   }
193 }
194 
195 static void
bundle_ClearQueues(void * v)196 bundle_ClearQueues(void *v)
197 {
198   struct bundle *bundle = (struct bundle *)v;
199   struct datalink *dl;
200 
201   log_Printf(LogPHASE, "Clearing choked output queue\n");
202   timer_Stop(&bundle->choked.timer);
203 
204   /*
205    * Emergency time:
206    *
207    * We've had a full queue for PACKET_DEL_SECS seconds without being
208    * able to get rid of any of the packets.  We've probably given up
209    * on the redials at this point, and the queued data has almost
210    * definitely been timed out by the layer above.  As this is preventing
211    * us from reading the TUN_NAME device (we don't want to buffer stuff
212    * indefinitely), we may as well nuke this data and start with a clean
213    * slate !
214    *
215    * Unfortunately, this has the side effect of shafting any compression
216    * dictionaries in use (causing the relevant RESET_REQ/RESET_ACK).
217    */
218 
219   ncp_DeleteQueues(&bundle->ncp);
220   for (dl = bundle->links; dl; dl = dl->next)
221     physical_DeleteQueue(dl->physical);
222 }
223 
224 static void
bundle_LinkAdded(struct bundle * bundle,struct datalink * dl)225 bundle_LinkAdded(struct bundle *bundle, struct datalink *dl)
226 {
227   bundle->phys_type.all |= dl->physical->type;
228   if (dl->state == DATALINK_OPEN)
229     bundle->phys_type.open |= dl->physical->type;
230 
231 #ifndef NORADIUS
232   if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
233       != bundle->phys_type.open && bundle->session.timer.state == TIMER_STOPPED)
234     if (bundle->radius.sessiontime)
235       bundle_StartSessionTimer(bundle, 0);
236 #endif
237 
238   if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
239       != bundle->phys_type.open && bundle->idle.timer.state == TIMER_STOPPED)
240     /* We may need to start our idle timer */
241     bundle_StartIdleTimer(bundle, 0);
242 }
243 
244 void
bundle_LinksRemoved(struct bundle * bundle)245 bundle_LinksRemoved(struct bundle *bundle)
246 {
247   struct datalink *dl;
248 
249   bundle->phys_type.all = bundle->phys_type.open = 0;
250   for (dl = bundle->links; dl; dl = dl->next)
251     bundle_LinkAdded(bundle, dl);
252 
253   bundle_CalculateBandwidth(bundle);
254   mp_CheckAutoloadTimer(&bundle->ncp.mp);
255 
256   if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
257       == bundle->phys_type.open) {
258 #ifndef NORADIUS
259     if (bundle->radius.sessiontime)
260       bundle_StopSessionTimer(bundle);
261 #endif
262     bundle_StopIdleTimer(bundle);
263    }
264 }
265 
266 static void
bundle_LayerUp(void * v,struct fsm * fp)267 bundle_LayerUp(void *v, struct fsm *fp)
268 {
269   /*
270    * The given fsm is now up
271    * If it's an LCP, adjust our phys_mode.open value and check the
272    * autoload timer.
273    * If it's the first NCP, calculate our bandwidth
274    * If it's the first NCP, set our ``upat'' time
275    * If it's the first NCP, start the idle timer.
276    * If it's an NCP, tell our -background parent to go away.
277    * If it's the first NCP, start the autoload timer
278    */
279   struct bundle *bundle = (struct bundle *)v;
280 
281   if (fp->proto == PROTO_LCP) {
282     struct physical *p = link2physical(fp->link);
283 
284     bundle_LinkAdded(bundle, p->dl);
285     mp_CheckAutoloadTimer(&bundle->ncp.mp);
286   } else if (isncp(fp->proto)) {
287     if (ncp_LayersOpen(&fp->bundle->ncp) == 1) {
288       bundle_CalculateBandwidth(fp->bundle);
289       time(&bundle->upat);
290 #ifndef NORADIUS
291       if (bundle->radius.sessiontime)
292         bundle_StartSessionTimer(bundle, 0);
293 #endif
294       bundle_StartIdleTimer(bundle, 0);
295       mp_CheckAutoloadTimer(&fp->bundle->ncp.mp);
296     }
297     bundle_Notify(bundle, EX_NORMAL);
298   } else if (fp->proto == PROTO_CCP)
299     bundle_CalculateBandwidth(fp->bundle);	/* Against ccp_MTUOverhead */
300 }
301 
302 static void
bundle_LayerDown(void * v,struct fsm * fp)303 bundle_LayerDown(void *v, struct fsm *fp)
304 {
305   /*
306    * The given FSM has been told to come down.
307    * If it's our last NCP, stop the idle timer.
308    * If it's our last NCP, clear our ``upat'' value.
309    * If it's our last NCP, stop the autoload timer
310    * If it's an LCP, adjust our phys_type.open value and any timers.
311    * If it's an LCP and we're in multilink mode, adjust our tun
312    * If it's the last LCP, down all NCPs
313    * speed and make sure our minimum sequence number is adjusted.
314    */
315 
316   struct bundle *bundle = (struct bundle *)v;
317 
318   if (isncp(fp->proto)) {
319     if (ncp_LayersOpen(&fp->bundle->ncp) == 0) {
320 #ifndef NORADIUS
321       if (bundle->radius.sessiontime)
322         bundle_StopSessionTimer(bundle);
323 #endif
324       bundle_StopIdleTimer(bundle);
325       bundle->upat = 0;
326       mp_StopAutoloadTimer(&bundle->ncp.mp);
327     }
328   } else if (fp->proto == PROTO_LCP) {
329     struct datalink *dl;
330     struct datalink *lost;
331     int others_active;
332 
333     bundle_LinksRemoved(bundle);  /* adjust timers & phys_type values */
334 
335     lost = NULL;
336     others_active = 0;
337     for (dl = bundle->links; dl; dl = dl->next) {
338       if (fp == &dl->physical->link.lcp.fsm)
339         lost = dl;
340       else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
341         others_active++;
342     }
343 
344     if (bundle->ncp.mp.active) {
345       bundle_CalculateBandwidth(bundle);
346 
347       if (lost)
348         mp_LinkLost(&bundle->ncp.mp, lost);
349       else
350         log_Printf(LogALERT, "Oops, lost an unrecognised datalink (%s) !\n",
351                    fp->link->name);
352     }
353 
354     if (!others_active) {
355       /* Down the NCPs.  We don't expect to get fsm_Close()d ourself ! */
356       ncp2initial(&bundle->ncp);
357       mp_Down(&bundle->ncp.mp);
358     }
359   }
360 }
361 
362 static void
bundle_LayerFinish(void * v,struct fsm * fp)363 bundle_LayerFinish(void *v, struct fsm *fp)
364 {
365   /* The given fsm is now down (fp cannot be NULL)
366    *
367    * If it's the last NCP, fsm_Close all LCPs
368    * If it's the last NCP, bring any MP layer down
369    */
370 
371   struct bundle *bundle = (struct bundle *)v;
372   struct datalink *dl;
373 
374   if (isncp(fp->proto) && !ncp_LayersUnfinished(&bundle->ncp)) {
375     if (bundle_Phase(bundle) != PHASE_DEAD)
376       bundle_NewPhase(bundle, PHASE_TERMINATE);
377     for (dl = bundle->links; dl; dl = dl->next)
378       if (dl->state == DATALINK_OPEN)
379         datalink_Close(dl, CLOSE_STAYDOWN);
380     fsm2initial(fp);
381     mp_Down(&bundle->ncp.mp);
382   }
383 }
384 
385 void
bundle_Close(struct bundle * bundle,const char * name,int how)386 bundle_Close(struct bundle *bundle, const char *name, int how)
387 {
388   /*
389    * Please close the given datalink.
390    * If name == NULL or name is the last datalink, fsm_Close all NCPs
391    * (except our MP)
392    * If it isn't the last datalink, just Close that datalink.
393    */
394 
395   struct datalink *dl, *this_dl;
396   int others_active;
397 
398   others_active = 0;
399   this_dl = NULL;
400 
401   for (dl = bundle->links; dl; dl = dl->next) {
402     if (name && !strcasecmp(name, dl->name))
403       this_dl = dl;
404     if (name == NULL || this_dl == dl) {
405       switch (how) {
406         case CLOSE_LCP:
407           datalink_DontHangup(dl);
408           break;
409         case CLOSE_STAYDOWN:
410           datalink_StayDown(dl);
411           break;
412       }
413     } else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
414       others_active++;
415   }
416 
417   if (name && this_dl == NULL) {
418     log_Printf(LogWARN, "%s: Invalid datalink name\n", name);
419     return;
420   }
421 
422   if (!others_active) {
423 #ifndef NORADIUS
424     if (bundle->radius.sessiontime)
425       bundle_StopSessionTimer(bundle);
426 #endif
427     bundle_StopIdleTimer(bundle);
428     if (ncp_LayersUnfinished(&bundle->ncp))
429       ncp_Close(&bundle->ncp);
430     else {
431       ncp2initial(&bundle->ncp);
432       mp_Down(&bundle->ncp.mp);
433       for (dl = bundle->links; dl; dl = dl->next)
434         datalink_Close(dl, how);
435     }
436   } else if (this_dl && this_dl->state != DATALINK_CLOSED &&
437              this_dl->state != DATALINK_HANGUP)
438     datalink_Close(this_dl, how);
439 }
440 
441 void
bundle_Down(struct bundle * bundle,int how)442 bundle_Down(struct bundle *bundle, int how)
443 {
444   struct datalink *dl;
445 
446   for (dl = bundle->links; dl; dl = dl->next)
447     datalink_Down(dl, how);
448 }
449 
450 static int
bundle_UpdateSet(struct fdescriptor * d,fd_set * r,fd_set * w,fd_set * e,int * n)451 bundle_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
452 {
453   struct bundle *bundle = descriptor2bundle(d);
454   struct datalink *dl;
455   int result, nlinks;
456   u_short ifqueue;
457   size_t queued;
458 
459   result = 0;
460 
461   /* If there are aren't many packets queued, look for some more. */
462   for (nlinks = 0, dl = bundle->links; dl; dl = dl->next)
463     nlinks++;
464 
465   if (nlinks) {
466     queued = r ? ncp_FillPhysicalQueues(&bundle->ncp, bundle) :
467                  ncp_QueueLen(&bundle->ncp);
468 
469     if (r && (bundle->phase == PHASE_NETWORK ||
470               bundle->phys_type.all & PHYS_AUTO)) {
471       /* enough surplus so that we can tell if we're getting swamped */
472       ifqueue = nlinks > bundle->cfg.ifqueue ? nlinks : bundle->cfg.ifqueue;
473       if (queued < ifqueue) {
474         /* Not enough - select() for more */
475         if (bundle->choked.timer.state == TIMER_RUNNING)
476           timer_Stop(&bundle->choked.timer);	/* Not needed any more */
477         FD_SET(bundle->dev.fd, r);
478         if (*n < bundle->dev.fd + 1)
479           *n = bundle->dev.fd + 1;
480         log_Printf(LogTIMER, "%s: fdset(r) %d\n", TUN_NAME, bundle->dev.fd);
481         result++;
482       } else if (bundle->choked.timer.state == TIMER_STOPPED) {
483         bundle->choked.timer.func = bundle_ClearQueues;
484         bundle->choked.timer.name = "output choke";
485         bundle->choked.timer.load = bundle->cfg.choked.timeout * SECTICKS;
486         bundle->choked.timer.arg = bundle;
487         timer_Start(&bundle->choked.timer);
488       }
489     }
490   }
491 
492 #ifndef NORADIUS
493   result += descriptor_UpdateSet(&bundle->radius.desc, r, w, e, n);
494 #endif
495 
496   /* Which links need a select() ? */
497   for (dl = bundle->links; dl; dl = dl->next)
498     result += descriptor_UpdateSet(&dl->desc, r, w, e, n);
499 
500   /*
501    * This *MUST* be called after the datalink UpdateSet()s as it
502    * might be ``holding'' one of the datalinks (death-row) and
503    * wants to be able to de-select() it from the descriptor set.
504    */
505   result += descriptor_UpdateSet(&bundle->ncp.mp.server.desc, r, w, e, n);
506 
507   return result;
508 }
509 
510 static int
bundle_IsSet(struct fdescriptor * d,const fd_set * fdset)511 bundle_IsSet(struct fdescriptor *d, const fd_set *fdset)
512 {
513   struct bundle *bundle = descriptor2bundle(d);
514   struct datalink *dl;
515 
516   for (dl = bundle->links; dl; dl = dl->next)
517     if (descriptor_IsSet(&dl->desc, fdset))
518       return 1;
519 
520 #ifndef NORADIUS
521   if (descriptor_IsSet(&bundle->radius.desc, fdset))
522     return 1;
523 #endif
524 
525   if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
526     return 1;
527 
528   return FD_ISSET(bundle->dev.fd, fdset);
529 }
530 
531 static void
bundle_DescriptorRead(struct fdescriptor * d __unused,struct bundle * bundle,const fd_set * fdset)532 bundle_DescriptorRead(struct fdescriptor *d __unused, struct bundle *bundle,
533                       const fd_set *fdset)
534 {
535   struct datalink *dl;
536   unsigned secs;
537   u_int32_t af;
538 
539   if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
540     descriptor_Read(&bundle->ncp.mp.server.desc, bundle, fdset);
541 
542   for (dl = bundle->links; dl; dl = dl->next)
543     if (descriptor_IsSet(&dl->desc, fdset))
544       descriptor_Read(&dl->desc, bundle, fdset);
545 
546 #ifndef NORADIUS
547   if (descriptor_IsSet(&bundle->radius.desc, fdset))
548     descriptor_Read(&bundle->radius.desc, bundle, fdset);
549 #endif
550 
551   if (FD_ISSET(bundle->dev.fd, fdset)) {
552     struct tun_data tun;
553     int n, pri;
554     u_char *data;
555     size_t sz;
556 
557     if (bundle->dev.header) {
558       data = (u_char *)&tun;
559       sz = sizeof tun;
560     } else {
561       data = tun.data;
562       sz = sizeof tun.data;
563     }
564 
565     /* something to read from tun */
566 
567     n = read(bundle->dev.fd, data, sz);
568     if (n < 0) {
569       log_Printf(LogWARN, "%s: read: %s\n", bundle->dev.Name, strerror(errno));
570       return;
571     }
572 
573     if (bundle->dev.header) {
574       n -= sz - sizeof tun.data;
575       if (n <= 0) {
576         log_Printf(LogERROR, "%s: read: Got only %d bytes of data !\n",
577                    bundle->dev.Name, n);
578         return;
579       }
580       af = ntohl(tun.header.family);
581 #ifndef NOINET6
582       if (af != AF_INET && af != AF_INET6)
583 #else
584       if (af != AF_INET)
585 #endif
586         /* XXX: Should be maintaining drop/family counts ! */
587         return;
588     } else
589       af = AF_INET;
590 
591     if (af == AF_INET && ((struct ip *)tun.data)->ip_dst.s_addr ==
592         bundle->ncp.ipcp.my_ip.s_addr) {
593       /* we've been asked to send something addressed *to* us :( */
594       if (Enabled(bundle, OPT_LOOPBACK)) {
595         pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.in,
596                           NULL, NULL);
597         if (pri >= 0) {
598           n += sz - sizeof tun.data;
599           write(bundle->dev.fd, data, n);
600           log_Printf(LogDEBUG, "Looped back packet addressed to myself\n");
601         }
602         return;
603       } else
604         log_Printf(LogDEBUG, "Oops - forwarding packet addressed to myself\n");
605     }
606 
607     /*
608      * Process on-demand dialup. Output packets are queued within the tunnel
609      * device until the appropriate NCP is opened.
610      */
611 
612     if (bundle_Phase(bundle) == PHASE_DEAD) {
613       /*
614        * Note, we must be in AUTO mode :-/ otherwise our interface should
615        * *not* be UP and we can't receive data
616        */
617       pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.dial,
618                         NULL, NULL);
619       if (pri >= 0)
620         bundle_Open(bundle, NULL, PHYS_AUTO, 0);
621       else
622         /*
623          * Drop the packet.  If we were to queue it, we'd just end up with
624          * a pile of timed-out data in our output queue by the time we get
625          * around to actually dialing.  We'd also prematurely reach the
626          * threshold at which we stop select()ing to read() the tun
627          * device - breaking auto-dial.
628          */
629         return;
630     }
631 
632     secs = 0;
633     pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.out,
634                       NULL, &secs);
635     if (pri >= 0) {
636       /* Prepend the number of seconds timeout given in the filter */
637       tun.header.timeout = secs;
638       ncp_Enqueue(&bundle->ncp, af, pri, (char *)&tun, n + sizeof tun.header);
639     }
640   }
641 }
642 
643 static int
bundle_DescriptorWrite(struct fdescriptor * d __unused,struct bundle * bundle,const fd_set * fdset)644 bundle_DescriptorWrite(struct fdescriptor *d __unused, struct bundle *bundle,
645                        const fd_set *fdset)
646 {
647   struct datalink *dl;
648   int result = 0;
649 
650   /* This is not actually necessary as struct mpserver doesn't Write() */
651   if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
652     if (descriptor_Write(&bundle->ncp.mp.server.desc, bundle, fdset) == 1)
653       result++;
654 
655   for (dl = bundle->links; dl; dl = dl->next)
656     if (descriptor_IsSet(&dl->desc, fdset))
657       switch (descriptor_Write(&dl->desc, bundle, fdset)) {
658       case -1:
659         datalink_ComeDown(dl, CLOSE_NORMAL);
660         break;
661       case 1:
662         result++;
663       }
664 
665   return result;
666 }
667 
668 void
bundle_LockTun(struct bundle * bundle)669 bundle_LockTun(struct bundle *bundle)
670 {
671   FILE *lockfile;
672   char pidfilename[PATH_MAX];
673 
674   snprintf(pidfilename, sizeof pidfilename, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
675   lockfile = ID0fopen(pidfilename, "w");
676   if (lockfile != NULL) {
677     fprintf(lockfile, "%d\n", (int)getpid());
678     fclose(lockfile);
679   }
680   else
681     log_Printf(LogERROR, "Warning: Can't create %s: %s\n",
682                pidfilename, strerror(errno));
683 }
684 
685 static void
bundle_UnlockTun(struct bundle * bundle)686 bundle_UnlockTun(struct bundle *bundle)
687 {
688   char pidfilename[PATH_MAX];
689 
690   snprintf(pidfilename, sizeof pidfilename, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
691   ID0unlink(pidfilename);
692 }
693 
694 struct bundle *
bundle_Create(const char * prefix,int type,int unit)695 bundle_Create(const char *prefix, int type, int unit)
696 {
697   static struct bundle bundle;		/* there can be only one */
698   int enoentcount, err, minunit, maxunit;
699   const char *ifname;
700 #if defined(__DragonFly__) && !defined(NOKLDLOAD)
701   int kldtried;
702 #endif
703 #if defined(TUNSIFMODE) || defined(TUNSLMODE) || defined(TUNSIFHEAD)
704   int iff;
705 #endif
706 
707   if (bundle.iface != NULL) {	/* Already allocated ! */
708     log_Printf(LogALERT, "bundle_Create:  There's only one BUNDLE !\n");
709     return NULL;
710   }
711 
712   if (unit == -1) {
713     minunit = 0;
714     maxunit = -1;
715   } else {
716     minunit = unit;
717     maxunit = unit + 1;
718   }
719   err = ENOENT;
720   enoentcount = 0;
721 #if defined(__DragonFly__) && !defined(NOKLDLOAD)
722   kldtried = 0;
723 #endif
724   for (bundle.unit = minunit; bundle.unit != maxunit; bundle.unit++) {
725     snprintf(bundle.dev.Name, sizeof bundle.dev.Name, "%s%d",
726              prefix, bundle.unit);
727     bundle.dev.fd = ID0open(bundle.dev.Name, O_RDWR);
728     if (bundle.dev.fd >= 0)
729       break;
730     else if (errno == ENXIO || errno == ENOENT) {
731 #if defined(__DragonFly__) && !defined(NOKLDLOAD)
732       if (bundle.unit == minunit && !kldtried++) {
733         /*
734          * Attempt to load the tunnel interface KLD if it isn't loaded
735          * already.
736          */
737         if (loadmodules(LOAD_VERBOSLY, "if_tun", NULL))
738           bundle.unit--;
739         continue;
740       }
741 #endif
742       if (errno != ENOENT || ++enoentcount > 2) {
743         err = errno;
744 	break;
745       }
746     } else
747       err = errno;
748   }
749 
750   if (bundle.dev.fd < 0) {
751     if (unit == -1)
752       log_Printf(LogWARN, "No available tunnel devices found (%s)\n",
753                 strerror(err));
754     else
755       log_Printf(LogWARN, "%s%d: %s\n", prefix, unit, strerror(err));
756     return NULL;
757   }
758 
759   log_SetTun(bundle.unit);
760 
761   ifname = strrchr(bundle.dev.Name, '/');
762   if (ifname == NULL)
763     ifname = bundle.dev.Name;
764   else
765     ifname++;
766 
767   bundle.iface = iface_Create(ifname);
768   if (bundle.iface == NULL) {
769     close(bundle.dev.fd);
770     return NULL;
771   }
772 
773 #ifdef TUNSIFMODE
774   /* Make sure we're POINTOPOINT & IFF_MULTICAST */
775   iff = IFF_POINTOPOINT | IFF_MULTICAST;
776   if (ID0ioctl(bundle.dev.fd, TUNSIFMODE, &iff) < 0)
777     log_Printf(LogERROR, "bundle_Create: ioctl(TUNSIFMODE): %s\n",
778 	       strerror(errno));
779 #endif
780 
781 #ifdef TUNSLMODE
782   /* Make sure we're not prepending sockaddrs */
783   iff = 0;
784   if (ID0ioctl(bundle.dev.fd, TUNSLMODE, &iff) < 0)
785     log_Printf(LogERROR, "bundle_Create: ioctl(TUNSLMODE): %s\n",
786 	       strerror(errno));
787 #endif
788 
789 #ifdef TUNSIFHEAD
790   /* We want the address family please ! */
791   iff = 1;
792   if (ID0ioctl(bundle.dev.fd, TUNSIFHEAD, &iff) < 0) {
793     log_Printf(LogERROR, "bundle_Create: ioctl(TUNSIFHEAD): %s\n",
794 	       strerror(errno));
795     bundle.dev.header = 0;
796   } else
797     bundle.dev.header = 1;
798 #else
799 #ifdef __OpenBSD__
800   /* Always present for OpenBSD */
801   bundle.dev.header = 1;
802 #else
803   /*
804    * If TUNSIFHEAD isn't available and we're not OpenBSD, assume
805    * everything's AF_INET (hopefully the tun device won't pass us
806    * anything else !).
807    */
808   bundle.dev.header = 0;
809 #endif
810 #endif
811 
812   log_Printf(LogPHASE, "Using interface: %s\n", ifname);
813 
814   bundle.bandwidth = 0;
815   bundle.routing_seq = 0;
816   bundle.phase = PHASE_DEAD;
817   bundle.CleaningUp = 0;
818   bundle.NatEnabled = 0;
819 
820   bundle.fsm.LayerStart = bundle_LayerStart;
821   bundle.fsm.LayerUp = bundle_LayerUp;
822   bundle.fsm.LayerDown = bundle_LayerDown;
823   bundle.fsm.LayerFinish = bundle_LayerFinish;
824   bundle.fsm.object = &bundle;
825 
826   bundle.cfg.idle.timeout = NCP_IDLE_TIMEOUT;
827   bundle.cfg.idle.min_timeout = 0;
828   *bundle.cfg.auth.name = '\0';
829   *bundle.cfg.auth.key = '\0';
830   bundle.cfg.opt = OPT_IDCHECK | OPT_LOOPBACK | OPT_SROUTES | OPT_TCPMSSFIXUP |
831                    OPT_THROUGHPUT | OPT_UTMP;
832 #ifndef NOINET6
833   bundle.cfg.opt |= OPT_IPCP;
834   if (probe.ipv6_available)
835     bundle.cfg.opt |= OPT_IPV6CP;
836 #endif
837   *bundle.cfg.label = '\0';
838   bundle.cfg.ifqueue = DEF_IFQUEUE;
839   bundle.cfg.choked.timeout = CHOKED_TIMEOUT;
840   bundle.phys_type.all = type;
841   bundle.phys_type.open = 0;
842   bundle.upat = 0;
843 
844   bundle.links = datalink_Create("deflink", &bundle, type);
845   if (bundle.links == NULL) {
846     log_Printf(LogALERT, "Cannot create data link: %s\n", strerror(errno));
847     iface_Destroy(bundle.iface);
848     bundle.iface = NULL;
849     close(bundle.dev.fd);
850     return NULL;
851   }
852 
853   bundle.desc.type = BUNDLE_DESCRIPTOR;
854   bundle.desc.UpdateSet = bundle_UpdateSet;
855   bundle.desc.IsSet = bundle_IsSet;
856   bundle.desc.Read = bundle_DescriptorRead;
857   bundle.desc.Write = bundle_DescriptorWrite;
858 
859   ncp_Init(&bundle.ncp, &bundle);
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   {
871     int	i;
872     for (i = 0; i < MAXFILTERS; i++) {
873         bundle.filter.in.rule[i].f_action = A_NONE;
874         bundle.filter.out.rule[i].f_action = A_NONE;
875         bundle.filter.dial.rule[i].f_action = A_NONE;
876         bundle.filter.alive.rule[i].f_action = A_NONE;
877     }
878   }
879   memset(&bundle.idle.timer, '\0', sizeof bundle.idle.timer);
880   bundle.idle.done = 0;
881   bundle.notify.fd = -1;
882   memset(&bundle.choked.timer, '\0', sizeof bundle.choked.timer);
883 #ifndef NORADIUS
884   radius_Init(&bundle.radius);
885 #endif
886 
887   /* Clean out any leftover crud */
888   iface_Clear(bundle.iface, &bundle.ncp, 0, IFACE_CLEAR_ALL);
889 
890   bundle_LockTun(&bundle);
891 
892   return &bundle;
893 }
894 
895 static void
bundle_DownInterface(struct bundle * bundle)896 bundle_DownInterface(struct bundle *bundle)
897 {
898   route_IfDelete(bundle, 1);
899   iface_ClearFlags(bundle->iface->name, IFF_UP);
900 }
901 
902 void
bundle_Destroy(struct bundle * bundle)903 bundle_Destroy(struct bundle *bundle)
904 {
905   struct datalink *dl;
906 
907   /*
908    * Clean up the interface.  We don't really need to do the timer_Stop()s,
909    * mp_Down(), iface_Clear() and bundle_DownInterface() unless we're getting
910    * out under exceptional conditions such as a descriptor exception.
911    */
912   timer_Stop(&bundle->idle.timer);
913   timer_Stop(&bundle->choked.timer);
914   mp_Down(&bundle->ncp.mp);
915   iface_Clear(bundle->iface, &bundle->ncp, 0, IFACE_CLEAR_ALL);
916   bundle_DownInterface(bundle);
917 
918 #ifndef NORADIUS
919   /* Tell the radius server the bad news */
920   radius_Destroy(&bundle->radius);
921 #endif
922 
923   /* Again, these are all DATALINK_CLOSED unless we're abending */
924   dl = bundle->links;
925   while (dl)
926     dl = datalink_Destroy(dl);
927 
928   ncp_Destroy(&bundle->ncp);
929 
930   close(bundle->dev.fd);
931   bundle_UnlockTun(bundle);
932 
933   /* In case we never made PHASE_NETWORK */
934   bundle_Notify(bundle, EX_ERRDEAD);
935 
936   iface_Destroy(bundle->iface);
937   bundle->iface = NULL;
938 }
939 
940 void
bundle_LinkClosed(struct bundle * bundle,struct datalink * dl)941 bundle_LinkClosed(struct bundle *bundle, struct datalink *dl)
942 {
943   /*
944    * Our datalink has closed.
945    * CleanDatalinks() (called from DoLoop()) will remove closed
946    * BACKGROUND, FOREGROUND and DIRECT links.
947    * If it's the last data link, enter phase DEAD.
948    *
949    * NOTE: dl may not be in our list (bundle_SendDatalink()) !
950    */
951 
952   struct datalink *odl;
953   int other_links;
954 
955   log_SetTtyCommandMode(dl);
956 
957   other_links = 0;
958   for (odl = bundle->links; odl; odl = odl->next)
959     if (odl != dl && odl->state != DATALINK_CLOSED)
960       other_links++;
961 
962   if (!other_links) {
963     if (dl->physical->type != PHYS_AUTO)	/* Not in -auto mode */
964       bundle_DownInterface(bundle);
965     ncp2initial(&bundle->ncp);
966     mp_Down(&bundle->ncp.mp);
967     bundle_NewPhase(bundle, PHASE_DEAD);
968 #ifndef NORADIUS
969     if (bundle->radius.sessiontime)
970       bundle_StopSessionTimer(bundle);
971 #endif
972     bundle_StopIdleTimer(bundle);
973   }
974 }
975 
976 void
bundle_Open(struct bundle * bundle,const char * name,int mask,int force)977 bundle_Open(struct bundle *bundle, const char *name, int mask, int force)
978 {
979   /*
980    * Please open the given datalink, or all if name == NULL
981    */
982   struct datalink *dl;
983 
984   for (dl = bundle->links; dl; dl = dl->next)
985     if (name == NULL || !strcasecmp(dl->name, name)) {
986       if ((mask & dl->physical->type) &&
987           (dl->state == DATALINK_CLOSED ||
988            (force && dl->state == DATALINK_OPENING &&
989             dl->dial.timer.state == TIMER_RUNNING) ||
990            dl->state == DATALINK_READY)) {
991         timer_Stop(&dl->dial.timer);	/* We're finished with this */
992         datalink_Up(dl, 1, 1);
993         if (mask & PHYS_AUTO)
994           break;			/* Only one AUTO link at a time */
995       }
996       if (name != NULL)
997         break;
998     }
999 }
1000 
1001 struct datalink *
bundle2datalink(struct bundle * bundle,const char * name)1002 bundle2datalink(struct bundle *bundle, const char *name)
1003 {
1004   struct datalink *dl;
1005 
1006   if (name != NULL) {
1007     for (dl = bundle->links; dl; dl = dl->next)
1008       if (!strcasecmp(dl->name, name))
1009         return dl;
1010   } else if (bundle->links && !bundle->links->next)
1011     return bundle->links;
1012 
1013   return NULL;
1014 }
1015 
1016 int
bundle_ShowLinks(struct cmdargs const * arg)1017 bundle_ShowLinks(struct cmdargs const *arg)
1018 {
1019   struct datalink *dl;
1020   struct pppThroughput *t;
1021   unsigned long long octets;
1022   int secs;
1023 
1024   for (dl = arg->bundle->links; dl; dl = dl->next) {
1025     octets = MAX(dl->physical->link.stats.total.in.OctetsPerSecond,
1026                  dl->physical->link.stats.total.out.OctetsPerSecond);
1027 
1028     prompt_Printf(arg->prompt, "Name: %s [%s, %s]",
1029                   dl->name, mode2Nam(dl->physical->type), datalink_State(dl));
1030     if (dl->physical->link.stats.total.rolling && dl->state == DATALINK_OPEN)
1031       prompt_Printf(arg->prompt, " bandwidth %d, %llu bps (%llu bytes/sec)",
1032                     dl->mp.bandwidth ? dl->mp.bandwidth :
1033                                        physical_GetSpeed(dl->physical),
1034                     octets * 8, octets);
1035     prompt_Printf(arg->prompt, "\n");
1036   }
1037 
1038   t = &arg->bundle->ncp.mp.link.stats.total;
1039   octets = MAX(t->in.OctetsPerSecond, t->out.OctetsPerSecond);
1040   secs = t->downtime ? 0 : throughput_uptime(t);
1041   if (secs > t->SamplePeriod)
1042     secs = t->SamplePeriod;
1043   if (secs)
1044     prompt_Printf(arg->prompt, "Currently averaging %llu bps (%llu bytes/sec)"
1045                   " over the last %d secs\n", octets * 8, octets, secs);
1046 
1047   return 0;
1048 }
1049 
1050 static const char *
optval(struct bundle * bundle,int bit)1051 optval(struct bundle *bundle, int bit)
1052 {
1053   return (bundle->cfg.opt & bit) ? "enabled" : "disabled";
1054 }
1055 
1056 int
bundle_ShowStatus(struct cmdargs const * arg)1057 bundle_ShowStatus(struct cmdargs const *arg)
1058 {
1059   int remaining;
1060 
1061   prompt_Printf(arg->prompt, "Phase %s\n", bundle_PhaseName(arg->bundle));
1062   prompt_Printf(arg->prompt, " Device:        %s\n", arg->bundle->dev.Name);
1063   prompt_Printf(arg->prompt, " Interface:     %s @ %lubps",
1064                 arg->bundle->iface->name, arg->bundle->bandwidth);
1065 
1066   if (arg->bundle->upat) {
1067     int secs = bundle_Uptime(arg->bundle);
1068 
1069     prompt_Printf(arg->prompt, ", up time %d:%02d:%02d", secs / 3600,
1070                   (secs / 60) % 60, secs % 60);
1071   }
1072   prompt_Printf(arg->prompt, "\n Queued:        %lu of %u\n",
1073                 (unsigned long)ncp_QueueLen(&arg->bundle->ncp),
1074                 arg->bundle->cfg.ifqueue);
1075 
1076   prompt_Printf(arg->prompt, "\nDefaults:\n");
1077   prompt_Printf(arg->prompt, " Label:             %s\n",
1078                 arg->bundle->cfg.label);
1079   prompt_Printf(arg->prompt, " Auth name:         %s\n",
1080                 arg->bundle->cfg.auth.name);
1081   prompt_Printf(arg->prompt, " Diagnostic socket: ");
1082   if (*server.cfg.sockname != '\0') {
1083     prompt_Printf(arg->prompt, "%s", server.cfg.sockname);
1084     if (server.cfg.mask != (mode_t)-1)
1085       prompt_Printf(arg->prompt, ", mask 0%03o", (int)server.cfg.mask);
1086     prompt_Printf(arg->prompt, "%s\n", server.fd == -1 ? " (not open)" : "");
1087   } else if (server.cfg.port != 0)
1088     prompt_Printf(arg->prompt, "TCP port %d%s\n", server.cfg.port,
1089                   server.fd == -1 ? " (not open)" : "");
1090   else
1091     prompt_Printf(arg->prompt, "none\n");
1092 
1093   prompt_Printf(arg->prompt, " Choked Timer:      %us\n",
1094                 arg->bundle->cfg.choked.timeout);
1095 
1096 #ifndef NORADIUS
1097   radius_Show(&arg->bundle->radius, arg->prompt);
1098 #endif
1099 
1100   prompt_Printf(arg->prompt, " Idle Timer:        ");
1101   if (arg->bundle->cfg.idle.timeout) {
1102     prompt_Printf(arg->prompt, "%us", arg->bundle->cfg.idle.timeout);
1103     if (arg->bundle->cfg.idle.min_timeout)
1104       prompt_Printf(arg->prompt, ", min %us",
1105                     arg->bundle->cfg.idle.min_timeout);
1106     remaining = bundle_RemainingIdleTime(arg->bundle);
1107     if (remaining != -1)
1108       prompt_Printf(arg->prompt, " (%ds remaining)", remaining);
1109     prompt_Printf(arg->prompt, "\n");
1110   } else
1111     prompt_Printf(arg->prompt, "disabled\n");
1112 
1113   prompt_Printf(arg->prompt, " Filter Decap:      %-20.20s",
1114                 optval(arg->bundle, OPT_FILTERDECAP));
1115   prompt_Printf(arg->prompt, " ID check:          %s\n",
1116                 optval(arg->bundle, OPT_IDCHECK));
1117   prompt_Printf(arg->prompt, " Iface-Alias:       %-20.20s",
1118                 optval(arg->bundle, OPT_IFACEALIAS));
1119 #ifndef NOINET6
1120   prompt_Printf(arg->prompt, " IPCP:              %s\n",
1121                 optval(arg->bundle, OPT_IPCP));
1122   prompt_Printf(arg->prompt, " IPV6CP:            %-20.20s",
1123                 optval(arg->bundle, OPT_IPV6CP));
1124 #endif
1125   prompt_Printf(arg->prompt, " Keep-Session:      %s\n",
1126                 optval(arg->bundle, OPT_KEEPSESSION));
1127   prompt_Printf(arg->prompt, " Loopback:          %-20.20s",
1128                 optval(arg->bundle, OPT_LOOPBACK));
1129   prompt_Printf(arg->prompt, " PasswdAuth:        %s\n",
1130                 optval(arg->bundle, OPT_PASSWDAUTH));
1131   prompt_Printf(arg->prompt, " Proxy:             %-20.20s",
1132                 optval(arg->bundle, OPT_PROXY));
1133   prompt_Printf(arg->prompt, " Proxyall:          %s\n",
1134                 optval(arg->bundle, OPT_PROXYALL));
1135   prompt_Printf(arg->prompt, " Sticky Routes:     %-20.20s",
1136                 optval(arg->bundle, OPT_SROUTES));
1137   prompt_Printf(arg->prompt, " TCPMSS Fixup:      %s\n",
1138                 optval(arg->bundle, OPT_TCPMSSFIXUP));
1139   prompt_Printf(arg->prompt, " Throughput:        %-20.20s",
1140                 optval(arg->bundle, OPT_THROUGHPUT));
1141   prompt_Printf(arg->prompt, " Utmp Logging:      %s\n",
1142                 optval(arg->bundle, OPT_UTMP));
1143 
1144   return 0;
1145 }
1146 
1147 static void
bundle_IdleTimeout(void * v)1148 bundle_IdleTimeout(void *v)
1149 {
1150   struct bundle *bundle = (struct bundle *)v;
1151 
1152   log_Printf(LogPHASE, "Idle timer expired\n");
1153   bundle_StopIdleTimer(bundle);
1154   bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
1155 }
1156 
1157 /*
1158  *  Start Idle timer. If timeout is reached, we call bundle_Close() to
1159  *  close LCP and link.
1160  */
1161 void
bundle_StartIdleTimer(struct bundle * bundle,unsigned secs)1162 bundle_StartIdleTimer(struct bundle *bundle, unsigned secs)
1163 {
1164   timer_Stop(&bundle->idle.timer);
1165   if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) !=
1166       bundle->phys_type.open && bundle->cfg.idle.timeout) {
1167     time_t now = time(NULL);
1168 
1169     if (secs == 0)
1170       secs = bundle->cfg.idle.timeout;
1171 
1172     /* We want at least `secs' */
1173     if (bundle->cfg.idle.min_timeout > secs && bundle->upat) {
1174       unsigned up = now - bundle->upat;
1175 
1176       if (bundle->cfg.idle.min_timeout > up &&
1177           bundle->cfg.idle.min_timeout - up > (long long)secs)
1178         /* Only increase from the current `remaining' value */
1179         secs = bundle->cfg.idle.min_timeout - up;
1180     }
1181     bundle->idle.timer.func = bundle_IdleTimeout;
1182     bundle->idle.timer.name = "idle";
1183     bundle->idle.timer.load = secs * SECTICKS;
1184     bundle->idle.timer.arg = bundle;
1185     timer_Start(&bundle->idle.timer);
1186     bundle->idle.done = now + secs;
1187   }
1188 }
1189 
1190 void
bundle_SetIdleTimer(struct bundle * bundle,unsigned timeout,unsigned min_timeout)1191 bundle_SetIdleTimer(struct bundle *bundle, unsigned timeout,
1192 		    unsigned min_timeout)
1193 {
1194   bundle->cfg.idle.timeout = timeout;
1195   bundle->cfg.idle.min_timeout = min_timeout;
1196   if (ncp_LayersOpen(&bundle->ncp))
1197     bundle_StartIdleTimer(bundle, 0);
1198 }
1199 
1200 void
bundle_StopIdleTimer(struct bundle * bundle)1201 bundle_StopIdleTimer(struct bundle *bundle)
1202 {
1203   timer_Stop(&bundle->idle.timer);
1204   bundle->idle.done = 0;
1205 }
1206 
1207 static int
bundle_RemainingIdleTime(struct bundle * bundle)1208 bundle_RemainingIdleTime(struct bundle *bundle)
1209 {
1210   if (bundle->idle.done)
1211     return bundle->idle.done - time(NULL);
1212   return -1;
1213 }
1214 
1215 #ifndef NORADIUS
1216 
1217 static void
bundle_SessionTimeout(void * v)1218 bundle_SessionTimeout(void *v)
1219 {
1220   struct bundle *bundle = (struct bundle *)v;
1221 
1222   log_Printf(LogPHASE, "Session-Timeout timer expired\n");
1223   bundle_StopSessionTimer(bundle);
1224   bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
1225 }
1226 
1227 void
bundle_StartSessionTimer(struct bundle * bundle,unsigned secs)1228 bundle_StartSessionTimer(struct bundle *bundle, unsigned secs)
1229 {
1230   timer_Stop(&bundle->session.timer);
1231   if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) !=
1232       bundle->phys_type.open && bundle->radius.sessiontime) {
1233     time_t now = time(NULL);
1234 
1235     if (secs == 0)
1236       secs = bundle->radius.sessiontime;
1237 
1238     bundle->session.timer.func = bundle_SessionTimeout;
1239     bundle->session.timer.name = "session";
1240     bundle->session.timer.load = secs * SECTICKS;
1241     bundle->session.timer.arg = bundle;
1242     timer_Start(&bundle->session.timer);
1243     bundle->session.done = now + secs;
1244   }
1245 }
1246 
1247 void
bundle_StopSessionTimer(struct bundle * bundle)1248 bundle_StopSessionTimer(struct bundle *bundle)
1249 {
1250   timer_Stop(&bundle->session.timer);
1251   bundle->session.done = 0;
1252 }
1253 
1254 #endif
1255 
1256 int
bundle_IsDead(struct bundle * bundle)1257 bundle_IsDead(struct bundle *bundle)
1258 {
1259   return !bundle->links || (bundle->phase == PHASE_DEAD && bundle->CleaningUp);
1260 }
1261 
1262 static struct datalink *
bundle_DatalinkLinkout(struct bundle * bundle,struct datalink * dl)1263 bundle_DatalinkLinkout(struct bundle *bundle, struct datalink *dl)
1264 {
1265   struct datalink **dlp;
1266 
1267   for (dlp = &bundle->links; *dlp; dlp = &(*dlp)->next)
1268     if (*dlp == dl) {
1269       *dlp = dl->next;
1270       dl->next = NULL;
1271       bundle_LinksRemoved(bundle);
1272       return dl;
1273     }
1274 
1275   return NULL;
1276 }
1277 
1278 static void
bundle_DatalinkLinkin(struct bundle * bundle,struct datalink * dl)1279 bundle_DatalinkLinkin(struct bundle *bundle, struct datalink *dl)
1280 {
1281   struct datalink **dlp = &bundle->links;
1282 
1283   while (*dlp)
1284     dlp = &(*dlp)->next;
1285 
1286   *dlp = dl;
1287   dl->next = NULL;
1288 
1289   bundle_LinkAdded(bundle, dl);
1290   mp_CheckAutoloadTimer(&bundle->ncp.mp);
1291 }
1292 
1293 void
bundle_CleanDatalinks(struct bundle * bundle)1294 bundle_CleanDatalinks(struct bundle *bundle)
1295 {
1296   struct datalink **dlp = &bundle->links;
1297   int found = 0;
1298 
1299   while (*dlp)
1300     if ((*dlp)->state == DATALINK_CLOSED &&
1301         (*dlp)->physical->type &
1302         (PHYS_DIRECT|PHYS_BACKGROUND|PHYS_FOREGROUND)) {
1303       *dlp = datalink_Destroy(*dlp);
1304       found++;
1305     } else
1306       dlp = &(*dlp)->next;
1307 
1308   if (found)
1309     bundle_LinksRemoved(bundle);
1310 }
1311 
1312 int
bundle_DatalinkClone(struct bundle * bundle,struct datalink * dl,const char * name)1313 bundle_DatalinkClone(struct bundle *bundle, struct datalink *dl,
1314                      const char *name)
1315 {
1316   if (bundle2datalink(bundle, name)) {
1317     log_Printf(LogWARN, "Clone: %s: name already exists\n", name);
1318     return 0;
1319   }
1320 
1321   bundle_DatalinkLinkin(bundle, datalink_Clone(dl, name));
1322   return 1;
1323 }
1324 
1325 void
bundle_DatalinkRemove(struct bundle * bundle,struct datalink * dl)1326 bundle_DatalinkRemove(struct bundle *bundle, struct datalink *dl)
1327 {
1328   dl = bundle_DatalinkLinkout(bundle, dl);
1329   if (dl)
1330     datalink_Destroy(dl);
1331 }
1332 
1333 void
bundle_SetLabel(struct bundle * bundle,const char * label)1334 bundle_SetLabel(struct bundle *bundle, const char *label)
1335 {
1336   if (label)
1337     strncpy(bundle->cfg.label, label, sizeof bundle->cfg.label - 1);
1338   else
1339     *bundle->cfg.label = '\0';
1340 }
1341 
1342 const char *
bundle_GetLabel(struct bundle * bundle)1343 bundle_GetLabel(struct bundle *bundle)
1344 {
1345   return *bundle->cfg.label ? bundle->cfg.label : NULL;
1346 }
1347 
1348 int
bundle_LinkSize(void)1349 bundle_LinkSize(void)
1350 {
1351   struct iovec iov[SCATTER_SEGMENTS];
1352   int niov, expect, f;
1353 
1354   iov[0].iov_len = strlen(Version) + 1;
1355   iov[0].iov_base = NULL;
1356   niov = 1;
1357   if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1358     log_Printf(LogERROR, "Cannot determine space required for link\n");
1359     return 0;
1360   }
1361 
1362   for (f = expect = 0; f < niov; f++)
1363     expect += iov[f].iov_len;
1364 
1365   return expect;
1366 }
1367 
1368 void
bundle_ReceiveDatalink(struct bundle * bundle,int s)1369 bundle_ReceiveDatalink(struct bundle *bundle, int s)
1370 {
1371   char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int) * SEND_MAXFD];
1372   int niov, expect, f, *fd, nfd, onfd;
1373   ssize_t got;
1374   struct iovec iov[SCATTER_SEGMENTS];
1375   struct cmsghdr *cmsg;
1376   struct msghdr msg;
1377   struct datalink *dl;
1378   pid_t pid;
1379 
1380   log_Printf(LogPHASE, "Receiving datalink\n");
1381 
1382   /*
1383    * Create our scatter/gather array - passing NULL gets the space
1384    * allocation requirement rather than actually flattening the
1385    * structures.
1386    */
1387   iov[0].iov_len = strlen(Version) + 1;
1388   iov[0].iov_base = NULL;
1389   niov = 1;
1390   if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1391     log_Printf(LogERROR, "Cannot determine space required for link\n");
1392     return;
1393   }
1394 
1395   /* Allocate the scatter/gather array for recvmsg() */
1396   for (f = expect = 0; f < niov; f++) {
1397     if ((iov[f].iov_base = malloc(iov[f].iov_len)) == NULL) {
1398       log_Printf(LogERROR, "Cannot allocate space to receive link\n");
1399       return;
1400     }
1401     if (f)
1402       expect += iov[f].iov_len;
1403   }
1404 
1405   /* Set up our message */
1406   cmsg = (struct cmsghdr *)cmsgbuf;
1407   cmsg->cmsg_len = sizeof cmsgbuf;
1408   cmsg->cmsg_level = SOL_SOCKET;
1409   cmsg->cmsg_type = 0;
1410 
1411   memset(&msg, '\0', sizeof msg);
1412   msg.msg_name = NULL;
1413   msg.msg_namelen = 0;
1414   msg.msg_iov = iov;
1415   msg.msg_iovlen = 1;		/* Only send the version at the first pass */
1416   msg.msg_control = cmsgbuf;
1417   msg.msg_controllen = sizeof cmsgbuf;
1418 
1419   log_Printf(LogDEBUG, "Expecting %u scatter/gather bytes\n",
1420              (unsigned)iov[0].iov_len);
1421 
1422   if ((got = recvmsg(s, &msg, MSG_WAITALL)) != (ssize_t)iov[0].iov_len) {
1423     if (got == -1)
1424       log_Printf(LogERROR, "Failed recvmsg: %s\n", strerror(errno));
1425     else
1426       log_Printf(LogERROR, "Failed recvmsg: Got %zu, not %u\n",
1427                  got, (unsigned)iov[0].iov_len);
1428     while (niov--)
1429       free(iov[niov].iov_base);
1430     return;
1431   }
1432 
1433   if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) {
1434     log_Printf(LogERROR, "Recvmsg: no descriptors received !\n");
1435     while (niov--)
1436       free(iov[niov].iov_base);
1437     return;
1438   }
1439 
1440   fd = (int *)CMSG_DATA(cmsg);
1441   nfd = ((caddr_t)cmsg + cmsg->cmsg_len - (caddr_t)fd) / sizeof(int);
1442 
1443   if (nfd < 2) {
1444     log_Printf(LogERROR, "Recvmsg: %d descriptor%s received (too few) !\n",
1445                nfd, nfd == 1 ? "" : "s");
1446     while (nfd--)
1447       close(fd[nfd]);
1448     while (niov--)
1449       free(iov[niov].iov_base);
1450     return;
1451   }
1452 
1453   /*
1454    * We've successfully received two or more open file descriptors
1455    * through our socket, plus a version string.  Make sure it's the
1456    * correct version, and drop the connection if it's not.
1457    */
1458   if (strncmp(Version, iov[0].iov_base, iov[0].iov_len)) {
1459     log_Printf(LogWARN, "Cannot receive datalink, incorrect version"
1460                " (\"%.*s\", not \"%s\")\n", (int)iov[0].iov_len,
1461                (char *)iov[0].iov_base, Version);
1462     while (nfd--)
1463       close(fd[nfd]);
1464     while (niov--)
1465       free(iov[niov].iov_base);
1466     return;
1467   }
1468 
1469   /*
1470    * Everything looks good.  Send the other side our process id so that
1471    * they can transfer lock ownership, and wait for them to send the
1472    * actual link data.
1473    */
1474   pid = getpid();
1475   if ((got = write(fd[1], &pid, sizeof pid)) != sizeof pid) {
1476     if (got == -1)
1477       log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1478     else
1479       log_Printf(LogERROR, "Failed write: Got %zu, not %d\n", got,
1480                  (int)(sizeof pid));
1481     while (nfd--)
1482       close(fd[nfd]);
1483     while (niov--)
1484       free(iov[niov].iov_base);
1485     return;
1486   }
1487 
1488   if ((got = readv(fd[1], iov + 1, niov - 1)) != expect) {
1489     if (got == -1)
1490       log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1491     else
1492       log_Printf(LogERROR, "Failed write: Got %zu, not %d\n", got, expect);
1493     while (nfd--)
1494       close(fd[nfd]);
1495     while (niov--)
1496       free(iov[niov].iov_base);
1497     return;
1498   }
1499   close(fd[1]);
1500 
1501   onfd = nfd;	/* We've got this many in our array */
1502   nfd -= 2;	/* Don't include p->fd and our reply descriptor */
1503   niov = 1;	/* Skip the version id */
1504   dl = iov2datalink(bundle, iov, &niov, NELEM(iov), fd[0],
1505                     fd + 2, &nfd);
1506   if (dl) {
1507 
1508     if (nfd) {
1509       log_Printf(LogERROR, "bundle_ReceiveDatalink: Failed to handle %d "
1510                  "auxiliary file descriptors (%d remain)\n", onfd, nfd);
1511       datalink_Destroy(dl);
1512       while (nfd--)
1513         close(fd[onfd--]);
1514       close(fd[0]);
1515     } else {
1516       bundle_DatalinkLinkin(bundle, dl);
1517       datalink_AuthOk(dl);
1518       bundle_CalculateBandwidth(dl->bundle);
1519     }
1520   } else {
1521     while (nfd--)
1522       close(fd[onfd--]);
1523     close(fd[0]);
1524     close(fd[1]);
1525   }
1526 
1527   free(iov[0].iov_base);
1528 }
1529 
1530 void
bundle_SendDatalink(struct datalink * dl,int s,struct sockaddr_un * sun)1531 bundle_SendDatalink(struct datalink *dl, int s, struct sockaddr_un *sun)
1532 {
1533   char cmsgbuf[CMSG_SPACE(sizeof(int) * SEND_MAXFD)];
1534   const char *constlock;
1535   char *lock;
1536   struct cmsghdr *cmsg;
1537   struct msghdr msg;
1538   struct iovec iov[SCATTER_SEGMENTS];
1539   int niov, f, expect, newsid, fd[SEND_MAXFD], nfd, reply[2];
1540   ssize_t got;
1541   pid_t newpid;
1542 
1543   log_Printf(LogPHASE, "Transmitting datalink %s\n", dl->name);
1544 
1545   /* Record the base device name for a lock transfer later */
1546   constlock = physical_LockedDevice(dl->physical);
1547   if (constlock) {
1548     lock = alloca(strlen(constlock) + 1);
1549     strcpy(lock, constlock);
1550   } else
1551     lock = NULL;
1552 
1553   bundle_LinkClosed(dl->bundle, dl);
1554   bundle_DatalinkLinkout(dl->bundle, dl);
1555 
1556   /* Build our scatter/gather array */
1557   iov[0].iov_len = strlen(Version) + 1;
1558   iov[0].iov_base = strdup(Version);
1559   niov = 1;
1560   nfd = 0;
1561 
1562   fd[0] = datalink2iov(dl, iov, &niov, SCATTER_SEGMENTS, fd + 2, &nfd);
1563 
1564   if (fd[0] != -1 && socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, reply) != -1) {
1565     /*
1566      * fd[1] is used to get the peer process id back, then to confirm that
1567      * we've transferred any device locks to that process id.
1568      */
1569     fd[1] = reply[1];
1570 
1571     nfd += 2;			/* Include fd[0] and fd[1] */
1572     memset(&msg, '\0', sizeof msg);
1573 
1574     msg.msg_name = NULL;
1575     msg.msg_namelen = 0;
1576     /*
1577      * Only send the version to start...  We used to send the whole lot, but
1578      * this caused problems with our RECVBUF size as a single link is about
1579      * 22k !  This way, we should bump into no limits.
1580      */
1581     msg.msg_iovlen = 1;
1582     msg.msg_iov = iov;
1583     msg.msg_control = cmsgbuf;
1584     msg.msg_controllen = CMSG_SPACE(sizeof(int) * nfd);
1585     msg.msg_flags = 0;
1586 
1587     cmsg = (struct cmsghdr *)cmsgbuf;
1588     cmsg->cmsg_len = msg.msg_controllen;
1589     cmsg->cmsg_level = SOL_SOCKET;
1590     cmsg->cmsg_type = SCM_RIGHTS;
1591 
1592     for (f = 0; f < nfd; f++)
1593       *((int *)CMSG_DATA(cmsg) + f) = fd[f];
1594 
1595     for (f = 1, expect = 0; f < niov; f++)
1596       expect += iov[f].iov_len;
1597 
1598     if (setsockopt(reply[0], SOL_SOCKET, SO_SNDBUF, &expect, sizeof(int)) == -1)
1599       log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1600                  strerror(errno));
1601     if (setsockopt(reply[1], SOL_SOCKET, SO_RCVBUF, &expect, sizeof(int)) == -1)
1602       log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1603                  strerror(errno));
1604 
1605     log_Printf(LogDEBUG, "Sending %d descriptor%s and %u bytes in scatter"
1606                "/gather array\n", nfd, nfd == 1 ? "" : "s",
1607                (unsigned)iov[0].iov_len);
1608 
1609     if ((got = sendmsg(s, &msg, 0)) == -1)
1610       log_Printf(LogERROR, "Failed sendmsg: %s: %s\n",
1611                  sun->sun_path, strerror(errno));
1612     else if (got != (ssize_t)iov[0].iov_len)
1613       log_Printf(LogERROR, "%s: Failed initial sendmsg: Only sent %zu of %u\n",
1614                  sun->sun_path, got, (unsigned)iov[0].iov_len);
1615     else {
1616       /* We must get the ACK before closing the descriptor ! */
1617       int res;
1618 
1619       if ((got = read(reply[0], &newpid, sizeof newpid)) == sizeof newpid) {
1620         log_Printf(LogDEBUG, "Received confirmation from pid %ld\n",
1621                    (long)newpid);
1622         if (lock && (res = ID0uu_lock_txfr(lock, newpid)) != UU_LOCK_OK)
1623             log_Printf(LogERROR, "uu_lock_txfr: %s\n", uu_lockerr(res));
1624 
1625         log_Printf(LogDEBUG, "Transmitting link (%d bytes)\n", expect);
1626         if ((got = writev(reply[0], iov + 1, niov - 1)) != expect) {
1627           if (got == -1)
1628             log_Printf(LogERROR, "%s: Failed writev: %s\n",
1629                        sun->sun_path, strerror(errno));
1630           else
1631             log_Printf(LogERROR, "%s: Failed writev: Wrote %zu of %d\n",
1632                        sun->sun_path, got, expect);
1633         }
1634       } else if (got == -1)
1635         log_Printf(LogERROR, "%s: Failed socketpair read: %s\n",
1636                    sun->sun_path, strerror(errno));
1637       else
1638         log_Printf(LogERROR, "%s: Failed socketpair read: Got %zu of %d\n",
1639                    sun->sun_path, got, (int)(sizeof newpid));
1640     }
1641 
1642     close(reply[0]);
1643     close(reply[1]);
1644 
1645     newsid = Enabled(dl->bundle, OPT_KEEPSESSION) ||
1646              tcgetpgrp(fd[0]) == getpgrp();
1647     while (nfd)
1648       close(fd[--nfd]);
1649     if (newsid)
1650       bundle_setsid(dl->bundle, got != -1);
1651   }
1652   close(s);
1653 
1654   while (niov--)
1655     free(iov[niov].iov_base);
1656 }
1657 
1658 int
bundle_RenameDatalink(struct bundle * bundle,struct datalink * ndl,const char * name)1659 bundle_RenameDatalink(struct bundle *bundle, struct datalink *ndl,
1660                       const char *name)
1661 {
1662   struct datalink *dl;
1663 
1664   if (!strcasecmp(ndl->name, name))
1665     return 1;
1666 
1667   for (dl = bundle->links; dl; dl = dl->next)
1668     if (!strcasecmp(dl->name, name))
1669       return 0;
1670 
1671   datalink_Rename(ndl, name);
1672   return 1;
1673 }
1674 
1675 int
bundle_SetMode(struct bundle * bundle,struct datalink * dl,int mode)1676 bundle_SetMode(struct bundle *bundle, struct datalink *dl, int mode)
1677 {
1678   int omode;
1679 
1680   omode = dl->physical->type;
1681   if (omode == mode)
1682     return 1;
1683 
1684   if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO))
1685     /* First auto link */
1686     if (bundle->ncp.ipcp.peer_ip.s_addr == INADDR_ANY) {
1687       log_Printf(LogWARN, "You must `set ifaddr' or `open' before"
1688                  " changing mode to %s\n", mode2Nam(mode));
1689       return 0;
1690     }
1691 
1692   if (!datalink_SetMode(dl, mode))
1693     return 0;
1694 
1695   if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO) &&
1696       bundle->phase != PHASE_NETWORK)
1697     /* First auto link, we need an interface */
1698     ipcp_InterfaceUp(&bundle->ncp.ipcp);
1699 
1700   /* Regenerate phys_type and adjust idle timer */
1701   bundle_LinksRemoved(bundle);
1702 
1703   return 1;
1704 }
1705 
1706 void
bundle_setsid(struct bundle * bundle,int holdsession)1707 bundle_setsid(struct bundle *bundle, int holdsession)
1708 {
1709   /*
1710    * Lose the current session.  This means getting rid of our pid
1711    * too so that the tty device will really go away, and any getty
1712    * etc will be allowed to restart.
1713    */
1714   pid_t pid, orig;
1715   int fds[2];
1716   char done;
1717   struct datalink *dl;
1718 
1719   if (!holdsession && bundle_IsDead(bundle)) {
1720     /*
1721      * No need to lose our session after all... we're going away anyway
1722      *
1723      * We should really stop the timer and pause if holdsession is set and
1724      * the bundle's dead, but that leaves other resources lying about :-(
1725      */
1726     return;
1727   }
1728 
1729   orig = getpid();
1730   if (pipe(fds) == -1) {
1731     log_Printf(LogERROR, "pipe: %s\n", strerror(errno));
1732     return;
1733   }
1734   switch ((pid = fork())) {
1735     case -1:
1736       log_Printf(LogERROR, "fork: %s\n", strerror(errno));
1737       close(fds[0]);
1738       close(fds[1]);
1739       return;
1740     case 0:
1741       close(fds[1]);
1742       read(fds[0], &done, 1);		/* uu_locks are mine ! */
1743       close(fds[0]);
1744       if (pipe(fds) == -1) {
1745         log_Printf(LogERROR, "pipe(2): %s\n", strerror(errno));
1746         return;
1747       }
1748       switch ((pid = fork())) {
1749         case -1:
1750           log_Printf(LogERROR, "fork(2): %s\n", strerror(errno));
1751           close(fds[0]);
1752           close(fds[1]);
1753           return;
1754         case 0:
1755           close(fds[1]);
1756           bundle_LockTun(bundle);	/* update pid */
1757           read(fds[0], &done, 1);	/* uu_locks are mine ! */
1758           close(fds[0]);
1759           setsid();
1760           bundle_ChangedPID(bundle);
1761           log_Printf(LogDEBUG, "%ld -> %ld: %s session control\n",
1762                      (long)orig, (long)getpid(),
1763                      holdsession ? "Passed" : "Dropped");
1764           timer_InitService(0);		/* Start the Timer Service */
1765           break;
1766         default:
1767           close(fds[0]);
1768           /* Give away all our physical locks (to the final process) */
1769           for (dl = bundle->links; dl; dl = dl->next)
1770             if (dl->state != DATALINK_CLOSED)
1771               physical_ChangedPid(dl->physical, pid);
1772           write(fds[1], "!", 1);	/* done */
1773           close(fds[1]);
1774           _exit(0);
1775           break;
1776       }
1777       break;
1778     default:
1779       close(fds[0]);
1780       /* Give away all our physical locks (to the intermediate process) */
1781       for (dl = bundle->links; dl; dl = dl->next)
1782         if (dl->state != DATALINK_CLOSED)
1783           physical_ChangedPid(dl->physical, pid);
1784       write(fds[1], "!", 1);	/* done */
1785       close(fds[1]);
1786       if (holdsession) {
1787         int fd, status;
1788 
1789         timer_TermService();
1790         signal(SIGPIPE, SIG_DFL);
1791         signal(SIGALRM, SIG_DFL);
1792         signal(SIGHUP, SIG_DFL);
1793         signal(SIGTERM, SIG_DFL);
1794         signal(SIGINT, SIG_DFL);
1795         signal(SIGQUIT, SIG_DFL);
1796         for (fd = getdtablesize(); fd >= 0; fd--)
1797           close(fd);
1798         /*
1799          * Reap the intermediate process.  As we're not exiting but the
1800          * intermediate is, we don't want it to become defunct.
1801          */
1802         waitpid(pid, &status, 0);
1803         /* Tweak our process arguments.... */
1804         SetTitle("session owner");
1805 #ifndef NOSUID
1806         setuid(ID0realuid());
1807 #endif
1808         /*
1809          * Hang around for a HUP.  This should happen as soon as the
1810          * ppp that we passed our ctty descriptor to closes it.
1811          * NOTE: If this process dies, the passed descriptor becomes
1812          *       invalid and will give a select() error by setting one
1813          *       of the error fds, aborting the other ppp.  We don't
1814          *       want that to happen !
1815          */
1816         pause();
1817       }
1818       _exit(0);
1819       break;
1820   }
1821 }
1822 
1823 unsigned
bundle_HighestState(struct bundle * bundle)1824 bundle_HighestState(struct bundle *bundle)
1825 {
1826   struct datalink *dl;
1827   unsigned result = DATALINK_CLOSED;
1828 
1829   for (dl = bundle->links; dl; dl = dl->next)
1830     if (result < dl->state)
1831       result = dl->state;
1832 
1833   return result;
1834 }
1835 
1836 int
bundle_Exception(struct bundle * bundle,int fd)1837 bundle_Exception(struct bundle *bundle, int fd)
1838 {
1839   struct datalink *dl;
1840 
1841   for (dl = bundle->links; dl; dl = dl->next)
1842     if (dl->physical->fd == fd) {
1843       datalink_Down(dl, CLOSE_NORMAL);
1844       return 1;
1845     }
1846 
1847   return 0;
1848 }
1849 
1850 void
bundle_AdjustFilters(struct bundle * bundle,struct ncpaddr * local,struct ncpaddr * remote)1851 bundle_AdjustFilters(struct bundle *bundle, struct ncpaddr *local,
1852                      struct ncpaddr *remote)
1853 {
1854   filter_AdjustAddr(&bundle->filter.in, local, remote, NULL);
1855   filter_AdjustAddr(&bundle->filter.out, local, remote, NULL);
1856   filter_AdjustAddr(&bundle->filter.dial, local, remote, NULL);
1857   filter_AdjustAddr(&bundle->filter.alive, local, remote, NULL);
1858 }
1859 
1860 void
bundle_AdjustDNS(struct bundle * bundle)1861 bundle_AdjustDNS(struct bundle *bundle)
1862 {
1863   struct in_addr *dns = bundle->ncp.ipcp.ns.dns;
1864 
1865   filter_AdjustAddr(&bundle->filter.in, NULL, NULL, dns);
1866   filter_AdjustAddr(&bundle->filter.out, NULL, NULL, dns);
1867   filter_AdjustAddr(&bundle->filter.dial, NULL, NULL, dns);
1868   filter_AdjustAddr(&bundle->filter.alive, NULL, NULL, dns);
1869 }
1870 
1871 void
bundle_CalculateBandwidth(struct bundle * bundle)1872 bundle_CalculateBandwidth(struct bundle *bundle)
1873 {
1874   struct datalink *dl;
1875   int sp, overhead, maxoverhead;
1876 
1877   bundle->bandwidth = 0;
1878   bundle->iface->mtu = 0;
1879   maxoverhead = 0;
1880 
1881   for (dl = bundle->links; dl; dl = dl->next) {
1882     overhead = ccp_MTUOverhead(&dl->physical->link.ccp);
1883     if (maxoverhead < overhead)
1884       maxoverhead = overhead;
1885     if (dl->state == DATALINK_OPEN) {
1886       if ((sp = dl->mp.bandwidth) == 0 &&
1887           (sp = physical_GetSpeed(dl->physical)) == 0)
1888         log_Printf(LogDEBUG, "%s: %s: Cannot determine bandwidth\n",
1889                    dl->name, dl->physical->name.full);
1890       else
1891         bundle->bandwidth += sp;
1892       if (!bundle->ncp.mp.active) {
1893         bundle->iface->mtu = dl->physical->link.lcp.his_mru;
1894         break;
1895       }
1896     }
1897   }
1898 
1899   if (bundle->bandwidth == 0)
1900     bundle->bandwidth = 115200;		/* Shrug */
1901 
1902   if (bundle->ncp.mp.active) {
1903     bundle->iface->mtu = bundle->ncp.mp.peer_mrru;
1904     overhead = ccp_MTUOverhead(&bundle->ncp.mp.link.ccp);
1905     if (maxoverhead < overhead)
1906       maxoverhead = overhead;
1907   } else if (!bundle->iface->mtu)
1908     bundle->iface->mtu = DEF_MRU;
1909 
1910 #ifndef NORADIUS
1911   if (bundle->radius.valid && bundle->radius.mtu &&
1912       bundle->radius.mtu < bundle->iface->mtu) {
1913     log_Printf(LogLCP, "Reducing MTU to radius value %lu\n",
1914                bundle->radius.mtu);
1915     bundle->iface->mtu = bundle->radius.mtu;
1916   }
1917 #endif
1918 
1919   if (maxoverhead) {
1920     log_Printf(LogLCP, "Reducing MTU from %lu to %lu (CCP requirement)\n",
1921                bundle->iface->mtu, bundle->iface->mtu - maxoverhead);
1922     bundle->iface->mtu -= maxoverhead;
1923   }
1924 
1925   tun_configure(bundle);
1926 
1927   route_UpdateMTU(bundle);
1928 }
1929 
1930 void
bundle_AutoAdjust(struct bundle * bundle,int percent,int what)1931 bundle_AutoAdjust(struct bundle *bundle, int percent, int what)
1932 {
1933   struct datalink *dl, *choice, *otherlinkup;
1934 
1935   choice = otherlinkup = NULL;
1936   for (dl = bundle->links; dl; dl = dl->next)
1937     if (dl->physical->type == PHYS_AUTO) {
1938       if (dl->state == DATALINK_OPEN) {
1939         if (what == AUTO_DOWN) {
1940           if (choice)
1941             otherlinkup = choice;
1942           choice = dl;
1943         }
1944       } else if (dl->state == DATALINK_CLOSED) {
1945         if (what == AUTO_UP) {
1946           choice = dl;
1947           break;
1948         }
1949       } else {
1950         /* An auto link in an intermediate state - forget it for the moment */
1951         choice = NULL;
1952         break;
1953       }
1954     } else if (dl->state == DATALINK_OPEN && what == AUTO_DOWN)
1955       otherlinkup = dl;
1956 
1957   if (choice) {
1958     if (what == AUTO_UP) {
1959       log_Printf(LogPHASE, "%d%% saturation -> Opening link ``%s''\n",
1960                  percent, choice->name);
1961       datalink_Up(choice, 1, 1);
1962       mp_CheckAutoloadTimer(&bundle->ncp.mp);
1963     } else if (otherlinkup) {	/* Only bring the second-last link down */
1964       log_Printf(LogPHASE, "%d%% saturation -> Closing link ``%s''\n",
1965                  percent, choice->name);
1966       datalink_Close(choice, CLOSE_STAYDOWN);
1967       mp_CheckAutoloadTimer(&bundle->ncp.mp);
1968     }
1969   }
1970 }
1971 
1972 int
bundle_WantAutoloadTimer(struct bundle * bundle)1973 bundle_WantAutoloadTimer(struct bundle *bundle)
1974 {
1975   struct datalink *dl;
1976   int autolink, opened;
1977 
1978   if (bundle->phase == PHASE_NETWORK) {
1979     for (autolink = opened = 0, dl = bundle->links; dl; dl = dl->next)
1980       if (dl->physical->type == PHYS_AUTO) {
1981         if (++autolink == 2 || (autolink == 1 && opened))
1982           /* Two auto links or one auto and one open in NETWORK phase */
1983           return 1;
1984       } else if (dl->state == DATALINK_OPEN) {
1985         opened++;
1986         if (autolink)
1987           /* One auto and one open link in NETWORK phase */
1988           return 1;
1989       }
1990   }
1991 
1992   return 0;
1993 }
1994 
1995 void
bundle_ChangedPID(struct bundle * bundle)1996 bundle_ChangedPID(struct bundle *bundle)
1997 {
1998 #ifdef TUNSIFPID
1999   ioctl(bundle->dev.fd, TUNSIFPID, 0);
2000 #endif
2001 }
2002 
2003 int
bundle_Uptime(struct bundle * bundle)2004 bundle_Uptime(struct bundle *bundle)
2005 {
2006   if (bundle->upat)
2007     return time(NULL) - bundle->upat;
2008 
2009   return 0;
2010 }
2011