2 * Copyright (c) 1998 Brian Somers <brian@Awfulhak.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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
29 #include <sys/param.h>
30 #include <sys/socket.h>
31 #include <netinet/in.h>
33 #include <net/if_tun.h> /* For TUNS* ioctls */
34 #include <net/route.h>
35 #include <netinet/in_systm.h>
36 #include <netinet/ip.h>
66 #include "throughput.h"
67 #include "slcompress.h"
72 #include "descriptor.h"
101 #define SCATTER_SEGMENTS 7 /* version, datalink, name, physical,
102 throughput, throughput, device */
104 #define SEND_MAXFD 3 /* Max file descriptors passed through
105 the local domain socket */
107 static int bundle_RemainingIdleTime(struct bundle *);
109 static const char * const PhaseNames[] = {
110 "Dead", "Establish", "Authenticate", "Network", "Terminate"
114 bundle_PhaseName(struct bundle *bundle)
116 return bundle->phase <= PHASE_TERMINATE ?
117 PhaseNames[bundle->phase] : "unknown";
121 bundle_NewPhase(struct bundle *bundle, u_int new)
123 if (new == bundle->phase)
126 if (new <= PHASE_TERMINATE)
127 log_Printf(LogPHASE, "bundle: %s\n", PhaseNames[new]);
133 MPPE_MasterKeyValid = 0;
135 log_DisplayPrompts();
138 case PHASE_ESTABLISH:
142 case PHASE_AUTHENTICATE:
144 log_DisplayPrompts();
148 if (ncp_fsmStart(&bundle->ncp, bundle)) {
150 log_DisplayPrompts();
152 log_Printf(LogPHASE, "bundle: All NCPs are disabled\n");
153 bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
157 case PHASE_TERMINATE:
159 mp_Down(&bundle->ncp.mp);
160 log_DisplayPrompts();
166 bundle_LayerStart(void *v, struct fsm *fp)
168 /* The given FSM is about to start up ! */
173 bundle_Notify(struct bundle *bundle, char c)
175 if (bundle->notify.fd != -1) {
178 ret = write(bundle->notify.fd, &c, 1);
179 if (c != EX_REDIAL && c != EX_RECONNECT) {
181 log_Printf(LogCHAT, "Parent notified of %s\n",
182 c == EX_NORMAL ? "success" : "failure");
184 log_Printf(LogERROR, "Failed to notify parent of success\n");
185 close(bundle->notify.fd);
186 bundle->notify.fd = -1;
188 log_Printf(LogCHAT, "Parent notified of %s\n", ex_desc(c));
190 log_Printf(LogERROR, "Failed to notify parent of %s\n", ex_desc(c));
195 bundle_ClearQueues(void *v)
197 struct bundle *bundle = (struct bundle *)v;
200 log_Printf(LogPHASE, "Clearing choked output queue\n");
201 timer_Stop(&bundle->choked.timer);
206 * We've had a full queue for PACKET_DEL_SECS seconds without being
207 * able to get rid of any of the packets. We've probably given up
208 * on the redials at this point, and the queued data has almost
209 * definitely been timed out by the layer above. As this is preventing
210 * us from reading the TUN_NAME device (we don't want to buffer stuff
211 * indefinitely), we may as well nuke this data and start with a clean
214 * Unfortunately, this has the side effect of shafting any compression
215 * dictionaries in use (causing the relevant RESET_REQ/RESET_ACK).
218 ncp_DeleteQueues(&bundle->ncp);
219 for (dl = bundle->links; dl; dl = dl->next)
220 physical_DeleteQueue(dl->physical);
224 bundle_LinkAdded(struct bundle *bundle, struct datalink *dl)
226 bundle->phys_type.all |= dl->physical->type;
227 if (dl->state == DATALINK_OPEN)
228 bundle->phys_type.open |= dl->physical->type;
230 if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
231 != bundle->phys_type.open && bundle->idle.timer.state == TIMER_STOPPED)
232 /* We may need to start our idle timer */
233 bundle_StartIdleTimer(bundle, 0);
237 bundle_LinksRemoved(struct bundle *bundle)
241 bundle->phys_type.all = bundle->phys_type.open = 0;
242 for (dl = bundle->links; dl; dl = dl->next)
243 bundle_LinkAdded(bundle, dl);
245 bundle_CalculateBandwidth(bundle);
246 mp_CheckAutoloadTimer(&bundle->ncp.mp);
248 if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
249 == bundle->phys_type.open)
250 bundle_StopIdleTimer(bundle);
254 bundle_LayerUp(void *v, struct fsm *fp)
257 * The given fsm is now up
258 * If it's an LCP, adjust our phys_mode.open value and check the
260 * If it's the first NCP, calculate our bandwidth
261 * If it's the first NCP, set our ``upat'' time
262 * If it's the first NCP, start the idle timer.
263 * If it's an NCP, tell our -background parent to go away.
264 * If it's the first NCP, start the autoload timer
266 struct bundle *bundle = (struct bundle *)v;
268 if (fp->proto == PROTO_LCP) {
269 struct physical *p = link2physical(fp->link);
271 bundle_LinkAdded(bundle, p->dl);
272 mp_CheckAutoloadTimer(&bundle->ncp.mp);
273 } else if (isncp(fp->proto)) {
274 if (ncp_LayersOpen(&fp->bundle->ncp) == 1) {
275 bundle_CalculateBandwidth(fp->bundle);
277 bundle_StartIdleTimer(bundle, 0);
278 mp_CheckAutoloadTimer(&fp->bundle->ncp.mp);
280 bundle_Notify(bundle, EX_NORMAL);
281 } else if (fp->proto == PROTO_CCP)
282 bundle_CalculateBandwidth(fp->bundle); /* Against ccp_MTUOverhead */
286 bundle_LayerDown(void *v, struct fsm *fp)
289 * The given FSM has been told to come down.
290 * If it's our last NCP, stop the idle timer.
291 * If it's our last NCP, clear our ``upat'' value.
292 * If it's our last NCP, stop the autoload timer
293 * If it's an LCP, adjust our phys_type.open value and any timers.
294 * If it's an LCP and we're in multilink mode, adjust our tun
295 * If it's the last LCP, down all NCPs
296 * speed and make sure our minimum sequence number is adjusted.
299 struct bundle *bundle = (struct bundle *)v;
301 if (isncp(fp->proto)) {
302 if (ncp_LayersOpen(&fp->bundle->ncp) == 0) {
303 bundle_StopIdleTimer(bundle);
305 mp_StopAutoloadTimer(&bundle->ncp.mp);
307 } else if (fp->proto == PROTO_LCP) {
309 struct datalink *lost;
312 bundle_LinksRemoved(bundle); /* adjust timers & phys_type values */
316 for (dl = bundle->links; dl; dl = dl->next) {
317 if (fp == &dl->physical->link.lcp.fsm)
319 else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
323 if (bundle->ncp.mp.active) {
324 bundle_CalculateBandwidth(bundle);
327 mp_LinkLost(&bundle->ncp.mp, lost);
329 log_Printf(LogALERT, "Oops, lost an unrecognised datalink (%s) !\n",
333 if (!others_active) {
334 /* Down the NCPs. We don't expect to get fsm_Close()d ourself ! */
335 ncp2initial(&bundle->ncp);
336 mp_Down(&bundle->ncp.mp);
342 bundle_LayerFinish(void *v, struct fsm *fp)
344 /* The given fsm is now down (fp cannot be NULL)
346 * If it's the last NCP, fsm_Close all LCPs
347 * If it's the last NCP, bring any MP layer down
350 struct bundle *bundle = (struct bundle *)v;
353 if (isncp(fp->proto) && !ncp_LayersUnfinished(&bundle->ncp)) {
354 if (bundle_Phase(bundle) != PHASE_DEAD)
355 bundle_NewPhase(bundle, PHASE_TERMINATE);
356 for (dl = bundle->links; dl; dl = dl->next)
357 if (dl->state == DATALINK_OPEN)
358 datalink_Close(dl, CLOSE_STAYDOWN);
360 mp_Down(&bundle->ncp.mp);
365 bundle_Close(struct bundle *bundle, const char *name, int how)
368 * Please close the given datalink.
369 * If name == NULL or name is the last datalink, fsm_Close all NCPs
371 * If it isn't the last datalink, just Close that datalink.
374 struct datalink *dl, *this_dl;
380 for (dl = bundle->links; dl; dl = dl->next) {
381 if (name && !strcasecmp(name, dl->name))
383 if (name == NULL || this_dl == dl) {
386 datalink_DontHangup(dl);
389 datalink_StayDown(dl);
392 } else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
396 if (name && this_dl == NULL) {
397 log_Printf(LogWARN, "%s: Invalid datalink name\n", name);
401 if (!others_active) {
402 bundle_StopIdleTimer(bundle);
403 if (ncp_LayersUnfinished(&bundle->ncp))
404 ncp_Close(&bundle->ncp);
406 ncp2initial(&bundle->ncp);
407 mp_Down(&bundle->ncp.mp);
408 for (dl = bundle->links; dl; dl = dl->next)
409 datalink_Close(dl, how);
411 } else if (this_dl && this_dl->state != DATALINK_CLOSED &&
412 this_dl->state != DATALINK_HANGUP)
413 datalink_Close(this_dl, how);
417 bundle_Down(struct bundle *bundle, int how)
421 for (dl = bundle->links; dl; dl = dl->next)
422 datalink_Down(dl, how);
426 bundle_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
428 struct bundle *bundle = descriptor2bundle(d);
436 /* If there are aren't many packets queued, look for some more. */
437 for (nlinks = 0, dl = bundle->links; dl; dl = dl->next)
441 queued = r ? ncp_FillPhysicalQueues(&bundle->ncp, bundle) :
442 ncp_QueueLen(&bundle->ncp);
444 if (r && (bundle->phase == PHASE_NETWORK ||
445 bundle->phys_type.all & PHYS_AUTO)) {
446 /* enough surplus so that we can tell if we're getting swamped */
447 ifqueue = nlinks > bundle->cfg.ifqueue ? nlinks : bundle->cfg.ifqueue;
448 if (queued < ifqueue) {
449 /* Not enough - select() for more */
450 if (bundle->choked.timer.state == TIMER_RUNNING)
451 timer_Stop(&bundle->choked.timer); /* Not needed any more */
452 FD_SET(bundle->dev.fd, r);
453 if (*n < bundle->dev.fd + 1)
454 *n = bundle->dev.fd + 1;
455 log_Printf(LogTIMER, "%s: fdset(r) %d\n", TUN_NAME, bundle->dev.fd);
457 } else if (bundle->choked.timer.state == TIMER_STOPPED) {
458 bundle->choked.timer.func = bundle_ClearQueues;
459 bundle->choked.timer.name = "output choke";
460 bundle->choked.timer.load = bundle->cfg.choked.timeout * SECTICKS;
461 bundle->choked.timer.arg = bundle;
462 timer_Start(&bundle->choked.timer);
468 result += descriptor_UpdateSet(&bundle->radius.desc, r, w, e, n);
471 /* Which links need a select() ? */
472 for (dl = bundle->links; dl; dl = dl->next)
473 result += descriptor_UpdateSet(&dl->desc, r, w, e, n);
476 * This *MUST* be called after the datalink UpdateSet()s as it
477 * might be ``holding'' one of the datalinks (death-row) and
478 * wants to be able to de-select() it from the descriptor set.
480 result += descriptor_UpdateSet(&bundle->ncp.mp.server.desc, r, w, e, n);
486 bundle_IsSet(struct fdescriptor *d, const fd_set *fdset)
488 struct bundle *bundle = descriptor2bundle(d);
491 for (dl = bundle->links; dl; dl = dl->next)
492 if (descriptor_IsSet(&dl->desc, fdset))
496 if (descriptor_IsSet(&bundle->radius.desc, fdset))
500 if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
503 return FD_ISSET(bundle->dev.fd, fdset);
507 bundle_DescriptorRead(struct fdescriptor *d, struct bundle *bundle,
514 if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
515 descriptor_Read(&bundle->ncp.mp.server.desc, bundle, fdset);
517 for (dl = bundle->links; dl; dl = dl->next)
518 if (descriptor_IsSet(&dl->desc, fdset))
519 descriptor_Read(&dl->desc, bundle, fdset);
522 if (descriptor_IsSet(&bundle->radius.desc, fdset))
523 descriptor_Read(&bundle->radius.desc, bundle, fdset);
526 if (FD_ISSET(bundle->dev.fd, fdset)) {
532 if (bundle->dev.header) {
537 sz = sizeof tun.data;
540 /* something to read from tun */
542 n = read(bundle->dev.fd, data, sz);
544 log_Printf(LogWARN, "%s: read: %s\n", bundle->dev.Name, strerror(errno));
548 if (bundle->dev.header) {
549 n -= sz - sizeof tun.data;
551 log_Printf(LogERROR, "%s: read: Got only %d bytes of data !\n",
552 bundle->dev.Name, n);
555 af = ntohl(tun.header.family);
557 if (af != AF_INET && af != AF_INET6)
561 /* XXX: Should be maintaining drop/family counts ! */
566 if (af == AF_INET && ((struct ip *)tun.data)->ip_dst.s_addr ==
567 bundle->ncp.ipcp.my_ip.s_addr) {
568 /* we've been asked to send something addressed *to* us :( */
569 if (Enabled(bundle, OPT_LOOPBACK)) {
570 pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.in,
573 n += sz - sizeof tun.data;
574 write(bundle->dev.fd, data, n);
575 log_Printf(LogDEBUG, "Looped back packet addressed to myself\n");
579 log_Printf(LogDEBUG, "Oops - forwarding packet addressed to myself\n");
583 * Process on-demand dialup. Output packets are queued within the tunnel
584 * device until the appropriate NCP is opened.
587 if (bundle_Phase(bundle) == PHASE_DEAD) {
589 * Note, we must be in AUTO mode :-/ otherwise our interface should
590 * *not* be UP and we can't receive data
592 pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.dial,
595 bundle_Open(bundle, NULL, PHYS_AUTO, 0);
598 * Drop the packet. If we were to queue it, we'd just end up with
599 * a pile of timed-out data in our output queue by the time we get
600 * around to actually dialing. We'd also prematurely reach the
601 * threshold at which we stop select()ing to read() the tun
602 * device - breaking auto-dial.
608 pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.out,
611 /* Prepend the number of seconds timeout given in the filter */
612 tun.header.timeout = secs;
613 ncp_Enqueue(&bundle->ncp, af, pri, (char *)&tun, n + sizeof tun.header);
619 bundle_DescriptorWrite(struct fdescriptor *d, struct bundle *bundle,
625 /* This is not actually necessary as struct mpserver doesn't Write() */
626 if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
627 if (descriptor_Write(&bundle->ncp.mp.server.desc, bundle, fdset) == 1)
630 for (dl = bundle->links; dl; dl = dl->next)
631 if (descriptor_IsSet(&dl->desc, fdset))
632 switch (descriptor_Write(&dl->desc, bundle, fdset)) {
634 datalink_ComeDown(dl, CLOSE_NORMAL);
644 bundle_LockTun(struct bundle *bundle)
647 char pidfile[PATH_MAX];
649 snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
650 lockfile = ID0fopen(pidfile, "w");
651 if (lockfile != NULL) {
652 fprintf(lockfile, "%d\n", (int)getpid());
655 #ifndef RELEASE_CRUNCH
657 log_Printf(LogERROR, "Warning: Can't create %s: %s\n",
658 pidfile, strerror(errno));
663 bundle_UnlockTun(struct bundle *bundle)
665 char pidfile[PATH_MAX];
667 snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
672 bundle_Create(const char *prefix, int type, int unit)
674 static struct bundle bundle; /* there can be only one */
675 int enoentcount, err, minunit, maxunit;
677 #if defined(__FreeBSD__) && !defined(NOKLDLOAD)
680 #if defined(TUNSIFMODE) || defined(TUNSLMODE) || defined(TUNSIFHEAD)
684 if (bundle.iface != NULL) { /* Already allocated ! */
685 log_Printf(LogALERT, "bundle_Create: There's only one BUNDLE !\n");
698 #if defined(__FreeBSD__) && !defined(NOKLDLOAD)
701 for (bundle.unit = minunit; bundle.unit != maxunit; bundle.unit++) {
702 snprintf(bundle.dev.Name, sizeof bundle.dev.Name, "%s%d",
703 prefix, bundle.unit);
704 bundle.dev.fd = ID0open(bundle.dev.Name, O_RDWR);
705 if (bundle.dev.fd >= 0)
707 else if (errno == ENXIO || errno == ENOENT) {
708 #if defined(__FreeBSD__) && !defined(NOKLDLOAD)
709 if (bundle.unit == minunit && !kldtried++) {
711 * Attempt to load the tunnel interface KLD if it isn't loaded
714 if (loadmodules(LOAD_VERBOSLY, "if_tun", NULL))
719 if (errno != ENOENT || ++enoentcount > 2) {
727 if (bundle.dev.fd < 0) {
729 log_Printf(LogWARN, "No available tunnel devices found (%s)\n",
732 log_Printf(LogWARN, "%s%d: %s\n", prefix, unit, strerror(err));
736 log_SetTun(bundle.unit);
738 ifname = strrchr(bundle.dev.Name, '/');
740 ifname = bundle.dev.Name;
744 bundle.iface = iface_Create(ifname);
745 if (bundle.iface == NULL) {
746 close(bundle.dev.fd);
751 /* Make sure we're POINTOPOINT & IFF_MULTICAST */
752 iff = IFF_POINTOPOINT | IFF_MULTICAST;
753 if (ID0ioctl(bundle.dev.fd, TUNSIFMODE, &iff) < 0)
754 log_Printf(LogERROR, "bundle_Create: ioctl(TUNSIFMODE): %s\n",
759 /* Make sure we're not prepending sockaddrs */
761 if (ID0ioctl(bundle.dev.fd, TUNSLMODE, &iff) < 0)
762 log_Printf(LogERROR, "bundle_Create: ioctl(TUNSLMODE): %s\n",
767 /* We want the address family please ! */
769 if (ID0ioctl(bundle.dev.fd, TUNSIFHEAD, &iff) < 0) {
770 log_Printf(LogERROR, "bundle_Create: ioctl(TUNSIFHEAD): %s\n",
772 bundle.dev.header = 0;
774 bundle.dev.header = 1;
777 /* Always present for OpenBSD */
778 bundle.dev.header = 1;
781 * If TUNSIFHEAD isn't available and we're not OpenBSD, assume
782 * everything's AF_INET (hopefully the tun device won't pass us
785 bundle.dev.header = 0;
789 log_Printf(LogPHASE, "Using interface: %s\n", ifname);
791 bundle.bandwidth = 0;
792 bundle.routing_seq = 0;
793 bundle.phase = PHASE_DEAD;
794 bundle.CleaningUp = 0;
795 bundle.NatEnabled = 0;
797 bundle.fsm.LayerStart = bundle_LayerStart;
798 bundle.fsm.LayerUp = bundle_LayerUp;
799 bundle.fsm.LayerDown = bundle_LayerDown;
800 bundle.fsm.LayerFinish = bundle_LayerFinish;
801 bundle.fsm.object = &bundle;
803 bundle.cfg.idle.timeout = NCP_IDLE_TIMEOUT;
804 bundle.cfg.idle.min_timeout = 0;
805 *bundle.cfg.auth.name = '\0';
806 *bundle.cfg.auth.key = '\0';
807 bundle.cfg.opt = OPT_IDCHECK | OPT_LOOPBACK | OPT_SROUTES | OPT_TCPMSSFIXUP |
808 OPT_THROUGHPUT | OPT_UTMP;
810 bundle.cfg.opt |= OPT_IPCP;
811 if (probe.ipv6_available)
812 bundle.cfg.opt |= OPT_IPV6CP;
814 *bundle.cfg.label = '\0';
815 bundle.cfg.ifqueue = DEF_IFQUEUE;
816 bundle.cfg.choked.timeout = CHOKED_TIMEOUT;
817 bundle.phys_type.all = type;
818 bundle.phys_type.open = 0;
821 bundle.links = datalink_Create("deflink", &bundle, type);
822 if (bundle.links == NULL) {
823 log_Printf(LogALERT, "Cannot create data link: %s\n", strerror(errno));
824 iface_Destroy(bundle.iface);
826 close(bundle.dev.fd);
830 bundle.desc.type = BUNDLE_DESCRIPTOR;
831 bundle.desc.UpdateSet = bundle_UpdateSet;
832 bundle.desc.IsSet = bundle_IsSet;
833 bundle.desc.Read = bundle_DescriptorRead;
834 bundle.desc.Write = bundle_DescriptorWrite;
836 ncp_Init(&bundle.ncp, &bundle);
838 memset(&bundle.filter, '\0', sizeof bundle.filter);
839 bundle.filter.in.fragok = bundle.filter.in.logok = 1;
840 bundle.filter.in.name = "IN";
841 bundle.filter.out.fragok = bundle.filter.out.logok = 1;
842 bundle.filter.out.name = "OUT";
843 bundle.filter.dial.name = "DIAL";
844 bundle.filter.dial.logok = 1;
845 bundle.filter.alive.name = "ALIVE";
846 bundle.filter.alive.logok = 1;
849 for (i = 0; i < MAXFILTERS; i++) {
850 bundle.filter.in.rule[i].f_action = A_NONE;
851 bundle.filter.out.rule[i].f_action = A_NONE;
852 bundle.filter.dial.rule[i].f_action = A_NONE;
853 bundle.filter.alive.rule[i].f_action = A_NONE;
856 memset(&bundle.idle.timer, '\0', sizeof bundle.idle.timer);
857 bundle.idle.done = 0;
858 bundle.notify.fd = -1;
859 memset(&bundle.choked.timer, '\0', sizeof bundle.choked.timer);
861 radius_Init(&bundle.radius);
864 /* Clean out any leftover crud */
865 iface_Clear(bundle.iface, &bundle.ncp, 0, IFACE_CLEAR_ALL);
867 bundle_LockTun(&bundle);
873 bundle_DownInterface(struct bundle *bundle)
875 route_IfDelete(bundle, 1);
876 iface_ClearFlags(bundle->iface->name, IFF_UP);
880 bundle_Destroy(struct bundle *bundle)
885 * Clean up the interface. We don't really need to do the timer_Stop()s,
886 * mp_Down(), iface_Clear() and bundle_DownInterface() unless we're getting
887 * out under exceptional conditions such as a descriptor exception.
889 timer_Stop(&bundle->idle.timer);
890 timer_Stop(&bundle->choked.timer);
891 mp_Down(&bundle->ncp.mp);
892 iface_Clear(bundle->iface, &bundle->ncp, 0, IFACE_CLEAR_ALL);
893 bundle_DownInterface(bundle);
896 /* Tell the radius server the bad news */
897 radius_Destroy(&bundle->radius);
900 /* Again, these are all DATALINK_CLOSED unless we're abending */
903 dl = datalink_Destroy(dl);
905 ncp_Destroy(&bundle->ncp);
907 close(bundle->dev.fd);
908 bundle_UnlockTun(bundle);
910 /* In case we never made PHASE_NETWORK */
911 bundle_Notify(bundle, EX_ERRDEAD);
913 iface_Destroy(bundle->iface);
914 bundle->iface = NULL;
918 bundle_LinkClosed(struct bundle *bundle, struct datalink *dl)
921 * Our datalink has closed.
922 * CleanDatalinks() (called from DoLoop()) will remove closed
923 * BACKGROUND, FOREGROUND and DIRECT links.
924 * If it's the last data link, enter phase DEAD.
926 * NOTE: dl may not be in our list (bundle_SendDatalink()) !
929 struct datalink *odl;
932 log_SetTtyCommandMode(dl);
935 for (odl = bundle->links; odl; odl = odl->next)
936 if (odl != dl && odl->state != DATALINK_CLOSED)
940 if (dl->physical->type != PHYS_AUTO) /* Not in -auto mode */
941 bundle_DownInterface(bundle);
942 ncp2initial(&bundle->ncp);
943 mp_Down(&bundle->ncp.mp);
944 bundle_NewPhase(bundle, PHASE_DEAD);
945 bundle_StopIdleTimer(bundle);
950 bundle_Open(struct bundle *bundle, const char *name, int mask, int force)
953 * Please open the given datalink, or all if name == NULL
957 for (dl = bundle->links; dl; dl = dl->next)
958 if (name == NULL || !strcasecmp(dl->name, name)) {
959 if ((mask & dl->physical->type) &&
960 (dl->state == DATALINK_CLOSED ||
961 (force && dl->state == DATALINK_OPENING &&
962 dl->dial.timer.state == TIMER_RUNNING) ||
963 dl->state == DATALINK_READY)) {
964 timer_Stop(&dl->dial.timer); /* We're finished with this */
965 datalink_Up(dl, 1, 1);
966 if (mask & PHYS_AUTO)
967 break; /* Only one AUTO link at a time */
975 bundle2datalink(struct bundle *bundle, const char *name)
980 for (dl = bundle->links; dl; dl = dl->next)
981 if (!strcasecmp(dl->name, name))
983 } else if (bundle->links && !bundle->links->next)
984 return bundle->links;
990 bundle_ShowLinks(struct cmdargs const *arg)
993 struct pppThroughput *t;
994 unsigned long long octets;
997 for (dl = arg->bundle->links; dl; dl = dl->next) {
998 octets = MAX(dl->physical->link.stats.total.in.OctetsPerSecond,
999 dl->physical->link.stats.total.out.OctetsPerSecond);
1001 prompt_Printf(arg->prompt, "Name: %s [%s, %s]",
1002 dl->name, mode2Nam(dl->physical->type), datalink_State(dl));
1003 if (dl->physical->link.stats.total.rolling && dl->state == DATALINK_OPEN)
1004 prompt_Printf(arg->prompt, " bandwidth %d, %llu bps (%llu bytes/sec)",
1005 dl->mp.bandwidth ? dl->mp.bandwidth :
1006 physical_GetSpeed(dl->physical),
1007 octets * 8, octets);
1008 prompt_Printf(arg->prompt, "\n");
1011 t = &arg->bundle->ncp.mp.link.stats.total;
1012 octets = MAX(t->in.OctetsPerSecond, t->out.OctetsPerSecond);
1013 secs = t->downtime ? 0 : throughput_uptime(t);
1014 if (secs > t->SamplePeriod)
1015 secs = t->SamplePeriod;
1017 prompt_Printf(arg->prompt, "Currently averaging %llu bps (%llu bytes/sec)"
1018 " over the last %d secs\n", octets * 8, octets, secs);
1024 optval(struct bundle *bundle, int bit)
1026 return (bundle->cfg.opt & bit) ? "enabled" : "disabled";
1030 bundle_ShowStatus(struct cmdargs const *arg)
1034 prompt_Printf(arg->prompt, "Phase %s\n", bundle_PhaseName(arg->bundle));
1035 prompt_Printf(arg->prompt, " Device: %s\n", arg->bundle->dev.Name);
1036 prompt_Printf(arg->prompt, " Interface: %s @ %lubps",
1037 arg->bundle->iface->name, arg->bundle->bandwidth);
1039 if (arg->bundle->upat) {
1040 int secs = bundle_Uptime(arg->bundle);
1042 prompt_Printf(arg->prompt, ", up time %d:%02d:%02d", secs / 3600,
1043 (secs / 60) % 60, secs % 60);
1045 prompt_Printf(arg->prompt, "\n Queued: %lu of %u\n",
1046 (unsigned long)ncp_QueueLen(&arg->bundle->ncp),
1047 arg->bundle->cfg.ifqueue);
1049 prompt_Printf(arg->prompt, "\nDefaults:\n");
1050 prompt_Printf(arg->prompt, " Label: %s\n",
1051 arg->bundle->cfg.label);
1052 prompt_Printf(arg->prompt, " Auth name: %s\n",
1053 arg->bundle->cfg.auth.name);
1054 prompt_Printf(arg->prompt, " Diagnostic socket: ");
1055 if (*server.cfg.sockname != '\0') {
1056 prompt_Printf(arg->prompt, "%s", server.cfg.sockname);
1057 if (server.cfg.mask != (mode_t)-1)
1058 prompt_Printf(arg->prompt, ", mask 0%03o", (int)server.cfg.mask);
1059 prompt_Printf(arg->prompt, "%s\n", server.fd == -1 ? " (not open)" : "");
1060 } else if (server.cfg.port != 0)
1061 prompt_Printf(arg->prompt, "TCP port %d%s\n", server.cfg.port,
1062 server.fd == -1 ? " (not open)" : "");
1064 prompt_Printf(arg->prompt, "none\n");
1066 prompt_Printf(arg->prompt, " Choked Timer: %ds\n",
1067 arg->bundle->cfg.choked.timeout);
1070 radius_Show(&arg->bundle->radius, arg->prompt);
1073 prompt_Printf(arg->prompt, " Idle Timer: ");
1074 if (arg->bundle->cfg.idle.timeout) {
1075 prompt_Printf(arg->prompt, "%ds", arg->bundle->cfg.idle.timeout);
1076 if (arg->bundle->cfg.idle.min_timeout)
1077 prompt_Printf(arg->prompt, ", min %ds",
1078 arg->bundle->cfg.idle.min_timeout);
1079 remaining = bundle_RemainingIdleTime(arg->bundle);
1080 if (remaining != -1)
1081 prompt_Printf(arg->prompt, " (%ds remaining)", remaining);
1082 prompt_Printf(arg->prompt, "\n");
1084 prompt_Printf(arg->prompt, "disabled\n");
1086 prompt_Printf(arg->prompt, " Filter Decap: %-20.20s",
1087 optval(arg->bundle, OPT_FILTERDECAP));
1088 prompt_Printf(arg->prompt, " ID check: %s\n",
1089 optval(arg->bundle, OPT_IDCHECK));
1090 prompt_Printf(arg->prompt, " Iface-Alias: %-20.20s",
1091 optval(arg->bundle, OPT_IFACEALIAS));
1093 prompt_Printf(arg->prompt, " IPCP: %s\n",
1094 optval(arg->bundle, OPT_IPCP));
1095 prompt_Printf(arg->prompt, " IPV6CP: %-20.20s",
1096 optval(arg->bundle, OPT_IPV6CP));
1098 prompt_Printf(arg->prompt, " Keep-Session: %s\n",
1099 optval(arg->bundle, OPT_KEEPSESSION));
1100 prompt_Printf(arg->prompt, " Loopback: %-20.20s",
1101 optval(arg->bundle, OPT_LOOPBACK));
1102 prompt_Printf(arg->prompt, " PasswdAuth: %s\n",
1103 optval(arg->bundle, OPT_PASSWDAUTH));
1104 prompt_Printf(arg->prompt, " Proxy: %-20.20s",
1105 optval(arg->bundle, OPT_PROXY));
1106 prompt_Printf(arg->prompt, " Proxyall: %s\n",
1107 optval(arg->bundle, OPT_PROXYALL));
1108 prompt_Printf(arg->prompt, " Sticky Routes: %-20.20s",
1109 optval(arg->bundle, OPT_SROUTES));
1110 prompt_Printf(arg->prompt, " TCPMSS Fixup: %s\n",
1111 optval(arg->bundle, OPT_TCPMSSFIXUP));
1112 prompt_Printf(arg->prompt, " Throughput: %-20.20s",
1113 optval(arg->bundle, OPT_THROUGHPUT));
1114 prompt_Printf(arg->prompt, " Utmp Logging: %s\n",
1115 optval(arg->bundle, OPT_UTMP));
1121 bundle_IdleTimeout(void *v)
1123 struct bundle *bundle = (struct bundle *)v;
1125 log_Printf(LogPHASE, "Idle timer expired\n");
1126 bundle_StopIdleTimer(bundle);
1127 bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
1131 * Start Idle timer. If timeout is reached, we call bundle_Close() to
1132 * close LCP and link.
1135 bundle_StartIdleTimer(struct bundle *bundle, unsigned secs)
1137 timer_Stop(&bundle->idle.timer);
1138 if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) !=
1139 bundle->phys_type.open && bundle->cfg.idle.timeout) {
1140 time_t now = time(NULL);
1143 secs = bundle->cfg.idle.timeout;
1145 /* We want at least `secs' */
1146 if (bundle->cfg.idle.min_timeout > secs && bundle->upat) {
1147 int up = now - bundle->upat;
1149 if ((long long)bundle->cfg.idle.min_timeout - up > (long long)secs)
1150 /* Only increase from the current `remaining' value */
1151 secs = bundle->cfg.idle.min_timeout - up;
1153 bundle->idle.timer.func = bundle_IdleTimeout;
1154 bundle->idle.timer.name = "idle";
1155 bundle->idle.timer.load = secs * SECTICKS;
1156 bundle->idle.timer.arg = bundle;
1157 timer_Start(&bundle->idle.timer);
1158 bundle->idle.done = now + secs;
1163 bundle_SetIdleTimer(struct bundle *bundle, int timeout, int min_timeout)
1165 bundle->cfg.idle.timeout = timeout;
1166 if (min_timeout >= 0)
1167 bundle->cfg.idle.min_timeout = min_timeout;
1168 if (ncp_LayersOpen(&bundle->ncp))
1169 bundle_StartIdleTimer(bundle, 0);
1173 bundle_StopIdleTimer(struct bundle *bundle)
1175 timer_Stop(&bundle->idle.timer);
1176 bundle->idle.done = 0;
1180 bundle_RemainingIdleTime(struct bundle *bundle)
1182 if (bundle->idle.done)
1183 return bundle->idle.done - time(NULL);
1188 bundle_IsDead(struct bundle *bundle)
1190 return !bundle->links || (bundle->phase == PHASE_DEAD && bundle->CleaningUp);
1193 static struct datalink *
1194 bundle_DatalinkLinkout(struct bundle *bundle, struct datalink *dl)
1196 struct datalink **dlp;
1198 for (dlp = &bundle->links; *dlp; dlp = &(*dlp)->next)
1202 bundle_LinksRemoved(bundle);
1210 bundle_DatalinkLinkin(struct bundle *bundle, struct datalink *dl)
1212 struct datalink **dlp = &bundle->links;
1215 dlp = &(*dlp)->next;
1220 bundle_LinkAdded(bundle, dl);
1221 mp_CheckAutoloadTimer(&bundle->ncp.mp);
1225 bundle_CleanDatalinks(struct bundle *bundle)
1227 struct datalink **dlp = &bundle->links;
1231 if ((*dlp)->state == DATALINK_CLOSED &&
1232 (*dlp)->physical->type &
1233 (PHYS_DIRECT|PHYS_BACKGROUND|PHYS_FOREGROUND)) {
1234 *dlp = datalink_Destroy(*dlp);
1237 dlp = &(*dlp)->next;
1240 bundle_LinksRemoved(bundle);
1244 bundle_DatalinkClone(struct bundle *bundle, struct datalink *dl,
1247 if (bundle2datalink(bundle, name)) {
1248 log_Printf(LogWARN, "Clone: %s: name already exists\n", name);
1252 bundle_DatalinkLinkin(bundle, datalink_Clone(dl, name));
1257 bundle_DatalinkRemove(struct bundle *bundle, struct datalink *dl)
1259 dl = bundle_DatalinkLinkout(bundle, dl);
1261 datalink_Destroy(dl);
1265 bundle_SetLabel(struct bundle *bundle, const char *label)
1268 strncpy(bundle->cfg.label, label, sizeof bundle->cfg.label - 1);
1270 *bundle->cfg.label = '\0';
1274 bundle_GetLabel(struct bundle *bundle)
1276 return *bundle->cfg.label ? bundle->cfg.label : NULL;
1282 struct iovec iov[SCATTER_SEGMENTS];
1283 int niov, expect, f;
1285 iov[0].iov_len = strlen(Version) + 1;
1286 iov[0].iov_base = NULL;
1288 if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1289 log_Printf(LogERROR, "Cannot determine space required for link\n");
1293 for (f = expect = 0; f < niov; f++)
1294 expect += iov[f].iov_len;
1300 bundle_ReceiveDatalink(struct bundle *bundle, int s)
1302 char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int) * SEND_MAXFD];
1303 int niov, expect, f, *fd, nfd, onfd, got;
1304 struct iovec iov[SCATTER_SEGMENTS];
1305 struct cmsghdr *cmsg;
1307 struct datalink *dl;
1310 log_Printf(LogPHASE, "Receiving datalink\n");
1313 * Create our scatter/gather array - passing NULL gets the space
1314 * allocation requirement rather than actually flattening the
1317 iov[0].iov_len = strlen(Version) + 1;
1318 iov[0].iov_base = NULL;
1320 if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1321 log_Printf(LogERROR, "Cannot determine space required for link\n");
1325 /* Allocate the scatter/gather array for recvmsg() */
1326 for (f = expect = 0; f < niov; f++) {
1327 if ((iov[f].iov_base = malloc(iov[f].iov_len)) == NULL) {
1328 log_Printf(LogERROR, "Cannot allocate space to receive link\n");
1332 expect += iov[f].iov_len;
1335 /* Set up our message */
1336 cmsg = (struct cmsghdr *)cmsgbuf;
1337 cmsg->cmsg_len = sizeof cmsgbuf;
1338 cmsg->cmsg_level = SOL_SOCKET;
1339 cmsg->cmsg_type = 0;
1341 memset(&msg, '\0', sizeof msg);
1342 msg.msg_name = NULL;
1343 msg.msg_namelen = 0;
1345 msg.msg_iovlen = 1; /* Only send the version at the first pass */
1346 msg.msg_control = cmsgbuf;
1347 msg.msg_controllen = sizeof cmsgbuf;
1349 log_Printf(LogDEBUG, "Expecting %u scatter/gather bytes\n",
1350 (unsigned)iov[0].iov_len);
1352 if ((got = recvmsg(s, &msg, MSG_WAITALL)) != iov[0].iov_len) {
1354 log_Printf(LogERROR, "Failed recvmsg: %s\n", strerror(errno));
1356 log_Printf(LogERROR, "Failed recvmsg: Got %d, not %u\n",
1357 got, (unsigned)iov[0].iov_len);
1359 free(iov[niov].iov_base);
1363 if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) {
1364 log_Printf(LogERROR, "Recvmsg: no descriptors received !\n");
1366 free(iov[niov].iov_base);
1370 fd = (int *)CMSG_DATA(cmsg);
1371 nfd = ((caddr_t)cmsg + cmsg->cmsg_len - (caddr_t)fd) / sizeof(int);
1374 log_Printf(LogERROR, "Recvmsg: %d descriptor%s received (too few) !\n",
1375 nfd, nfd == 1 ? "" : "s");
1379 free(iov[niov].iov_base);
1384 * We've successfully received two or more open file descriptors
1385 * through our socket, plus a version string. Make sure it's the
1386 * correct version, and drop the connection if it's not.
1388 if (strncmp(Version, iov[0].iov_base, iov[0].iov_len)) {
1389 log_Printf(LogWARN, "Cannot receive datalink, incorrect version"
1390 " (\"%.*s\", not \"%s\")\n", (int)iov[0].iov_len,
1391 (char *)iov[0].iov_base, Version);
1395 free(iov[niov].iov_base);
1400 * Everything looks good. Send the other side our process id so that
1401 * they can transfer lock ownership, and wait for them to send the
1405 if ((got = write(fd[1], &pid, sizeof pid)) != sizeof pid) {
1407 log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1409 log_Printf(LogERROR, "Failed write: Got %d, not %d\n", got,
1414 free(iov[niov].iov_base);
1418 if ((got = readv(fd[1], iov + 1, niov - 1)) != expect) {
1420 log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1422 log_Printf(LogERROR, "Failed write: Got %d, not %d\n", got, expect);
1426 free(iov[niov].iov_base);
1431 onfd = nfd; /* We've got this many in our array */
1432 nfd -= 2; /* Don't include p->fd and our reply descriptor */
1433 niov = 1; /* Skip the version id */
1434 dl = iov2datalink(bundle, iov, &niov, sizeof iov / sizeof *iov, fd[0],
1439 log_Printf(LogERROR, "bundle_ReceiveDatalink: Failed to handle %d "
1440 "auxiliary file descriptors (%d remain)\n", onfd, nfd);
1441 datalink_Destroy(dl);
1446 bundle_DatalinkLinkin(bundle, dl);
1447 datalink_AuthOk(dl);
1448 bundle_CalculateBandwidth(dl->bundle);
1457 free(iov[0].iov_base);
1461 bundle_SendDatalink(struct datalink *dl, int s, struct sockaddr_un *sun)
1463 char cmsgbuf[CMSG_SPACE(sizeof(int) * SEND_MAXFD)];
1464 const char *constlock;
1466 struct cmsghdr *cmsg;
1468 struct iovec iov[SCATTER_SEGMENTS];
1469 int niov, f, expect, newsid, fd[SEND_MAXFD], nfd, reply[2], got;
1472 log_Printf(LogPHASE, "Transmitting datalink %s\n", dl->name);
1474 /* Record the base device name for a lock transfer later */
1475 constlock = physical_LockedDevice(dl->physical);
1477 lock = alloca(strlen(constlock) + 1);
1478 strcpy(lock, constlock);
1482 bundle_LinkClosed(dl->bundle, dl);
1483 bundle_DatalinkLinkout(dl->bundle, dl);
1485 /* Build our scatter/gather array */
1486 iov[0].iov_len = strlen(Version) + 1;
1487 iov[0].iov_base = strdup(Version);
1491 fd[0] = datalink2iov(dl, iov, &niov, SCATTER_SEGMENTS, fd + 2, &nfd);
1493 if (fd[0] != -1 && socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, reply) != -1) {
1495 * fd[1] is used to get the peer process id back, then to confirm that
1496 * we've transferred any device locks to that process id.
1500 nfd += 2; /* Include fd[0] and fd[1] */
1501 memset(&msg, '\0', sizeof msg);
1503 msg.msg_name = NULL;
1504 msg.msg_namelen = 0;
1506 * Only send the version to start... We used to send the whole lot, but
1507 * this caused problems with our RECVBUF size as a single link is about
1508 * 22k ! This way, we should bump into no limits.
1512 msg.msg_control = cmsgbuf;
1513 msg.msg_controllen = CMSG_SPACE(sizeof(int) * nfd);
1516 cmsg = (struct cmsghdr *)cmsgbuf;
1517 cmsg->cmsg_len = msg.msg_controllen;
1518 cmsg->cmsg_level = SOL_SOCKET;
1519 cmsg->cmsg_type = SCM_RIGHTS;
1521 for (f = 0; f < nfd; f++)
1522 *((int *)CMSG_DATA(cmsg) + f) = fd[f];
1524 for (f = 1, expect = 0; f < niov; f++)
1525 expect += iov[f].iov_len;
1527 if (setsockopt(reply[0], SOL_SOCKET, SO_SNDBUF, &expect, sizeof(int)) == -1)
1528 log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1530 if (setsockopt(reply[1], SOL_SOCKET, SO_RCVBUF, &expect, sizeof(int)) == -1)
1531 log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1534 log_Printf(LogDEBUG, "Sending %d descriptor%s and %u bytes in scatter"
1535 "/gather array\n", nfd, nfd == 1 ? "" : "s",
1536 (unsigned)iov[0].iov_len);
1538 if ((got = sendmsg(s, &msg, 0)) == -1)
1539 log_Printf(LogERROR, "Failed sendmsg: %s: %s\n",
1540 sun->sun_path, strerror(errno));
1541 else if (got != iov[0].iov_len)
1542 log_Printf(LogERROR, "%s: Failed initial sendmsg: Only sent %d of %u\n",
1543 sun->sun_path, got, (unsigned)iov[0].iov_len);
1545 /* We must get the ACK before closing the descriptor ! */
1548 if ((got = read(reply[0], &newpid, sizeof newpid)) == sizeof newpid) {
1549 log_Printf(LogDEBUG, "Received confirmation from pid %d\n",
1551 if (lock && (res = ID0uu_lock_txfr(lock, newpid)) != UU_LOCK_OK)
1552 log_Printf(LogERROR, "uu_lock_txfr: %s\n", uu_lockerr(res));
1554 log_Printf(LogDEBUG, "Transmitting link (%d bytes)\n", expect);
1555 if ((got = writev(reply[0], iov + 1, niov - 1)) != expect) {
1557 log_Printf(LogERROR, "%s: Failed writev: %s\n",
1558 sun->sun_path, strerror(errno));
1560 log_Printf(LogERROR, "%s: Failed writev: Wrote %d of %d\n",
1561 sun->sun_path, got, expect);
1563 } else if (got == -1)
1564 log_Printf(LogERROR, "%s: Failed socketpair read: %s\n",
1565 sun->sun_path, strerror(errno));
1567 log_Printf(LogERROR, "%s: Failed socketpair read: Got %d of %d\n",
1568 sun->sun_path, got, (int)(sizeof newpid));
1574 newsid = Enabled(dl->bundle, OPT_KEEPSESSION) ||
1575 tcgetpgrp(fd[0]) == getpgrp();
1579 bundle_setsid(dl->bundle, got != -1);
1584 free(iov[niov].iov_base);
1588 bundle_RenameDatalink(struct bundle *bundle, struct datalink *ndl,
1591 struct datalink *dl;
1593 if (!strcasecmp(ndl->name, name))
1596 for (dl = bundle->links; dl; dl = dl->next)
1597 if (!strcasecmp(dl->name, name))
1600 datalink_Rename(ndl, name);
1605 bundle_SetMode(struct bundle *bundle, struct datalink *dl, int mode)
1609 omode = dl->physical->type;
1613 if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO))
1614 /* First auto link */
1615 if (bundle->ncp.ipcp.peer_ip.s_addr == INADDR_ANY) {
1616 log_Printf(LogWARN, "You must `set ifaddr' or `open' before"
1617 " changing mode to %s\n", mode2Nam(mode));
1621 if (!datalink_SetMode(dl, mode))
1624 if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO) &&
1625 bundle->phase != PHASE_NETWORK)
1626 /* First auto link, we need an interface */
1627 ipcp_InterfaceUp(&bundle->ncp.ipcp);
1629 /* Regenerate phys_type and adjust idle timer */
1630 bundle_LinksRemoved(bundle);
1636 bundle_setsid(struct bundle *bundle, int holdsession)
1639 * Lose the current session. This means getting rid of our pid
1640 * too so that the tty device will really go away, and any getty
1641 * etc will be allowed to restart.
1646 struct datalink *dl;
1648 if (!holdsession && bundle_IsDead(bundle)) {
1650 * No need to lose our session after all... we're going away anyway
1652 * We should really stop the timer and pause if holdsession is set and
1653 * the bundle's dead, but that leaves other resources lying about :-(
1659 if (pipe(fds) == -1) {
1660 log_Printf(LogERROR, "pipe: %s\n", strerror(errno));
1663 switch ((pid = fork())) {
1665 log_Printf(LogERROR, "fork: %s\n", strerror(errno));
1671 read(fds[0], &done, 1); /* uu_locks are mine ! */
1673 if (pipe(fds) == -1) {
1674 log_Printf(LogERROR, "pipe(2): %s\n", strerror(errno));
1677 switch ((pid = fork())) {
1679 log_Printf(LogERROR, "fork(2): %s\n", strerror(errno));
1685 bundle_LockTun(bundle); /* update pid */
1686 read(fds[0], &done, 1); /* uu_locks are mine ! */
1689 bundle_ChangedPID(bundle);
1690 log_Printf(LogDEBUG, "%d -> %d: %s session control\n",
1691 (int)orig, (int)getpid(),
1692 holdsession ? "Passed" : "Dropped");
1693 timer_InitService(0); /* Start the Timer Service */
1697 /* Give away all our physical locks (to the final process) */
1698 for (dl = bundle->links; dl; dl = dl->next)
1699 if (dl->state != DATALINK_CLOSED)
1700 physical_ChangedPid(dl->physical, pid);
1701 write(fds[1], "!", 1); /* done */
1709 /* Give away all our physical locks (to the intermediate process) */
1710 for (dl = bundle->links; dl; dl = dl->next)
1711 if (dl->state != DATALINK_CLOSED)
1712 physical_ChangedPid(dl->physical, pid);
1713 write(fds[1], "!", 1); /* done */
1718 timer_TermService();
1719 signal(SIGPIPE, SIG_DFL);
1720 signal(SIGALRM, SIG_DFL);
1721 signal(SIGHUP, SIG_DFL);
1722 signal(SIGTERM, SIG_DFL);
1723 signal(SIGINT, SIG_DFL);
1724 signal(SIGQUIT, SIG_DFL);
1725 for (fd = getdtablesize(); fd >= 0; fd--)
1728 * Reap the intermediate process. As we're not exiting but the
1729 * intermediate is, we don't want it to become defunct.
1731 waitpid(pid, &status, 0);
1732 /* Tweak our process arguments.... */
1733 SetTitle("session owner");
1735 setuid(ID0realuid());
1738 * Hang around for a HUP. This should happen as soon as the
1739 * ppp that we passed our ctty descriptor to closes it.
1740 * NOTE: If this process dies, the passed descriptor becomes
1741 * invalid and will give a select() error by setting one
1742 * of the error fds, aborting the other ppp. We don't
1743 * want that to happen !
1753 bundle_HighestState(struct bundle *bundle)
1755 struct datalink *dl;
1756 int result = DATALINK_CLOSED;
1758 for (dl = bundle->links; dl; dl = dl->next)
1759 if (result < dl->state)
1766 bundle_Exception(struct bundle *bundle, int fd)
1768 struct datalink *dl;
1770 for (dl = bundle->links; dl; dl = dl->next)
1771 if (dl->physical->fd == fd) {
1772 datalink_Down(dl, CLOSE_NORMAL);
1780 bundle_AdjustFilters(struct bundle *bundle, struct ncpaddr *local,
1781 struct ncpaddr *remote)
1783 filter_AdjustAddr(&bundle->filter.in, local, remote, NULL);
1784 filter_AdjustAddr(&bundle->filter.out, local, remote, NULL);
1785 filter_AdjustAddr(&bundle->filter.dial, local, remote, NULL);
1786 filter_AdjustAddr(&bundle->filter.alive, local, remote, NULL);
1790 bundle_AdjustDNS(struct bundle *bundle)
1792 struct in_addr *dns = bundle->ncp.ipcp.ns.dns;
1794 filter_AdjustAddr(&bundle->filter.in, NULL, NULL, dns);
1795 filter_AdjustAddr(&bundle->filter.out, NULL, NULL, dns);
1796 filter_AdjustAddr(&bundle->filter.dial, NULL, NULL, dns);
1797 filter_AdjustAddr(&bundle->filter.alive, NULL, NULL, dns);
1801 bundle_CalculateBandwidth(struct bundle *bundle)
1803 struct datalink *dl;
1804 int sp, overhead, maxoverhead;
1806 bundle->bandwidth = 0;
1807 bundle->iface->mtu = 0;
1810 for (dl = bundle->links; dl; dl = dl->next) {
1811 overhead = ccp_MTUOverhead(&dl->physical->link.ccp);
1812 if (maxoverhead < overhead)
1813 maxoverhead = overhead;
1814 if (dl->state == DATALINK_OPEN) {
1815 if ((sp = dl->mp.bandwidth) == 0 &&
1816 (sp = physical_GetSpeed(dl->physical)) == 0)
1817 log_Printf(LogDEBUG, "%s: %s: Cannot determine bandwidth\n",
1818 dl->name, dl->physical->name.full);
1820 bundle->bandwidth += sp;
1821 if (!bundle->ncp.mp.active) {
1822 bundle->iface->mtu = dl->physical->link.lcp.his_mru;
1828 if(bundle->bandwidth == 0)
1829 bundle->bandwidth = 115200; /* Shrug */
1831 if (bundle->ncp.mp.active) {
1832 bundle->iface->mtu = bundle->ncp.mp.peer_mrru;
1833 overhead = ccp_MTUOverhead(&bundle->ncp.mp.link.ccp);
1834 if (maxoverhead < overhead)
1835 maxoverhead = overhead;
1836 } else if (!bundle->iface->mtu)
1837 bundle->iface->mtu = DEF_MRU;
1840 if (bundle->radius.valid && bundle->radius.mtu &&
1841 bundle->radius.mtu < bundle->iface->mtu) {
1842 log_Printf(LogLCP, "Reducing MTU to radius value %lu\n",
1843 bundle->radius.mtu);
1844 bundle->iface->mtu = bundle->radius.mtu;
1849 log_Printf(LogLCP, "Reducing MTU from %d to %d (CCP requirement)\n",
1850 bundle->iface->mtu, bundle->iface->mtu - maxoverhead);
1851 bundle->iface->mtu -= maxoverhead;
1854 tun_configure(bundle);
1856 route_UpdateMTU(bundle);
1860 bundle_AutoAdjust(struct bundle *bundle, int percent, int what)
1862 struct datalink *dl, *choice, *otherlinkup;
1864 choice = otherlinkup = NULL;
1865 for (dl = bundle->links; dl; dl = dl->next)
1866 if (dl->physical->type == PHYS_AUTO) {
1867 if (dl->state == DATALINK_OPEN) {
1868 if (what == AUTO_DOWN) {
1870 otherlinkup = choice;
1873 } else if (dl->state == DATALINK_CLOSED) {
1874 if (what == AUTO_UP) {
1879 /* An auto link in an intermediate state - forget it for the moment */
1883 } else if (dl->state == DATALINK_OPEN && what == AUTO_DOWN)
1887 if (what == AUTO_UP) {
1888 log_Printf(LogPHASE, "%d%% saturation -> Opening link ``%s''\n",
1889 percent, choice->name);
1890 datalink_Up(choice, 1, 1);
1891 mp_CheckAutoloadTimer(&bundle->ncp.mp);
1892 } else if (otherlinkup) { /* Only bring the second-last link down */
1893 log_Printf(LogPHASE, "%d%% saturation -> Closing link ``%s''\n",
1894 percent, choice->name);
1895 datalink_Close(choice, CLOSE_STAYDOWN);
1896 mp_CheckAutoloadTimer(&bundle->ncp.mp);
1902 bundle_WantAutoloadTimer(struct bundle *bundle)
1904 struct datalink *dl;
1905 int autolink, opened;
1907 if (bundle->phase == PHASE_NETWORK) {
1908 for (autolink = opened = 0, dl = bundle->links; dl; dl = dl->next)
1909 if (dl->physical->type == PHYS_AUTO) {
1910 if (++autolink == 2 || (autolink == 1 && opened))
1911 /* Two auto links or one auto and one open in NETWORK phase */
1913 } else if (dl->state == DATALINK_OPEN) {
1916 /* One auto and one open link in NETWORK phase */
1925 bundle_ChangedPID(struct bundle *bundle)
1928 ioctl(bundle->dev.fd, TUNSIFPID, 0);
1933 bundle_Uptime(struct bundle *bundle)
1936 return time(NULL) - bundle->upat;