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