nlookup.9 - document nlookup_init_root
[dragonfly.git] / usr.sbin / ppp / bundle.c
blob8717e5c566a6114a04d115af08cd0b89e6795d3d
1 /*-
2 * Copyright (c) 1998 Brian Somers <brian@Awfulhak.org>
3 * All rights reserved.
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.
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.
26 * $FreeBSD: src/usr.sbin/ppp/bundle.c,v 1.84.2.12 2002/09/01 02:12:22 brian Exp $
27 * $DragonFly: src/usr.sbin/ppp/bundle.c,v 1.5 2005/11/24 23:42:54 swildner Exp $
30 #include <sys/param.h>
31 #include <sys/socket.h>
32 #include <netinet/in.h>
33 #include <net/if.h>
34 #include <net/tun/if_tun.h> /* For TUNS* ioctls */
35 #include <net/route.h>
36 #include <netinet/in_systm.h>
37 #include <netinet/ip.h>
38 #include <sys/un.h>
40 #include <errno.h>
41 #include <fcntl.h>
42 #ifdef __OpenBSD__
43 #include <util.h>
44 #else
45 #include <libutil.h>
46 #endif
47 #include <paths.h>
48 #include <stdarg.h>
49 #include <stdio.h>
50 #include <stdlib.h>
51 #include <string.h>
52 #include <sys/uio.h>
53 #include <sys/wait.h>
54 #include <termios.h>
55 #include <unistd.h>
57 #include "layer.h"
58 #include "defs.h"
59 #include "command.h"
60 #include "mbuf.h"
61 #include "log.h"
62 #include "id.h"
63 #include "timer.h"
64 #include "fsm.h"
65 #include "iplist.h"
66 #include "lqr.h"
67 #include "hdlc.h"
68 #include "throughput.h"
69 #include "slcompress.h"
70 #include "ncpaddr.h"
71 #include "ip.h"
72 #include "ipcp.h"
73 #include "filter.h"
74 #include "descriptor.h"
75 #include "route.h"
76 #include "lcp.h"
77 #include "ccp.h"
78 #include "link.h"
79 #include "mp.h"
80 #ifndef NORADIUS
81 #include "radius.h"
82 #endif
83 #include "ipv6cp.h"
84 #include "ncp.h"
85 #include "bundle.h"
86 #include "async.h"
87 #include "physical.h"
88 #include "auth.h"
89 #include "proto.h"
90 #include "chap.h"
91 #include "tun.h"
92 #include "prompt.h"
93 #include "chat.h"
94 #include "cbcp.h"
95 #include "datalink.h"
96 #include "iface.h"
97 #include "server.h"
98 #include "probe.h"
99 #ifndef NODES
100 #include "mppe.h"
101 #endif
103 #define SCATTER_SEGMENTS 7 /* version, datalink, name, physical,
104 throughput, throughput, device */
106 #define SEND_MAXFD 3 /* Max file descriptors passed through
107 the local domain socket */
109 static int bundle_RemainingIdleTime(struct bundle *);
111 static const char * const PhaseNames[] = {
112 "Dead", "Establish", "Authenticate", "Network", "Terminate"
115 const char *
116 bundle_PhaseName(struct bundle *bundle)
118 return bundle->phase <= PHASE_TERMINATE ?
119 PhaseNames[bundle->phase] : "unknown";
122 void
123 bundle_NewPhase(struct bundle *bundle, u_int new)
125 if (new == bundle->phase)
126 return;
128 if (new <= PHASE_TERMINATE)
129 log_Printf(LogPHASE, "bundle: %s\n", PhaseNames[new]);
131 switch (new) {
132 case PHASE_DEAD:
133 bundle->phase = new;
134 #ifndef NODES
135 MPPE_MasterKeyValid = 0;
136 #endif
137 log_DisplayPrompts();
138 break;
140 case PHASE_ESTABLISH:
141 bundle->phase = new;
142 break;
144 case PHASE_AUTHENTICATE:
145 bundle->phase = new;
146 log_DisplayPrompts();
147 break;
149 case PHASE_NETWORK:
150 if (ncp_fsmStart(&bundle->ncp, bundle)) {
151 bundle->phase = new;
152 log_DisplayPrompts();
153 } else {
154 log_Printf(LogPHASE, "bundle: All NCPs are disabled\n");
155 bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
157 break;
159 case PHASE_TERMINATE:
160 bundle->phase = new;
161 mp_Down(&bundle->ncp.mp);
162 log_DisplayPrompts();
163 break;
167 static void
168 bundle_LayerStart(void *v, struct fsm *fp)
170 /* The given FSM is about to start up ! */
174 void
175 bundle_Notify(struct bundle *bundle, char c)
177 if (bundle->notify.fd != -1) {
178 int ret;
180 ret = write(bundle->notify.fd, &c, 1);
181 if (c != EX_REDIAL && c != EX_RECONNECT) {
182 if (ret == 1)
183 log_Printf(LogCHAT, "Parent notified of %s\n",
184 c == EX_NORMAL ? "success" : "failure");
185 else
186 log_Printf(LogERROR, "Failed to notify parent of success\n");
187 close(bundle->notify.fd);
188 bundle->notify.fd = -1;
189 } else if (ret == 1)
190 log_Printf(LogCHAT, "Parent notified of %s\n", ex_desc(c));
191 else
192 log_Printf(LogERROR, "Failed to notify parent of %s\n", ex_desc(c));
196 static void
197 bundle_ClearQueues(void *v)
199 struct bundle *bundle = (struct bundle *)v;
200 struct datalink *dl;
202 log_Printf(LogPHASE, "Clearing choked output queue\n");
203 timer_Stop(&bundle->choked.timer);
206 * Emergency time:
208 * We've had a full queue for PACKET_DEL_SECS seconds without being
209 * able to get rid of any of the packets. We've probably given up
210 * on the redials at this point, and the queued data has almost
211 * definitely been timed out by the layer above. As this is preventing
212 * us from reading the TUN_NAME device (we don't want to buffer stuff
213 * indefinitely), we may as well nuke this data and start with a clean
214 * slate !
216 * Unfortunately, this has the side effect of shafting any compression
217 * dictionaries in use (causing the relevant RESET_REQ/RESET_ACK).
220 ncp_DeleteQueues(&bundle->ncp);
221 for (dl = bundle->links; dl; dl = dl->next)
222 physical_DeleteQueue(dl->physical);
225 static void
226 bundle_LinkAdded(struct bundle *bundle, struct datalink *dl)
228 bundle->phys_type.all |= dl->physical->type;
229 if (dl->state == DATALINK_OPEN)
230 bundle->phys_type.open |= dl->physical->type;
232 #ifndef NORADIUS
233 if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
234 != bundle->phys_type.open && bundle->session.timer.state == TIMER_STOPPED)
235 if (bundle->radius.sessiontime)
236 bundle_StartSessionTimer(bundle, 0);
237 #endif
239 if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
240 != bundle->phys_type.open && bundle->idle.timer.state == TIMER_STOPPED)
241 /* We may need to start our idle timer */
242 bundle_StartIdleTimer(bundle, 0);
245 void
246 bundle_LinksRemoved(struct bundle *bundle)
248 struct datalink *dl;
250 bundle->phys_type.all = bundle->phys_type.open = 0;
251 for (dl = bundle->links; dl; dl = dl->next)
252 bundle_LinkAdded(bundle, dl);
254 bundle_CalculateBandwidth(bundle);
255 mp_CheckAutoloadTimer(&bundle->ncp.mp);
257 if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
258 == bundle->phys_type.open) {
259 #ifndef NORADIUS
260 if (bundle->radius.sessiontime)
261 bundle_StopSessionTimer(bundle);
262 #endif
263 bundle_StopIdleTimer(bundle);
267 static void
268 bundle_LayerUp(void *v, struct fsm *fp)
271 * The given fsm is now up
272 * If it's an LCP, adjust our phys_mode.open value and check the
273 * autoload timer.
274 * If it's the first NCP, calculate our bandwidth
275 * If it's the first NCP, set our ``upat'' time
276 * If it's the first NCP, start the idle timer.
277 * If it's an NCP, tell our -background parent to go away.
278 * If it's the first NCP, start the autoload timer
280 struct bundle *bundle = (struct bundle *)v;
282 if (fp->proto == PROTO_LCP) {
283 struct physical *p = link2physical(fp->link);
285 bundle_LinkAdded(bundle, p->dl);
286 mp_CheckAutoloadTimer(&bundle->ncp.mp);
287 } else if (isncp(fp->proto)) {
288 if (ncp_LayersOpen(&fp->bundle->ncp) == 1) {
289 bundle_CalculateBandwidth(fp->bundle);
290 time(&bundle->upat);
291 #ifndef NORADIUS
292 if (bundle->radius.sessiontime)
293 bundle_StartSessionTimer(bundle, 0);
294 #endif
295 bundle_StartIdleTimer(bundle, 0);
296 mp_CheckAutoloadTimer(&fp->bundle->ncp.mp);
298 bundle_Notify(bundle, EX_NORMAL);
299 } else if (fp->proto == PROTO_CCP)
300 bundle_CalculateBandwidth(fp->bundle); /* Against ccp_MTUOverhead */
303 static void
304 bundle_LayerDown(void *v, struct fsm *fp)
307 * The given FSM has been told to come down.
308 * If it's our last NCP, stop the idle timer.
309 * If it's our last NCP, clear our ``upat'' value.
310 * If it's our last NCP, stop the autoload timer
311 * If it's an LCP, adjust our phys_type.open value and any timers.
312 * If it's an LCP and we're in multilink mode, adjust our tun
313 * If it's the last LCP, down all NCPs
314 * speed and make sure our minimum sequence number is adjusted.
317 struct bundle *bundle = (struct bundle *)v;
319 if (isncp(fp->proto)) {
320 if (ncp_LayersOpen(&fp->bundle->ncp) == 0) {
321 #ifndef NORADIUS
322 if (bundle->radius.sessiontime)
323 bundle_StopSessionTimer(bundle);
324 #endif
325 bundle_StopIdleTimer(bundle);
326 bundle->upat = 0;
327 mp_StopAutoloadTimer(&bundle->ncp.mp);
329 } else if (fp->proto == PROTO_LCP) {
330 struct datalink *dl;
331 struct datalink *lost;
332 int others_active;
334 bundle_LinksRemoved(bundle); /* adjust timers & phys_type values */
336 lost = NULL;
337 others_active = 0;
338 for (dl = bundle->links; dl; dl = dl->next) {
339 if (fp == &dl->physical->link.lcp.fsm)
340 lost = dl;
341 else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
342 others_active++;
345 if (bundle->ncp.mp.active) {
346 bundle_CalculateBandwidth(bundle);
348 if (lost)
349 mp_LinkLost(&bundle->ncp.mp, lost);
350 else
351 log_Printf(LogALERT, "Oops, lost an unrecognised datalink (%s) !\n",
352 fp->link->name);
355 if (!others_active) {
356 /* Down the NCPs. We don't expect to get fsm_Close()d ourself ! */
357 ncp2initial(&bundle->ncp);
358 mp_Down(&bundle->ncp.mp);
363 static void
364 bundle_LayerFinish(void *v, struct fsm *fp)
366 /* The given fsm is now down (fp cannot be NULL)
368 * If it's the last NCP, fsm_Close all LCPs
369 * If it's the last NCP, bring any MP layer down
372 struct bundle *bundle = (struct bundle *)v;
373 struct datalink *dl;
375 if (isncp(fp->proto) && !ncp_LayersUnfinished(&bundle->ncp)) {
376 if (bundle_Phase(bundle) != PHASE_DEAD)
377 bundle_NewPhase(bundle, PHASE_TERMINATE);
378 for (dl = bundle->links; dl; dl = dl->next)
379 if (dl->state == DATALINK_OPEN)
380 datalink_Close(dl, CLOSE_STAYDOWN);
381 fsm2initial(fp);
382 mp_Down(&bundle->ncp.mp);
386 void
387 bundle_Close(struct bundle *bundle, const char *name, int how)
390 * Please close the given datalink.
391 * If name == NULL or name is the last datalink, fsm_Close all NCPs
392 * (except our MP)
393 * If it isn't the last datalink, just Close that datalink.
396 struct datalink *dl, *this_dl;
397 int others_active;
399 others_active = 0;
400 this_dl = NULL;
402 for (dl = bundle->links; dl; dl = dl->next) {
403 if (name && !strcasecmp(name, dl->name))
404 this_dl = dl;
405 if (name == NULL || this_dl == dl) {
406 switch (how) {
407 case CLOSE_LCP:
408 datalink_DontHangup(dl);
409 break;
410 case CLOSE_STAYDOWN:
411 datalink_StayDown(dl);
412 break;
414 } else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
415 others_active++;
418 if (name && this_dl == NULL) {
419 log_Printf(LogWARN, "%s: Invalid datalink name\n", name);
420 return;
423 if (!others_active) {
424 #ifndef NORADIUS
425 if (bundle->radius.sessiontime)
426 bundle_StopSessionTimer(bundle);
427 #endif
428 bundle_StopIdleTimer(bundle);
429 if (ncp_LayersUnfinished(&bundle->ncp))
430 ncp_Close(&bundle->ncp);
431 else {
432 ncp2initial(&bundle->ncp);
433 mp_Down(&bundle->ncp.mp);
434 for (dl = bundle->links; dl; dl = dl->next)
435 datalink_Close(dl, how);
437 } else if (this_dl && this_dl->state != DATALINK_CLOSED &&
438 this_dl->state != DATALINK_HANGUP)
439 datalink_Close(this_dl, how);
442 void
443 bundle_Down(struct bundle *bundle, int how)
445 struct datalink *dl;
447 for (dl = bundle->links; dl; dl = dl->next)
448 datalink_Down(dl, how);
451 static int
452 bundle_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
454 struct bundle *bundle = descriptor2bundle(d);
455 struct datalink *dl;
456 int result, nlinks;
457 u_short ifqueue;
458 size_t queued;
460 result = 0;
462 /* If there are aren't many packets queued, look for some more. */
463 for (nlinks = 0, dl = bundle->links; dl; dl = dl->next)
464 nlinks++;
466 if (nlinks) {
467 queued = r ? ncp_FillPhysicalQueues(&bundle->ncp, bundle) :
468 ncp_QueueLen(&bundle->ncp);
470 if (r && (bundle->phase == PHASE_NETWORK ||
471 bundle->phys_type.all & PHYS_AUTO)) {
472 /* enough surplus so that we can tell if we're getting swamped */
473 ifqueue = nlinks > bundle->cfg.ifqueue ? nlinks : bundle->cfg.ifqueue;
474 if (queued < ifqueue) {
475 /* Not enough - select() for more */
476 if (bundle->choked.timer.state == TIMER_RUNNING)
477 timer_Stop(&bundle->choked.timer); /* Not needed any more */
478 FD_SET(bundle->dev.fd, r);
479 if (*n < bundle->dev.fd + 1)
480 *n = bundle->dev.fd + 1;
481 log_Printf(LogTIMER, "%s: fdset(r) %d\n", TUN_NAME, bundle->dev.fd);
482 result++;
483 } else if (bundle->choked.timer.state == TIMER_STOPPED) {
484 bundle->choked.timer.func = bundle_ClearQueues;
485 bundle->choked.timer.name = "output choke";
486 bundle->choked.timer.load = bundle->cfg.choked.timeout * SECTICKS;
487 bundle->choked.timer.arg = bundle;
488 timer_Start(&bundle->choked.timer);
493 #ifndef NORADIUS
494 result += descriptor_UpdateSet(&bundle->radius.desc, r, w, e, n);
495 #endif
497 /* Which links need a select() ? */
498 for (dl = bundle->links; dl; dl = dl->next)
499 result += descriptor_UpdateSet(&dl->desc, r, w, e, n);
502 * This *MUST* be called after the datalink UpdateSet()s as it
503 * might be ``holding'' one of the datalinks (death-row) and
504 * wants to be able to de-select() it from the descriptor set.
506 result += descriptor_UpdateSet(&bundle->ncp.mp.server.desc, r, w, e, n);
508 return result;
511 static int
512 bundle_IsSet(struct fdescriptor *d, const fd_set *fdset)
514 struct bundle *bundle = descriptor2bundle(d);
515 struct datalink *dl;
517 for (dl = bundle->links; dl; dl = dl->next)
518 if (descriptor_IsSet(&dl->desc, fdset))
519 return 1;
521 #ifndef NORADIUS
522 if (descriptor_IsSet(&bundle->radius.desc, fdset))
523 return 1;
524 #endif
526 if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
527 return 1;
529 return FD_ISSET(bundle->dev.fd, fdset);
532 static void
533 bundle_DescriptorRead(struct fdescriptor *d, struct bundle *bundle,
534 const fd_set *fdset)
536 struct datalink *dl;
537 unsigned secs;
538 u_int32_t af;
540 if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
541 descriptor_Read(&bundle->ncp.mp.server.desc, bundle, fdset);
543 for (dl = bundle->links; dl; dl = dl->next)
544 if (descriptor_IsSet(&dl->desc, fdset))
545 descriptor_Read(&dl->desc, bundle, fdset);
547 #ifndef NORADIUS
548 if (descriptor_IsSet(&bundle->radius.desc, fdset))
549 descriptor_Read(&bundle->radius.desc, bundle, fdset);
550 #endif
552 if (FD_ISSET(bundle->dev.fd, fdset)) {
553 struct tun_data tun;
554 int n, pri;
555 u_char *data;
556 size_t sz;
558 if (bundle->dev.header) {
559 data = (u_char *)&tun;
560 sz = sizeof tun;
561 } else {
562 data = tun.data;
563 sz = sizeof tun.data;
566 /* something to read from tun */
568 n = read(bundle->dev.fd, data, sz);
569 if (n < 0) {
570 log_Printf(LogWARN, "%s: read: %s\n", bundle->dev.Name, strerror(errno));
571 return;
574 if (bundle->dev.header) {
575 n -= sz - sizeof tun.data;
576 if (n <= 0) {
577 log_Printf(LogERROR, "%s: read: Got only %d bytes of data !\n",
578 bundle->dev.Name, n);
579 return;
581 af = ntohl(tun.header.family);
582 #ifndef NOINET6
583 if (af != AF_INET && af != AF_INET6)
584 #else
585 if (af != AF_INET)
586 #endif
587 /* XXX: Should be maintaining drop/family counts ! */
588 return;
589 } else
590 af = AF_INET;
592 if (af == AF_INET && ((struct ip *)tun.data)->ip_dst.s_addr ==
593 bundle->ncp.ipcp.my_ip.s_addr) {
594 /* we've been asked to send something addressed *to* us :( */
595 if (Enabled(bundle, OPT_LOOPBACK)) {
596 pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.in,
597 NULL, NULL);
598 if (pri >= 0) {
599 n += sz - sizeof tun.data;
600 write(bundle->dev.fd, data, n);
601 log_Printf(LogDEBUG, "Looped back packet addressed to myself\n");
603 return;
604 } else
605 log_Printf(LogDEBUG, "Oops - forwarding packet addressed to myself\n");
609 * Process on-demand dialup. Output packets are queued within the tunnel
610 * device until the appropriate NCP is opened.
613 if (bundle_Phase(bundle) == PHASE_DEAD) {
615 * Note, we must be in AUTO mode :-/ otherwise our interface should
616 * *not* be UP and we can't receive data
618 pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.dial,
619 NULL, NULL);
620 if (pri >= 0)
621 bundle_Open(bundle, NULL, PHYS_AUTO, 0);
622 else
624 * Drop the packet. If we were to queue it, we'd just end up with
625 * a pile of timed-out data in our output queue by the time we get
626 * around to actually dialing. We'd also prematurely reach the
627 * threshold at which we stop select()ing to read() the tun
628 * device - breaking auto-dial.
630 return;
633 secs = 0;
634 pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.out,
635 NULL, &secs);
636 if (pri >= 0) {
637 /* Prepend the number of seconds timeout given in the filter */
638 tun.header.timeout = secs;
639 ncp_Enqueue(&bundle->ncp, af, pri, (char *)&tun, n + sizeof tun.header);
644 static int
645 bundle_DescriptorWrite(struct fdescriptor *d, struct bundle *bundle,
646 const fd_set *fdset)
648 struct datalink *dl;
649 int result = 0;
651 /* This is not actually necessary as struct mpserver doesn't Write() */
652 if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
653 if (descriptor_Write(&bundle->ncp.mp.server.desc, bundle, fdset) == 1)
654 result++;
656 for (dl = bundle->links; dl; dl = dl->next)
657 if (descriptor_IsSet(&dl->desc, fdset))
658 switch (descriptor_Write(&dl->desc, bundle, fdset)) {
659 case -1:
660 datalink_ComeDown(dl, CLOSE_NORMAL);
661 break;
662 case 1:
663 result++;
666 return result;
669 void
670 bundle_LockTun(struct bundle *bundle)
672 FILE *lockfile;
673 char pidfile[PATH_MAX];
675 snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
676 lockfile = ID0fopen(pidfile, "w");
677 if (lockfile != NULL) {
678 fprintf(lockfile, "%d\n", (int)getpid());
679 fclose(lockfile);
680 } else
681 log_Printf(LogERROR, "Warning: Can't create %s: %s\n",
682 pidfile, strerror(errno));
685 static void
686 bundle_UnlockTun(struct bundle *bundle)
688 char pidfile[PATH_MAX];
690 snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
691 ID0unlink(pidfile);
694 struct bundle *
695 bundle_Create(const char *prefix, int type, int unit)
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
707 if (bundle.iface != NULL) { /* Already allocated ! */
708 log_Printf(LogALERT, "bundle_Create: There's only one BUNDLE !\n");
709 return NULL;
712 if (unit == -1) {
713 minunit = 0;
714 maxunit = -1;
715 } else {
716 minunit = unit;
717 maxunit = unit + 1;
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++) {
734 * Attempt to load the tunnel interface KLD if it isn't loaded
735 * already.
737 if (loadmodules(LOAD_VERBOSLY, "if_tun", NULL))
738 bundle.unit--;
739 continue;
741 #endif
742 if (errno != ENOENT || ++enoentcount > 2) {
743 err = errno;
744 break;
746 } else
747 err = errno;
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;
759 log_SetTun(bundle.unit);
761 ifname = strrchr(bundle.dev.Name, '/');
762 if (ifname == NULL)
763 ifname = bundle.dev.Name;
764 else
765 ifname++;
767 bundle.iface = iface_Create(ifname);
768 if (bundle.iface == NULL) {
769 close(bundle.dev.fd);
770 return NULL;
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
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
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
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 !).
808 bundle.dev.header = 0;
809 #endif
810 #endif
812 log_Printf(LogPHASE, "Using interface: %s\n", ifname);
814 bundle.bandwidth = 0;
815 bundle.routing_seq = 0;
816 bundle.phase = PHASE_DEAD;
817 bundle.CleaningUp = 0;
818 bundle.NatEnabled = 0;
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;
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;
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;
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;
859 ncp_Init(&bundle.ncp, &bundle);
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;
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;
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
887 /* Clean out any leftover crud */
888 iface_Clear(bundle.iface, &bundle.ncp, 0, IFACE_CLEAR_ALL);
890 bundle_LockTun(&bundle);
892 return &bundle;
895 static void
896 bundle_DownInterface(struct bundle *bundle)
898 route_IfDelete(bundle, 1);
899 iface_ClearFlags(bundle->iface->name, IFF_UP);
902 void
903 bundle_Destroy(struct bundle *bundle)
905 struct datalink *dl;
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.
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);
918 #ifndef NORADIUS
919 /* Tell the radius server the bad news */
920 radius_Destroy(&bundle->radius);
921 #endif
923 /* Again, these are all DATALINK_CLOSED unless we're abending */
924 dl = bundle->links;
925 while (dl)
926 dl = datalink_Destroy(dl);
928 ncp_Destroy(&bundle->ncp);
930 close(bundle->dev.fd);
931 bundle_UnlockTun(bundle);
933 /* In case we never made PHASE_NETWORK */
934 bundle_Notify(bundle, EX_ERRDEAD);
936 iface_Destroy(bundle->iface);
937 bundle->iface = NULL;
940 void
941 bundle_LinkClosed(struct bundle *bundle, struct datalink *dl)
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.
949 * NOTE: dl may not be in our list (bundle_SendDatalink()) !
952 struct datalink *odl;
953 int other_links;
955 log_SetTtyCommandMode(dl);
957 other_links = 0;
958 for (odl = bundle->links; odl; odl = odl->next)
959 if (odl != dl && odl->state != DATALINK_CLOSED)
960 other_links++;
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);
976 void
977 bundle_Open(struct bundle *bundle, const char *name, int mask, int force)
980 * Please open the given datalink, or all if name == NULL
982 struct datalink *dl;
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 */
996 if (name != NULL)
997 break;
1001 struct datalink *
1002 bundle2datalink(struct bundle *bundle, const char *name)
1004 struct datalink *dl;
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;
1013 return NULL;
1017 bundle_ShowLinks(struct cmdargs const *arg)
1019 struct datalink *dl;
1020 struct pppThroughput *t;
1021 unsigned long long octets;
1022 int secs;
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);
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");
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);
1047 return 0;
1050 static const char *
1051 optval(struct bundle *bundle, int bit)
1053 return (bundle->cfg.opt & bit) ? "enabled" : "disabled";
1057 bundle_ShowStatus(struct cmdargs const *arg)
1059 int remaining;
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);
1066 if (arg->bundle->upat) {
1067 int secs = bundle_Uptime(arg->bundle);
1069 prompt_Printf(arg->prompt, ", up time %d:%02d:%02d", secs / 3600,
1070 (secs / 60) % 60, secs % 60);
1072 prompt_Printf(arg->prompt, "\n Queued: %lu of %u\n",
1073 (unsigned long)ncp_QueueLen(&arg->bundle->ncp),
1074 arg->bundle->cfg.ifqueue);
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");
1093 prompt_Printf(arg->prompt, " Choked Timer: %ds\n",
1094 arg->bundle->cfg.choked.timeout);
1096 #ifndef NORADIUS
1097 radius_Show(&arg->bundle->radius, arg->prompt);
1098 #endif
1100 prompt_Printf(arg->prompt, " Idle Timer: ");
1101 if (arg->bundle->cfg.idle.timeout) {
1102 prompt_Printf(arg->prompt, "%ds", arg->bundle->cfg.idle.timeout);
1103 if (arg->bundle->cfg.idle.min_timeout)
1104 prompt_Printf(arg->prompt, ", min %ds",
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");
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));
1144 return 0;
1147 static void
1148 bundle_IdleTimeout(void *v)
1150 struct bundle *bundle = (struct bundle *)v;
1152 log_Printf(LogPHASE, "Idle timer expired\n");
1153 bundle_StopIdleTimer(bundle);
1154 bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
1158 * Start Idle timer. If timeout is reached, we call bundle_Close() to
1159 * close LCP and link.
1161 void
1162 bundle_StartIdleTimer(struct bundle *bundle, unsigned secs)
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);
1169 if (secs == 0)
1170 secs = bundle->cfg.idle.timeout;
1172 /* We want at least `secs' */
1173 if (bundle->cfg.idle.min_timeout > secs && bundle->upat) {
1174 int up = now - bundle->upat;
1176 if ((long long)bundle->cfg.idle.min_timeout - up > (long long)secs)
1177 /* Only increase from the current `remaining' value */
1178 secs = bundle->cfg.idle.min_timeout - up;
1180 bundle->idle.timer.func = bundle_IdleTimeout;
1181 bundle->idle.timer.name = "idle";
1182 bundle->idle.timer.load = secs * SECTICKS;
1183 bundle->idle.timer.arg = bundle;
1184 timer_Start(&bundle->idle.timer);
1185 bundle->idle.done = now + secs;
1189 void
1190 bundle_SetIdleTimer(struct bundle *bundle, int timeout, int min_timeout)
1192 bundle->cfg.idle.timeout = timeout;
1193 if (min_timeout >= 0)
1194 bundle->cfg.idle.min_timeout = min_timeout;
1195 if (ncp_LayersOpen(&bundle->ncp))
1196 bundle_StartIdleTimer(bundle, 0);
1199 void
1200 bundle_StopIdleTimer(struct bundle *bundle)
1202 timer_Stop(&bundle->idle.timer);
1203 bundle->idle.done = 0;
1206 static int
1207 bundle_RemainingIdleTime(struct bundle *bundle)
1209 if (bundle->idle.done)
1210 return bundle->idle.done - time(NULL);
1211 return -1;
1214 #ifndef NORADIUS
1216 static void
1217 bundle_SessionTimeout(void *v)
1219 struct bundle *bundle = (struct bundle *)v;
1221 log_Printf(LogPHASE, "Session-Timeout timer expired\n");
1222 bundle_StopSessionTimer(bundle);
1223 bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
1226 void
1227 bundle_StartSessionTimer(struct bundle *bundle, unsigned secs)
1229 timer_Stop(&bundle->session.timer);
1230 if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) !=
1231 bundle->phys_type.open && bundle->radius.sessiontime) {
1232 time_t now = time(NULL);
1234 if (secs == 0)
1235 secs = bundle->radius.sessiontime;
1237 bundle->session.timer.func = bundle_SessionTimeout;
1238 bundle->session.timer.name = "session";
1239 bundle->session.timer.load = secs * SECTICKS;
1240 bundle->session.timer.arg = bundle;
1241 timer_Start(&bundle->session.timer);
1242 bundle->session.done = now + secs;
1246 void
1247 bundle_StopSessionTimer(struct bundle *bundle)
1249 timer_Stop(&bundle->session.timer);
1250 bundle->session.done = 0;
1253 #endif
1256 bundle_IsDead(struct bundle *bundle)
1258 return !bundle->links || (bundle->phase == PHASE_DEAD && bundle->CleaningUp);
1261 static struct datalink *
1262 bundle_DatalinkLinkout(struct bundle *bundle, struct datalink *dl)
1264 struct datalink **dlp;
1266 for (dlp = &bundle->links; *dlp; dlp = &(*dlp)->next)
1267 if (*dlp == dl) {
1268 *dlp = dl->next;
1269 dl->next = NULL;
1270 bundle_LinksRemoved(bundle);
1271 return dl;
1274 return NULL;
1277 static void
1278 bundle_DatalinkLinkin(struct bundle *bundle, struct datalink *dl)
1280 struct datalink **dlp = &bundle->links;
1282 while (*dlp)
1283 dlp = &(*dlp)->next;
1285 *dlp = dl;
1286 dl->next = NULL;
1288 bundle_LinkAdded(bundle, dl);
1289 mp_CheckAutoloadTimer(&bundle->ncp.mp);
1292 void
1293 bundle_CleanDatalinks(struct bundle *bundle)
1295 struct datalink **dlp = &bundle->links;
1296 int found = 0;
1298 while (*dlp)
1299 if ((*dlp)->state == DATALINK_CLOSED &&
1300 (*dlp)->physical->type &
1301 (PHYS_DIRECT|PHYS_BACKGROUND|PHYS_FOREGROUND)) {
1302 *dlp = datalink_Destroy(*dlp);
1303 found++;
1304 } else
1305 dlp = &(*dlp)->next;
1307 if (found)
1308 bundle_LinksRemoved(bundle);
1312 bundle_DatalinkClone(struct bundle *bundle, struct datalink *dl,
1313 const char *name)
1315 if (bundle2datalink(bundle, name)) {
1316 log_Printf(LogWARN, "Clone: %s: name already exists\n", name);
1317 return 0;
1320 bundle_DatalinkLinkin(bundle, datalink_Clone(dl, name));
1321 return 1;
1324 void
1325 bundle_DatalinkRemove(struct bundle *bundle, struct datalink *dl)
1327 dl = bundle_DatalinkLinkout(bundle, dl);
1328 if (dl)
1329 datalink_Destroy(dl);
1332 void
1333 bundle_SetLabel(struct bundle *bundle, const char *label)
1335 if (label)
1336 strncpy(bundle->cfg.label, label, sizeof bundle->cfg.label - 1);
1337 else
1338 *bundle->cfg.label = '\0';
1341 const char *
1342 bundle_GetLabel(struct bundle *bundle)
1344 return *bundle->cfg.label ? bundle->cfg.label : NULL;
1348 bundle_LinkSize(void)
1350 struct iovec iov[SCATTER_SEGMENTS];
1351 int niov, expect, f;
1353 iov[0].iov_len = strlen(Version) + 1;
1354 iov[0].iov_base = NULL;
1355 niov = 1;
1356 if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1357 log_Printf(LogERROR, "Cannot determine space required for link\n");
1358 return 0;
1361 for (f = expect = 0; f < niov; f++)
1362 expect += iov[f].iov_len;
1364 return expect;
1367 void
1368 bundle_ReceiveDatalink(struct bundle *bundle, int s)
1370 char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int) * SEND_MAXFD];
1371 int niov, expect, f, *fd, nfd, onfd, got;
1372 struct iovec iov[SCATTER_SEGMENTS];
1373 struct cmsghdr *cmsg;
1374 struct msghdr msg;
1375 struct datalink *dl;
1376 pid_t pid;
1378 log_Printf(LogPHASE, "Receiving datalink\n");
1381 * Create our scatter/gather array - passing NULL gets the space
1382 * allocation requirement rather than actually flattening the
1383 * structures.
1385 iov[0].iov_len = strlen(Version) + 1;
1386 iov[0].iov_base = NULL;
1387 niov = 1;
1388 if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1389 log_Printf(LogERROR, "Cannot determine space required for link\n");
1390 return;
1393 /* Allocate the scatter/gather array for recvmsg() */
1394 for (f = expect = 0; f < niov; f++) {
1395 if ((iov[f].iov_base = malloc(iov[f].iov_len)) == NULL) {
1396 log_Printf(LogERROR, "Cannot allocate space to receive link\n");
1397 return;
1399 if (f)
1400 expect += iov[f].iov_len;
1403 /* Set up our message */
1404 cmsg = (struct cmsghdr *)cmsgbuf;
1405 cmsg->cmsg_len = sizeof cmsgbuf;
1406 cmsg->cmsg_level = SOL_SOCKET;
1407 cmsg->cmsg_type = 0;
1409 memset(&msg, '\0', sizeof msg);
1410 msg.msg_name = NULL;
1411 msg.msg_namelen = 0;
1412 msg.msg_iov = iov;
1413 msg.msg_iovlen = 1; /* Only send the version at the first pass */
1414 msg.msg_control = cmsgbuf;
1415 msg.msg_controllen = sizeof cmsgbuf;
1417 log_Printf(LogDEBUG, "Expecting %u scatter/gather bytes\n",
1418 (unsigned)iov[0].iov_len);
1420 if ((got = recvmsg(s, &msg, MSG_WAITALL)) != iov[0].iov_len) {
1421 if (got == -1)
1422 log_Printf(LogERROR, "Failed recvmsg: %s\n", strerror(errno));
1423 else
1424 log_Printf(LogERROR, "Failed recvmsg: Got %d, not %u\n",
1425 got, (unsigned)iov[0].iov_len);
1426 while (niov--)
1427 free(iov[niov].iov_base);
1428 return;
1431 if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) {
1432 log_Printf(LogERROR, "Recvmsg: no descriptors received !\n");
1433 while (niov--)
1434 free(iov[niov].iov_base);
1435 return;
1438 fd = (int *)CMSG_DATA(cmsg);
1439 nfd = ((caddr_t)cmsg + cmsg->cmsg_len - (caddr_t)fd) / sizeof(int);
1441 if (nfd < 2) {
1442 log_Printf(LogERROR, "Recvmsg: %d descriptor%s received (too few) !\n",
1443 nfd, nfd == 1 ? "" : "s");
1444 while (nfd--)
1445 close(fd[nfd]);
1446 while (niov--)
1447 free(iov[niov].iov_base);
1448 return;
1452 * We've successfully received two or more open file descriptors
1453 * through our socket, plus a version string. Make sure it's the
1454 * correct version, and drop the connection if it's not.
1456 if (strncmp(Version, iov[0].iov_base, iov[0].iov_len)) {
1457 log_Printf(LogWARN, "Cannot receive datalink, incorrect version"
1458 " (\"%.*s\", not \"%s\")\n", (int)iov[0].iov_len,
1459 (char *)iov[0].iov_base, Version);
1460 while (nfd--)
1461 close(fd[nfd]);
1462 while (niov--)
1463 free(iov[niov].iov_base);
1464 return;
1468 * Everything looks good. Send the other side our process id so that
1469 * they can transfer lock ownership, and wait for them to send the
1470 * actual link data.
1472 pid = getpid();
1473 if ((got = write(fd[1], &pid, sizeof pid)) != sizeof pid) {
1474 if (got == -1)
1475 log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1476 else
1477 log_Printf(LogERROR, "Failed write: Got %d, not %d\n", got,
1478 (int)(sizeof pid));
1479 while (nfd--)
1480 close(fd[nfd]);
1481 while (niov--)
1482 free(iov[niov].iov_base);
1483 return;
1486 if ((got = readv(fd[1], iov + 1, niov - 1)) != expect) {
1487 if (got == -1)
1488 log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1489 else
1490 log_Printf(LogERROR, "Failed write: Got %d, not %d\n", got, expect);
1491 while (nfd--)
1492 close(fd[nfd]);
1493 while (niov--)
1494 free(iov[niov].iov_base);
1495 return;
1497 close(fd[1]);
1499 onfd = nfd; /* We've got this many in our array */
1500 nfd -= 2; /* Don't include p->fd and our reply descriptor */
1501 niov = 1; /* Skip the version id */
1502 dl = iov2datalink(bundle, iov, &niov, sizeof iov / sizeof *iov, fd[0],
1503 fd + 2, &nfd);
1504 if (dl) {
1506 if (nfd) {
1507 log_Printf(LogERROR, "bundle_ReceiveDatalink: Failed to handle %d "
1508 "auxiliary file descriptors (%d remain)\n", onfd, nfd);
1509 datalink_Destroy(dl);
1510 while (nfd--)
1511 close(fd[onfd--]);
1512 close(fd[0]);
1513 } else {
1514 bundle_DatalinkLinkin(bundle, dl);
1515 datalink_AuthOk(dl);
1516 bundle_CalculateBandwidth(dl->bundle);
1518 } else {
1519 while (nfd--)
1520 close(fd[onfd--]);
1521 close(fd[0]);
1522 close(fd[1]);
1525 free(iov[0].iov_base);
1528 void
1529 bundle_SendDatalink(struct datalink *dl, int s, struct sockaddr_un *sun)
1531 char cmsgbuf[CMSG_SPACE(sizeof(int) * SEND_MAXFD)];
1532 const char *constlock;
1533 char *lock;
1534 struct cmsghdr *cmsg;
1535 struct msghdr msg;
1536 struct iovec iov[SCATTER_SEGMENTS];
1537 int niov, f, expect, newsid, fd[SEND_MAXFD], nfd, reply[2], got;
1538 pid_t newpid;
1540 log_Printf(LogPHASE, "Transmitting datalink %s\n", dl->name);
1542 /* Record the base device name for a lock transfer later */
1543 constlock = physical_LockedDevice(dl->physical);
1544 if (constlock) {
1545 lock = alloca(strlen(constlock) + 1);
1546 strcpy(lock, constlock);
1547 } else
1548 lock = NULL;
1550 bundle_LinkClosed(dl->bundle, dl);
1551 bundle_DatalinkLinkout(dl->bundle, dl);
1553 /* Build our scatter/gather array */
1554 iov[0].iov_len = strlen(Version) + 1;
1555 iov[0].iov_base = strdup(Version);
1556 niov = 1;
1557 nfd = 0;
1559 fd[0] = datalink2iov(dl, iov, &niov, SCATTER_SEGMENTS, fd + 2, &nfd);
1561 if (fd[0] != -1 && socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, reply) != -1) {
1563 * fd[1] is used to get the peer process id back, then to confirm that
1564 * we've transferred any device locks to that process id.
1566 fd[1] = reply[1];
1568 nfd += 2; /* Include fd[0] and fd[1] */
1569 memset(&msg, '\0', sizeof msg);
1571 msg.msg_name = NULL;
1572 msg.msg_namelen = 0;
1574 * Only send the version to start... We used to send the whole lot, but
1575 * this caused problems with our RECVBUF size as a single link is about
1576 * 22k ! This way, we should bump into no limits.
1578 msg.msg_iovlen = 1;
1579 msg.msg_iov = iov;
1580 msg.msg_control = cmsgbuf;
1581 msg.msg_controllen = CMSG_SPACE(sizeof(int) * nfd);
1582 msg.msg_flags = 0;
1584 cmsg = (struct cmsghdr *)cmsgbuf;
1585 cmsg->cmsg_len = msg.msg_controllen;
1586 cmsg->cmsg_level = SOL_SOCKET;
1587 cmsg->cmsg_type = SCM_RIGHTS;
1589 for (f = 0; f < nfd; f++)
1590 *((int *)CMSG_DATA(cmsg) + f) = fd[f];
1592 for (f = 1, expect = 0; f < niov; f++)
1593 expect += iov[f].iov_len;
1595 if (setsockopt(reply[0], SOL_SOCKET, SO_SNDBUF, &expect, sizeof(int)) == -1)
1596 log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1597 strerror(errno));
1598 if (setsockopt(reply[1], SOL_SOCKET, SO_RCVBUF, &expect, sizeof(int)) == -1)
1599 log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1600 strerror(errno));
1602 log_Printf(LogDEBUG, "Sending %d descriptor%s and %u bytes in scatter"
1603 "/gather array\n", nfd, nfd == 1 ? "" : "s",
1604 (unsigned)iov[0].iov_len);
1606 if ((got = sendmsg(s, &msg, 0)) == -1)
1607 log_Printf(LogERROR, "Failed sendmsg: %s: %s\n",
1608 sun->sun_path, strerror(errno));
1609 else if (got != iov[0].iov_len)
1610 log_Printf(LogERROR, "%s: Failed initial sendmsg: Only sent %d of %u\n",
1611 sun->sun_path, got, (unsigned)iov[0].iov_len);
1612 else {
1613 /* We must get the ACK before closing the descriptor ! */
1614 int res;
1616 if ((got = read(reply[0], &newpid, sizeof newpid)) == sizeof newpid) {
1617 log_Printf(LogDEBUG, "Received confirmation from pid %ld\n",
1618 (long)newpid);
1619 if (lock && (res = ID0uu_lock_txfr(lock, newpid)) != UU_LOCK_OK)
1620 log_Printf(LogERROR, "uu_lock_txfr: %s\n", uu_lockerr(res));
1622 log_Printf(LogDEBUG, "Transmitting link (%d bytes)\n", expect);
1623 if ((got = writev(reply[0], iov + 1, niov - 1)) != expect) {
1624 if (got == -1)
1625 log_Printf(LogERROR, "%s: Failed writev: %s\n",
1626 sun->sun_path, strerror(errno));
1627 else
1628 log_Printf(LogERROR, "%s: Failed writev: Wrote %d of %d\n",
1629 sun->sun_path, got, expect);
1631 } else if (got == -1)
1632 log_Printf(LogERROR, "%s: Failed socketpair read: %s\n",
1633 sun->sun_path, strerror(errno));
1634 else
1635 log_Printf(LogERROR, "%s: Failed socketpair read: Got %d of %d\n",
1636 sun->sun_path, got, (int)(sizeof newpid));
1639 close(reply[0]);
1640 close(reply[1]);
1642 newsid = Enabled(dl->bundle, OPT_KEEPSESSION) ||
1643 tcgetpgrp(fd[0]) == getpgrp();
1644 while (nfd)
1645 close(fd[--nfd]);
1646 if (newsid)
1647 bundle_setsid(dl->bundle, got != -1);
1649 close(s);
1651 while (niov--)
1652 free(iov[niov].iov_base);
1656 bundle_RenameDatalink(struct bundle *bundle, struct datalink *ndl,
1657 const char *name)
1659 struct datalink *dl;
1661 if (!strcasecmp(ndl->name, name))
1662 return 1;
1664 for (dl = bundle->links; dl; dl = dl->next)
1665 if (!strcasecmp(dl->name, name))
1666 return 0;
1668 datalink_Rename(ndl, name);
1669 return 1;
1673 bundle_SetMode(struct bundle *bundle, struct datalink *dl, int mode)
1675 int omode;
1677 omode = dl->physical->type;
1678 if (omode == mode)
1679 return 1;
1681 if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO))
1682 /* First auto link */
1683 if (bundle->ncp.ipcp.peer_ip.s_addr == INADDR_ANY) {
1684 log_Printf(LogWARN, "You must `set ifaddr' or `open' before"
1685 " changing mode to %s\n", mode2Nam(mode));
1686 return 0;
1689 if (!datalink_SetMode(dl, mode))
1690 return 0;
1692 if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO) &&
1693 bundle->phase != PHASE_NETWORK)
1694 /* First auto link, we need an interface */
1695 ipcp_InterfaceUp(&bundle->ncp.ipcp);
1697 /* Regenerate phys_type and adjust idle timer */
1698 bundle_LinksRemoved(bundle);
1700 return 1;
1703 void
1704 bundle_setsid(struct bundle *bundle, int holdsession)
1707 * Lose the current session. This means getting rid of our pid
1708 * too so that the tty device will really go away, and any getty
1709 * etc will be allowed to restart.
1711 pid_t pid, orig;
1712 int fds[2];
1713 char done;
1714 struct datalink *dl;
1716 if (!holdsession && bundle_IsDead(bundle)) {
1718 * No need to lose our session after all... we're going away anyway
1720 * We should really stop the timer and pause if holdsession is set and
1721 * the bundle's dead, but that leaves other resources lying about :-(
1723 return;
1726 orig = getpid();
1727 if (pipe(fds) == -1) {
1728 log_Printf(LogERROR, "pipe: %s\n", strerror(errno));
1729 return;
1731 switch ((pid = fork())) {
1732 case -1:
1733 log_Printf(LogERROR, "fork: %s\n", strerror(errno));
1734 close(fds[0]);
1735 close(fds[1]);
1736 return;
1737 case 0:
1738 close(fds[1]);
1739 read(fds[0], &done, 1); /* uu_locks are mine ! */
1740 close(fds[0]);
1741 if (pipe(fds) == -1) {
1742 log_Printf(LogERROR, "pipe(2): %s\n", strerror(errno));
1743 return;
1745 switch ((pid = fork())) {
1746 case -1:
1747 log_Printf(LogERROR, "fork(2): %s\n", strerror(errno));
1748 close(fds[0]);
1749 close(fds[1]);
1750 return;
1751 case 0:
1752 close(fds[1]);
1753 bundle_LockTun(bundle); /* update pid */
1754 read(fds[0], &done, 1); /* uu_locks are mine ! */
1755 close(fds[0]);
1756 setsid();
1757 bundle_ChangedPID(bundle);
1758 log_Printf(LogDEBUG, "%ld -> %ld: %s session control\n",
1759 (long)orig, (long)getpid(),
1760 holdsession ? "Passed" : "Dropped");
1761 timer_InitService(0); /* Start the Timer Service */
1762 break;
1763 default:
1764 close(fds[0]);
1765 /* Give away all our physical locks (to the final process) */
1766 for (dl = bundle->links; dl; dl = dl->next)
1767 if (dl->state != DATALINK_CLOSED)
1768 physical_ChangedPid(dl->physical, pid);
1769 write(fds[1], "!", 1); /* done */
1770 close(fds[1]);
1771 _exit(0);
1772 break;
1774 break;
1775 default:
1776 close(fds[0]);
1777 /* Give away all our physical locks (to the intermediate process) */
1778 for (dl = bundle->links; dl; dl = dl->next)
1779 if (dl->state != DATALINK_CLOSED)
1780 physical_ChangedPid(dl->physical, pid);
1781 write(fds[1], "!", 1); /* done */
1782 close(fds[1]);
1783 if (holdsession) {
1784 int fd, status;
1786 timer_TermService();
1787 signal(SIGPIPE, SIG_DFL);
1788 signal(SIGALRM, SIG_DFL);
1789 signal(SIGHUP, SIG_DFL);
1790 signal(SIGTERM, SIG_DFL);
1791 signal(SIGINT, SIG_DFL);
1792 signal(SIGQUIT, SIG_DFL);
1793 for (fd = getdtablesize(); fd >= 0; fd--)
1794 close(fd);
1796 * Reap the intermediate process. As we're not exiting but the
1797 * intermediate is, we don't want it to become defunct.
1799 waitpid(pid, &status, 0);
1800 /* Tweak our process arguments.... */
1801 SetTitle("session owner");
1802 #ifndef NOSUID
1803 setuid(ID0realuid());
1804 #endif
1806 * Hang around for a HUP. This should happen as soon as the
1807 * ppp that we passed our ctty descriptor to closes it.
1808 * NOTE: If this process dies, the passed descriptor becomes
1809 * invalid and will give a select() error by setting one
1810 * of the error fds, aborting the other ppp. We don't
1811 * want that to happen !
1813 pause();
1815 _exit(0);
1816 break;
1821 bundle_HighestState(struct bundle *bundle)
1823 struct datalink *dl;
1824 int result = DATALINK_CLOSED;
1826 for (dl = bundle->links; dl; dl = dl->next)
1827 if (result < dl->state)
1828 result = dl->state;
1830 return result;
1834 bundle_Exception(struct bundle *bundle, int fd)
1836 struct datalink *dl;
1838 for (dl = bundle->links; dl; dl = dl->next)
1839 if (dl->physical->fd == fd) {
1840 datalink_Down(dl, CLOSE_NORMAL);
1841 return 1;
1844 return 0;
1847 void
1848 bundle_AdjustFilters(struct bundle *bundle, struct ncpaddr *local,
1849 struct ncpaddr *remote)
1851 filter_AdjustAddr(&bundle->filter.in, local, remote, NULL);
1852 filter_AdjustAddr(&bundle->filter.out, local, remote, NULL);
1853 filter_AdjustAddr(&bundle->filter.dial, local, remote, NULL);
1854 filter_AdjustAddr(&bundle->filter.alive, local, remote, NULL);
1857 void
1858 bundle_AdjustDNS(struct bundle *bundle)
1860 struct in_addr *dns = bundle->ncp.ipcp.ns.dns;
1862 filter_AdjustAddr(&bundle->filter.in, NULL, NULL, dns);
1863 filter_AdjustAddr(&bundle->filter.out, NULL, NULL, dns);
1864 filter_AdjustAddr(&bundle->filter.dial, NULL, NULL, dns);
1865 filter_AdjustAddr(&bundle->filter.alive, NULL, NULL, dns);
1868 void
1869 bundle_CalculateBandwidth(struct bundle *bundle)
1871 struct datalink *dl;
1872 int sp, overhead, maxoverhead;
1874 bundle->bandwidth = 0;
1875 bundle->iface->mtu = 0;
1876 maxoverhead = 0;
1878 for (dl = bundle->links; dl; dl = dl->next) {
1879 overhead = ccp_MTUOverhead(&dl->physical->link.ccp);
1880 if (maxoverhead < overhead)
1881 maxoverhead = overhead;
1882 if (dl->state == DATALINK_OPEN) {
1883 if ((sp = dl->mp.bandwidth) == 0 &&
1884 (sp = physical_GetSpeed(dl->physical)) == 0)
1885 log_Printf(LogDEBUG, "%s: %s: Cannot determine bandwidth\n",
1886 dl->name, dl->physical->name.full);
1887 else
1888 bundle->bandwidth += sp;
1889 if (!bundle->ncp.mp.active) {
1890 bundle->iface->mtu = dl->physical->link.lcp.his_mru;
1891 break;
1896 if (bundle->bandwidth == 0)
1897 bundle->bandwidth = 115200; /* Shrug */
1899 if (bundle->ncp.mp.active) {
1900 bundle->iface->mtu = bundle->ncp.mp.peer_mrru;
1901 overhead = ccp_MTUOverhead(&bundle->ncp.mp.link.ccp);
1902 if (maxoverhead < overhead)
1903 maxoverhead = overhead;
1904 } else if (!bundle->iface->mtu)
1905 bundle->iface->mtu = DEF_MRU;
1907 #ifndef NORADIUS
1908 if (bundle->radius.valid && bundle->radius.mtu &&
1909 bundle->radius.mtu < bundle->iface->mtu) {
1910 log_Printf(LogLCP, "Reducing MTU to radius value %lu\n",
1911 bundle->radius.mtu);
1912 bundle->iface->mtu = bundle->radius.mtu;
1914 #endif
1916 if (maxoverhead) {
1917 log_Printf(LogLCP, "Reducing MTU from %d to %d (CCP requirement)\n",
1918 bundle->iface->mtu, bundle->iface->mtu - maxoverhead);
1919 bundle->iface->mtu -= maxoverhead;
1922 tun_configure(bundle);
1924 route_UpdateMTU(bundle);
1927 void
1928 bundle_AutoAdjust(struct bundle *bundle, int percent, int what)
1930 struct datalink *dl, *choice, *otherlinkup;
1932 choice = otherlinkup = NULL;
1933 for (dl = bundle->links; dl; dl = dl->next)
1934 if (dl->physical->type == PHYS_AUTO) {
1935 if (dl->state == DATALINK_OPEN) {
1936 if (what == AUTO_DOWN) {
1937 if (choice)
1938 otherlinkup = choice;
1939 choice = dl;
1941 } else if (dl->state == DATALINK_CLOSED) {
1942 if (what == AUTO_UP) {
1943 choice = dl;
1944 break;
1946 } else {
1947 /* An auto link in an intermediate state - forget it for the moment */
1948 choice = NULL;
1949 break;
1951 } else if (dl->state == DATALINK_OPEN && what == AUTO_DOWN)
1952 otherlinkup = dl;
1954 if (choice) {
1955 if (what == AUTO_UP) {
1956 log_Printf(LogPHASE, "%d%% saturation -> Opening link ``%s''\n",
1957 percent, choice->name);
1958 datalink_Up(choice, 1, 1);
1959 mp_CheckAutoloadTimer(&bundle->ncp.mp);
1960 } else if (otherlinkup) { /* Only bring the second-last link down */
1961 log_Printf(LogPHASE, "%d%% saturation -> Closing link ``%s''\n",
1962 percent, choice->name);
1963 datalink_Close(choice, CLOSE_STAYDOWN);
1964 mp_CheckAutoloadTimer(&bundle->ncp.mp);
1970 bundle_WantAutoloadTimer(struct bundle *bundle)
1972 struct datalink *dl;
1973 int autolink, opened;
1975 if (bundle->phase == PHASE_NETWORK) {
1976 for (autolink = opened = 0, dl = bundle->links; dl; dl = dl->next)
1977 if (dl->physical->type == PHYS_AUTO) {
1978 if (++autolink == 2 || (autolink == 1 && opened))
1979 /* Two auto links or one auto and one open in NETWORK phase */
1980 return 1;
1981 } else if (dl->state == DATALINK_OPEN) {
1982 opened++;
1983 if (autolink)
1984 /* One auto and one open link in NETWORK phase */
1985 return 1;
1989 return 0;
1992 void
1993 bundle_ChangedPID(struct bundle *bundle)
1995 #ifdef TUNSIFPID
1996 ioctl(bundle->dev.fd, TUNSIFPID, 0);
1997 #endif
2001 bundle_Uptime(struct bundle *bundle)
2003 if (bundle->upat)
2004 return time(NULL) - bundle->upat;
2006 return 0;