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 loadmodules(LOAD_VERBOSLY, "if_tun", NULL);
718 if (errno != ENOENT || ++enoentcount > 2) {
726 if (bundle.dev.fd < 0) {
728 log_Printf(LogWARN, "No available tunnel devices found (%s)\n",
731 log_Printf(LogWARN, "%s%d: %s\n", prefix, unit, strerror(err));
735 log_SetTun(bundle.unit);
737 ifname = strrchr(bundle.dev.Name, '/');
739 ifname = bundle.dev.Name;
743 bundle.iface = iface_Create(ifname);
744 if (bundle.iface == NULL) {
745 close(bundle.dev.fd);
750 /* Make sure we're POINTOPOINT & IFF_MULTICAST */
751 iff = IFF_POINTOPOINT | IFF_MULTICAST;
752 if (ID0ioctl(bundle.dev.fd, TUNSIFMODE, &iff) < 0)
753 log_Printf(LogERROR, "bundle_Create: ioctl(TUNSIFMODE): %s\n",
758 /* Make sure we're not prepending sockaddrs */
760 if (ID0ioctl(bundle.dev.fd, TUNSLMODE, &iff) < 0)
761 log_Printf(LogERROR, "bundle_Create: ioctl(TUNSLMODE): %s\n",
766 /* We want the address family please ! */
768 if (ID0ioctl(bundle.dev.fd, TUNSIFHEAD, &iff) < 0) {
769 log_Printf(LogERROR, "bundle_Create: ioctl(TUNSIFHEAD): %s\n",
771 bundle.dev.header = 0;
773 bundle.dev.header = 1;
776 /* Always present for OpenBSD */
777 bundle.dev.header = 1;
780 * If TUNSIFHEAD isn't available and we're not OpenBSD, assume
781 * everything's AF_INET (hopefully the tun device won't pass us
784 bundle.dev.header = 0;
788 log_Printf(LogPHASE, "Using interface: %s\n", ifname);
790 bundle.bandwidth = 0;
791 bundle.routing_seq = 0;
792 bundle.phase = PHASE_DEAD;
793 bundle.CleaningUp = 0;
794 bundle.NatEnabled = 0;
796 bundle.fsm.LayerStart = bundle_LayerStart;
797 bundle.fsm.LayerUp = bundle_LayerUp;
798 bundle.fsm.LayerDown = bundle_LayerDown;
799 bundle.fsm.LayerFinish = bundle_LayerFinish;
800 bundle.fsm.object = &bundle;
802 bundle.cfg.idle.timeout = NCP_IDLE_TIMEOUT;
803 bundle.cfg.idle.min_timeout = 0;
804 *bundle.cfg.auth.name = '\0';
805 *bundle.cfg.auth.key = '\0';
806 bundle.cfg.opt = OPT_IDCHECK | OPT_LOOPBACK | OPT_SROUTES | OPT_TCPMSSFIXUP |
807 OPT_THROUGHPUT | OPT_UTMP;
809 bundle.cfg.opt |= OPT_IPCP;
810 if (probe.ipv6_available)
811 bundle.cfg.opt |= OPT_IPV6CP;
813 *bundle.cfg.label = '\0';
814 bundle.cfg.ifqueue = DEF_IFQUEUE;
815 bundle.cfg.choked.timeout = CHOKED_TIMEOUT;
816 bundle.phys_type.all = type;
817 bundle.phys_type.open = 0;
820 bundle.links = datalink_Create("deflink", &bundle, type);
821 if (bundle.links == NULL) {
822 log_Printf(LogALERT, "Cannot create data link: %s\n", strerror(errno));
823 iface_Destroy(bundle.iface);
825 close(bundle.dev.fd);
829 bundle.desc.type = BUNDLE_DESCRIPTOR;
830 bundle.desc.UpdateSet = bundle_UpdateSet;
831 bundle.desc.IsSet = bundle_IsSet;
832 bundle.desc.Read = bundle_DescriptorRead;
833 bundle.desc.Write = bundle_DescriptorWrite;
835 ncp_Init(&bundle.ncp, &bundle);
837 memset(&bundle.filter, '\0', sizeof bundle.filter);
838 bundle.filter.in.fragok = bundle.filter.in.logok = 1;
839 bundle.filter.in.name = "IN";
840 bundle.filter.out.fragok = bundle.filter.out.logok = 1;
841 bundle.filter.out.name = "OUT";
842 bundle.filter.dial.name = "DIAL";
843 bundle.filter.dial.logok = 1;
844 bundle.filter.alive.name = "ALIVE";
845 bundle.filter.alive.logok = 1;
848 for (i = 0; i < MAXFILTERS; i++) {
849 bundle.filter.in.rule[i].f_action = A_NONE;
850 bundle.filter.out.rule[i].f_action = A_NONE;
851 bundle.filter.dial.rule[i].f_action = A_NONE;
852 bundle.filter.alive.rule[i].f_action = A_NONE;
855 memset(&bundle.idle.timer, '\0', sizeof bundle.idle.timer);
856 bundle.idle.done = 0;
857 bundle.notify.fd = -1;
858 memset(&bundle.choked.timer, '\0', sizeof bundle.choked.timer);
860 radius_Init(&bundle.radius);
863 /* Clean out any leftover crud */
864 iface_Clear(bundle.iface, &bundle.ncp, 0, IFACE_CLEAR_ALL);
866 bundle_LockTun(&bundle);
872 bundle_DownInterface(struct bundle *bundle)
874 route_IfDelete(bundle, 1);
875 iface_ClearFlags(bundle->iface->name, IFF_UP);
879 bundle_Destroy(struct bundle *bundle)
884 * Clean up the interface. We don't really need to do the timer_Stop()s,
885 * mp_Down(), iface_Clear() and bundle_DownInterface() unless we're getting
886 * out under exceptional conditions such as a descriptor exception.
888 timer_Stop(&bundle->idle.timer);
889 timer_Stop(&bundle->choked.timer);
890 mp_Down(&bundle->ncp.mp);
891 iface_Clear(bundle->iface, &bundle->ncp, 0, IFACE_CLEAR_ALL);
892 bundle_DownInterface(bundle);
895 /* Tell the radius server the bad news */
896 radius_Destroy(&bundle->radius);
899 /* Again, these are all DATALINK_CLOSED unless we're abending */
902 dl = datalink_Destroy(dl);
904 ncp_Destroy(&bundle->ncp);
906 close(bundle->dev.fd);
907 bundle_UnlockTun(bundle);
909 /* In case we never made PHASE_NETWORK */
910 bundle_Notify(bundle, EX_ERRDEAD);
912 iface_Destroy(bundle->iface);
913 bundle->iface = NULL;
917 bundle_LinkClosed(struct bundle *bundle, struct datalink *dl)
920 * Our datalink has closed.
921 * CleanDatalinks() (called from DoLoop()) will remove closed
922 * BACKGROUND, FOREGROUND and DIRECT links.
923 * If it's the last data link, enter phase DEAD.
925 * NOTE: dl may not be in our list (bundle_SendDatalink()) !
928 struct datalink *odl;
931 log_SetTtyCommandMode(dl);
934 for (odl = bundle->links; odl; odl = odl->next)
935 if (odl != dl && odl->state != DATALINK_CLOSED)
939 if (dl->physical->type != PHYS_AUTO) /* Not in -auto mode */
940 bundle_DownInterface(bundle);
941 ncp2initial(&bundle->ncp);
942 mp_Down(&bundle->ncp.mp);
943 bundle_NewPhase(bundle, PHASE_DEAD);
944 bundle_StopIdleTimer(bundle);
949 bundle_Open(struct bundle *bundle, const char *name, int mask, int force)
952 * Please open the given datalink, or all if name == NULL
956 for (dl = bundle->links; dl; dl = dl->next)
957 if (name == NULL || !strcasecmp(dl->name, name)) {
958 if ((mask & dl->physical->type) &&
959 (dl->state == DATALINK_CLOSED ||
960 (force && dl->state == DATALINK_OPENING &&
961 dl->dial.timer.state == TIMER_RUNNING) ||
962 dl->state == DATALINK_READY)) {
963 timer_Stop(&dl->dial.timer); /* We're finished with this */
964 datalink_Up(dl, 1, 1);
965 if (mask & PHYS_AUTO)
966 break; /* Only one AUTO link at a time */
974 bundle2datalink(struct bundle *bundle, const char *name)
979 for (dl = bundle->links; dl; dl = dl->next)
980 if (!strcasecmp(dl->name, name))
982 } else if (bundle->links && !bundle->links->next)
983 return bundle->links;
989 bundle_ShowLinks(struct cmdargs const *arg)
992 struct pppThroughput *t;
993 unsigned long long octets;
996 for (dl = arg->bundle->links; dl; dl = dl->next) {
997 octets = MAX(dl->physical->link.stats.total.in.OctetsPerSecond,
998 dl->physical->link.stats.total.out.OctetsPerSecond);
1000 prompt_Printf(arg->prompt, "Name: %s [%s, %s]",
1001 dl->name, mode2Nam(dl->physical->type), datalink_State(dl));
1002 if (dl->physical->link.stats.total.rolling && dl->state == DATALINK_OPEN)
1003 prompt_Printf(arg->prompt, " bandwidth %d, %llu bps (%llu bytes/sec)",
1004 dl->mp.bandwidth ? dl->mp.bandwidth :
1005 physical_GetSpeed(dl->physical),
1006 octets * 8, octets);
1007 prompt_Printf(arg->prompt, "\n");
1010 t = &arg->bundle->ncp.mp.link.stats.total;
1011 octets = MAX(t->in.OctetsPerSecond, t->out.OctetsPerSecond);
1012 secs = t->downtime ? 0 : throughput_uptime(t);
1013 if (secs > t->SamplePeriod)
1014 secs = t->SamplePeriod;
1016 prompt_Printf(arg->prompt, "Currently averaging %llu bps (%llu bytes/sec)"
1017 " over the last %d secs\n", octets * 8, octets, secs);
1023 optval(struct bundle *bundle, int bit)
1025 return (bundle->cfg.opt & bit) ? "enabled" : "disabled";
1029 bundle_ShowStatus(struct cmdargs const *arg)
1033 prompt_Printf(arg->prompt, "Phase %s\n", bundle_PhaseName(arg->bundle));
1034 prompt_Printf(arg->prompt, " Device: %s\n", arg->bundle->dev.Name);
1035 prompt_Printf(arg->prompt, " Interface: %s @ %lubps",
1036 arg->bundle->iface->name, arg->bundle->bandwidth);
1038 if (arg->bundle->upat) {
1039 int secs = bundle_Uptime(arg->bundle);
1041 prompt_Printf(arg->prompt, ", up time %d:%02d:%02d", secs / 3600,
1042 (secs / 60) % 60, secs % 60);
1044 prompt_Printf(arg->prompt, "\n Queued: %lu of %u\n",
1045 (unsigned long)ncp_QueueLen(&arg->bundle->ncp),
1046 arg->bundle->cfg.ifqueue);
1048 prompt_Printf(arg->prompt, "\nDefaults:\n");
1049 prompt_Printf(arg->prompt, " Label: %s\n",
1050 arg->bundle->cfg.label);
1051 prompt_Printf(arg->prompt, " Auth name: %s\n",
1052 arg->bundle->cfg.auth.name);
1053 prompt_Printf(arg->prompt, " Diagnostic socket: ");
1054 if (*server.cfg.sockname != '\0') {
1055 prompt_Printf(arg->prompt, "%s", server.cfg.sockname);
1056 if (server.cfg.mask != (mode_t)-1)
1057 prompt_Printf(arg->prompt, ", mask 0%03o", (int)server.cfg.mask);
1058 prompt_Printf(arg->prompt, "%s\n", server.fd == -1 ? " (not open)" : "");
1059 } else if (server.cfg.port != 0)
1060 prompt_Printf(arg->prompt, "TCP port %d%s\n", server.cfg.port,
1061 server.fd == -1 ? " (not open)" : "");
1063 prompt_Printf(arg->prompt, "none\n");
1065 prompt_Printf(arg->prompt, " Choked Timer: %ds\n",
1066 arg->bundle->cfg.choked.timeout);
1069 radius_Show(&arg->bundle->radius, arg->prompt);
1072 prompt_Printf(arg->prompt, " Idle Timer: ");
1073 if (arg->bundle->cfg.idle.timeout) {
1074 prompt_Printf(arg->prompt, "%ds", arg->bundle->cfg.idle.timeout);
1075 if (arg->bundle->cfg.idle.min_timeout)
1076 prompt_Printf(arg->prompt, ", min %ds",
1077 arg->bundle->cfg.idle.min_timeout);
1078 remaining = bundle_RemainingIdleTime(arg->bundle);
1079 if (remaining != -1)
1080 prompt_Printf(arg->prompt, " (%ds remaining)", remaining);
1081 prompt_Printf(arg->prompt, "\n");
1083 prompt_Printf(arg->prompt, "disabled\n");
1085 prompt_Printf(arg->prompt, " Filter Decap: %-20.20s",
1086 optval(arg->bundle, OPT_FILTERDECAP));
1087 prompt_Printf(arg->prompt, " ID check: %s\n",
1088 optval(arg->bundle, OPT_IDCHECK));
1089 prompt_Printf(arg->prompt, " Iface-Alias: %-20.20s",
1090 optval(arg->bundle, OPT_IFACEALIAS));
1092 prompt_Printf(arg->prompt, " IPCP: %s\n",
1093 optval(arg->bundle, OPT_IPCP));
1094 prompt_Printf(arg->prompt, " IPV6CP: %-20.20s",
1095 optval(arg->bundle, OPT_IPV6CP));
1097 prompt_Printf(arg->prompt, " Keep-Session: %s\n",
1098 optval(arg->bundle, OPT_KEEPSESSION));
1099 prompt_Printf(arg->prompt, " Loopback: %-20.20s",
1100 optval(arg->bundle, OPT_LOOPBACK));
1101 prompt_Printf(arg->prompt, " PasswdAuth: %s\n",
1102 optval(arg->bundle, OPT_PASSWDAUTH));
1103 prompt_Printf(arg->prompt, " Proxy: %-20.20s",
1104 optval(arg->bundle, OPT_PROXY));
1105 prompt_Printf(arg->prompt, " Proxyall: %s\n",
1106 optval(arg->bundle, OPT_PROXYALL));
1107 prompt_Printf(arg->prompt, " Sticky Routes: %-20.20s",
1108 optval(arg->bundle, OPT_SROUTES));
1109 prompt_Printf(arg->prompt, " TCPMSS Fixup: %s\n",
1110 optval(arg->bundle, OPT_TCPMSSFIXUP));
1111 prompt_Printf(arg->prompt, " Throughput: %-20.20s",
1112 optval(arg->bundle, OPT_THROUGHPUT));
1113 prompt_Printf(arg->prompt, " Utmp Logging: %s\n",
1114 optval(arg->bundle, OPT_UTMP));
1120 bundle_IdleTimeout(void *v)
1122 struct bundle *bundle = (struct bundle *)v;
1124 log_Printf(LogPHASE, "Idle timer expired\n");
1125 bundle_StopIdleTimer(bundle);
1126 bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
1130 * Start Idle timer. If timeout is reached, we call bundle_Close() to
1131 * close LCP and link.
1134 bundle_StartIdleTimer(struct bundle *bundle, unsigned secs)
1136 timer_Stop(&bundle->idle.timer);
1137 if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) !=
1138 bundle->phys_type.open && bundle->cfg.idle.timeout) {
1139 time_t now = time(NULL);
1142 secs = bundle->cfg.idle.timeout;
1144 /* We want at least `secs' */
1145 if (bundle->cfg.idle.min_timeout > secs && bundle->upat) {
1146 int up = now - bundle->upat;
1148 if ((long long)bundle->cfg.idle.min_timeout - up > (long long)secs)
1149 /* Only increase from the current `remaining' value */
1150 secs = bundle->cfg.idle.min_timeout - up;
1152 bundle->idle.timer.func = bundle_IdleTimeout;
1153 bundle->idle.timer.name = "idle";
1154 bundle->idle.timer.load = secs * SECTICKS;
1155 bundle->idle.timer.arg = bundle;
1156 timer_Start(&bundle->idle.timer);
1157 bundle->idle.done = now + secs;
1162 bundle_SetIdleTimer(struct bundle *bundle, int timeout, int min_timeout)
1164 bundle->cfg.idle.timeout = timeout;
1165 if (min_timeout >= 0)
1166 bundle->cfg.idle.min_timeout = min_timeout;
1167 if (ncp_LayersOpen(&bundle->ncp))
1168 bundle_StartIdleTimer(bundle, 0);
1172 bundle_StopIdleTimer(struct bundle *bundle)
1174 timer_Stop(&bundle->idle.timer);
1175 bundle->idle.done = 0;
1179 bundle_RemainingIdleTime(struct bundle *bundle)
1181 if (bundle->idle.done)
1182 return bundle->idle.done - time(NULL);
1187 bundle_IsDead(struct bundle *bundle)
1189 return !bundle->links || (bundle->phase == PHASE_DEAD && bundle->CleaningUp);
1192 static struct datalink *
1193 bundle_DatalinkLinkout(struct bundle *bundle, struct datalink *dl)
1195 struct datalink **dlp;
1197 for (dlp = &bundle->links; *dlp; dlp = &(*dlp)->next)
1201 bundle_LinksRemoved(bundle);
1209 bundle_DatalinkLinkin(struct bundle *bundle, struct datalink *dl)
1211 struct datalink **dlp = &bundle->links;
1214 dlp = &(*dlp)->next;
1219 bundle_LinkAdded(bundle, dl);
1220 mp_CheckAutoloadTimer(&bundle->ncp.mp);
1224 bundle_CleanDatalinks(struct bundle *bundle)
1226 struct datalink **dlp = &bundle->links;
1230 if ((*dlp)->state == DATALINK_CLOSED &&
1231 (*dlp)->physical->type &
1232 (PHYS_DIRECT|PHYS_BACKGROUND|PHYS_FOREGROUND)) {
1233 *dlp = datalink_Destroy(*dlp);
1236 dlp = &(*dlp)->next;
1239 bundle_LinksRemoved(bundle);
1243 bundle_DatalinkClone(struct bundle *bundle, struct datalink *dl,
1246 if (bundle2datalink(bundle, name)) {
1247 log_Printf(LogWARN, "Clone: %s: name already exists\n", name);
1251 bundle_DatalinkLinkin(bundle, datalink_Clone(dl, name));
1256 bundle_DatalinkRemove(struct bundle *bundle, struct datalink *dl)
1258 dl = bundle_DatalinkLinkout(bundle, dl);
1260 datalink_Destroy(dl);
1264 bundle_SetLabel(struct bundle *bundle, const char *label)
1267 strncpy(bundle->cfg.label, label, sizeof bundle->cfg.label - 1);
1269 *bundle->cfg.label = '\0';
1273 bundle_GetLabel(struct bundle *bundle)
1275 return *bundle->cfg.label ? bundle->cfg.label : NULL;
1281 struct iovec iov[SCATTER_SEGMENTS];
1282 int niov, expect, f;
1284 iov[0].iov_len = strlen(Version) + 1;
1285 iov[0].iov_base = NULL;
1287 if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1288 log_Printf(LogERROR, "Cannot determine space required for link\n");
1292 for (f = expect = 0; f < niov; f++)
1293 expect += iov[f].iov_len;
1299 bundle_ReceiveDatalink(struct bundle *bundle, int s)
1301 char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int) * SEND_MAXFD];
1302 int niov, expect, f, *fd, nfd, onfd, got;
1303 struct iovec iov[SCATTER_SEGMENTS];
1304 struct cmsghdr *cmsg;
1306 struct datalink *dl;
1309 log_Printf(LogPHASE, "Receiving datalink\n");
1312 * Create our scatter/gather array - passing NULL gets the space
1313 * allocation requirement rather than actually flattening the
1316 iov[0].iov_len = strlen(Version) + 1;
1317 iov[0].iov_base = NULL;
1319 if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1320 log_Printf(LogERROR, "Cannot determine space required for link\n");
1324 /* Allocate the scatter/gather array for recvmsg() */
1325 for (f = expect = 0; f < niov; f++) {
1326 if ((iov[f].iov_base = malloc(iov[f].iov_len)) == NULL) {
1327 log_Printf(LogERROR, "Cannot allocate space to receive link\n");
1331 expect += iov[f].iov_len;
1334 /* Set up our message */
1335 cmsg = (struct cmsghdr *)cmsgbuf;
1336 cmsg->cmsg_len = sizeof cmsgbuf;
1337 cmsg->cmsg_level = SOL_SOCKET;
1338 cmsg->cmsg_type = 0;
1340 memset(&msg, '\0', sizeof msg);
1341 msg.msg_name = NULL;
1342 msg.msg_namelen = 0;
1344 msg.msg_iovlen = 1; /* Only send the version at the first pass */
1345 msg.msg_control = cmsgbuf;
1346 msg.msg_controllen = sizeof cmsgbuf;
1348 log_Printf(LogDEBUG, "Expecting %u scatter/gather bytes\n",
1349 (unsigned)iov[0].iov_len);
1351 if ((got = recvmsg(s, &msg, MSG_WAITALL)) != iov[0].iov_len) {
1353 log_Printf(LogERROR, "Failed recvmsg: %s\n", strerror(errno));
1355 log_Printf(LogERROR, "Failed recvmsg: Got %d, not %u\n",
1356 got, (unsigned)iov[0].iov_len);
1358 free(iov[niov].iov_base);
1362 if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) {
1363 log_Printf(LogERROR, "Recvmsg: no descriptors received !\n");
1365 free(iov[niov].iov_base);
1369 fd = (int *)CMSG_DATA(cmsg);
1370 nfd = ((caddr_t)cmsg + cmsg->cmsg_len - (caddr_t)fd) / sizeof(int);
1373 log_Printf(LogERROR, "Recvmsg: %d descriptor%s received (too few) !\n",
1374 nfd, nfd == 1 ? "" : "s");
1378 free(iov[niov].iov_base);
1383 * We've successfully received two or more open file descriptors
1384 * through our socket, plus a version string. Make sure it's the
1385 * correct version, and drop the connection if it's not.
1387 if (strncmp(Version, iov[0].iov_base, iov[0].iov_len)) {
1388 log_Printf(LogWARN, "Cannot receive datalink, incorrect version"
1389 " (\"%.*s\", not \"%s\")\n", (int)iov[0].iov_len,
1390 (char *)iov[0].iov_base, Version);
1394 free(iov[niov].iov_base);
1399 * Everything looks good. Send the other side our process id so that
1400 * they can transfer lock ownership, and wait for them to send the
1404 if ((got = write(fd[1], &pid, sizeof pid)) != sizeof pid) {
1406 log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1408 log_Printf(LogERROR, "Failed write: Got %d, not %d\n", got,
1413 free(iov[niov].iov_base);
1417 if ((got = readv(fd[1], iov + 1, niov - 1)) != expect) {
1419 log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1421 log_Printf(LogERROR, "Failed write: Got %d, not %d\n", got, expect);
1425 free(iov[niov].iov_base);
1430 onfd = nfd; /* We've got this many in our array */
1431 nfd -= 2; /* Don't include p->fd and our reply descriptor */
1432 niov = 1; /* Skip the version id */
1433 dl = iov2datalink(bundle, iov, &niov, sizeof iov / sizeof *iov, fd[0],
1438 log_Printf(LogERROR, "bundle_ReceiveDatalink: Failed to handle %d "
1439 "auxiliary file descriptors (%d remain)\n", onfd, nfd);
1440 datalink_Destroy(dl);
1445 bundle_DatalinkLinkin(bundle, dl);
1446 datalink_AuthOk(dl);
1447 bundle_CalculateBandwidth(dl->bundle);
1456 free(iov[0].iov_base);
1460 bundle_SendDatalink(struct datalink *dl, int s, struct sockaddr_un *sun)
1462 char cmsgbuf[CMSG_SPACE(sizeof(int) * SEND_MAXFD)];
1463 const char *constlock;
1465 struct cmsghdr *cmsg;
1467 struct iovec iov[SCATTER_SEGMENTS];
1468 int niov, f, expect, newsid, fd[SEND_MAXFD], nfd, reply[2], got;
1471 log_Printf(LogPHASE, "Transmitting datalink %s\n", dl->name);
1473 /* Record the base device name for a lock transfer later */
1474 constlock = physical_LockedDevice(dl->physical);
1476 lock = alloca(strlen(constlock) + 1);
1477 strcpy(lock, constlock);
1481 bundle_LinkClosed(dl->bundle, dl);
1482 bundle_DatalinkLinkout(dl->bundle, dl);
1484 /* Build our scatter/gather array */
1485 iov[0].iov_len = strlen(Version) + 1;
1486 iov[0].iov_base = strdup(Version);
1490 fd[0] = datalink2iov(dl, iov, &niov, SCATTER_SEGMENTS, fd + 2, &nfd);
1492 if (fd[0] != -1 && socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, reply) != -1) {
1494 * fd[1] is used to get the peer process id back, then to confirm that
1495 * we've transferred any device locks to that process id.
1499 nfd += 2; /* Include fd[0] and fd[1] */
1500 memset(&msg, '\0', sizeof msg);
1502 msg.msg_name = NULL;
1503 msg.msg_namelen = 0;
1505 * Only send the version to start... We used to send the whole lot, but
1506 * this caused problems with our RECVBUF size as a single link is about
1507 * 22k ! This way, we should bump into no limits.
1511 msg.msg_control = cmsgbuf;
1512 msg.msg_controllen = CMSG_SPACE(sizeof(int) * nfd);
1515 cmsg = (struct cmsghdr *)cmsgbuf;
1516 cmsg->cmsg_len = msg.msg_controllen;
1517 cmsg->cmsg_level = SOL_SOCKET;
1518 cmsg->cmsg_type = SCM_RIGHTS;
1520 for (f = 0; f < nfd; f++)
1521 *((int *)CMSG_DATA(cmsg) + f) = fd[f];
1523 for (f = 1, expect = 0; f < niov; f++)
1524 expect += iov[f].iov_len;
1526 if (setsockopt(reply[0], SOL_SOCKET, SO_SNDBUF, &expect, sizeof(int)) == -1)
1527 log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1529 if (setsockopt(reply[1], SOL_SOCKET, SO_RCVBUF, &expect, sizeof(int)) == -1)
1530 log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1533 log_Printf(LogDEBUG, "Sending %d descriptor%s and %u bytes in scatter"
1534 "/gather array\n", nfd, nfd == 1 ? "" : "s",
1535 (unsigned)iov[0].iov_len);
1537 if ((got = sendmsg(s, &msg, 0)) == -1)
1538 log_Printf(LogERROR, "Failed sendmsg: %s: %s\n",
1539 sun->sun_path, strerror(errno));
1540 else if (got != iov[0].iov_len)
1541 log_Printf(LogERROR, "%s: Failed initial sendmsg: Only sent %d of %u\n",
1542 sun->sun_path, got, (unsigned)iov[0].iov_len);
1544 /* We must get the ACK before closing the descriptor ! */
1547 if ((got = read(reply[0], &newpid, sizeof newpid)) == sizeof newpid) {
1548 log_Printf(LogDEBUG, "Received confirmation from pid %d\n",
1550 if (lock && (res = ID0uu_lock_txfr(lock, newpid)) != UU_LOCK_OK)
1551 log_Printf(LogERROR, "uu_lock_txfr: %s\n", uu_lockerr(res));
1553 log_Printf(LogDEBUG, "Transmitting link (%d bytes)\n", expect);
1554 if ((got = writev(reply[0], iov + 1, niov - 1)) != expect) {
1556 log_Printf(LogERROR, "%s: Failed writev: %s\n",
1557 sun->sun_path, strerror(errno));
1559 log_Printf(LogERROR, "%s: Failed writev: Wrote %d of %d\n",
1560 sun->sun_path, got, expect);
1562 } else if (got == -1)
1563 log_Printf(LogERROR, "%s: Failed socketpair read: %s\n",
1564 sun->sun_path, strerror(errno));
1566 log_Printf(LogERROR, "%s: Failed socketpair read: Got %d of %d\n",
1567 sun->sun_path, got, (int)(sizeof newpid));
1573 newsid = Enabled(dl->bundle, OPT_KEEPSESSION) ||
1574 tcgetpgrp(fd[0]) == getpgrp();
1578 bundle_setsid(dl->bundle, got != -1);
1583 free(iov[niov].iov_base);
1587 bundle_RenameDatalink(struct bundle *bundle, struct datalink *ndl,
1590 struct datalink *dl;
1592 if (!strcasecmp(ndl->name, name))
1595 for (dl = bundle->links; dl; dl = dl->next)
1596 if (!strcasecmp(dl->name, name))
1599 datalink_Rename(ndl, name);
1604 bundle_SetMode(struct bundle *bundle, struct datalink *dl, int mode)
1608 omode = dl->physical->type;
1612 if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO))
1613 /* First auto link */
1614 if (bundle->ncp.ipcp.peer_ip.s_addr == INADDR_ANY) {
1615 log_Printf(LogWARN, "You must `set ifaddr' or `open' before"
1616 " changing mode to %s\n", mode2Nam(mode));
1620 if (!datalink_SetMode(dl, mode))
1623 if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO) &&
1624 bundle->phase != PHASE_NETWORK)
1625 /* First auto link, we need an interface */
1626 ipcp_InterfaceUp(&bundle->ncp.ipcp);
1628 /* Regenerate phys_type and adjust idle timer */
1629 bundle_LinksRemoved(bundle);
1635 bundle_setsid(struct bundle *bundle, int holdsession)
1638 * Lose the current session. This means getting rid of our pid
1639 * too so that the tty device will really go away, and any getty
1640 * etc will be allowed to restart.
1645 struct datalink *dl;
1647 if (!holdsession && bundle_IsDead(bundle)) {
1649 * No need to lose our session after all... we're going away anyway
1651 * We should really stop the timer and pause if holdsession is set and
1652 * the bundle's dead, but that leaves other resources lying about :-(
1658 if (pipe(fds) == -1) {
1659 log_Printf(LogERROR, "pipe: %s\n", strerror(errno));
1662 switch ((pid = fork())) {
1664 log_Printf(LogERROR, "fork: %s\n", strerror(errno));
1670 read(fds[0], &done, 1); /* uu_locks are mine ! */
1672 if (pipe(fds) == -1) {
1673 log_Printf(LogERROR, "pipe(2): %s\n", strerror(errno));
1676 switch ((pid = fork())) {
1678 log_Printf(LogERROR, "fork(2): %s\n", strerror(errno));
1684 bundle_LockTun(bundle); /* update pid */
1685 read(fds[0], &done, 1); /* uu_locks are mine ! */
1688 bundle_ChangedPID(bundle);
1689 log_Printf(LogDEBUG, "%d -> %d: %s session control\n",
1690 (int)orig, (int)getpid(),
1691 holdsession ? "Passed" : "Dropped");
1692 timer_InitService(0); /* Start the Timer Service */
1696 /* Give away all our physical locks (to the final process) */
1697 for (dl = bundle->links; dl; dl = dl->next)
1698 if (dl->state != DATALINK_CLOSED)
1699 physical_ChangedPid(dl->physical, pid);
1700 write(fds[1], "!", 1); /* done */
1708 /* Give away all our physical locks (to the intermediate process) */
1709 for (dl = bundle->links; dl; dl = dl->next)
1710 if (dl->state != DATALINK_CLOSED)
1711 physical_ChangedPid(dl->physical, pid);
1712 write(fds[1], "!", 1); /* done */
1717 timer_TermService();
1718 signal(SIGPIPE, SIG_DFL);
1719 signal(SIGALRM, SIG_DFL);
1720 signal(SIGHUP, SIG_DFL);
1721 signal(SIGTERM, SIG_DFL);
1722 signal(SIGINT, SIG_DFL);
1723 signal(SIGQUIT, SIG_DFL);
1724 for (fd = getdtablesize(); fd >= 0; fd--)
1727 * Reap the intermediate process. As we're not exiting but the
1728 * intermediate is, we don't want it to become defunct.
1730 waitpid(pid, &status, 0);
1731 /* Tweak our process arguments.... */
1732 SetTitle("session owner");
1734 setuid(ID0realuid());
1737 * Hang around for a HUP. This should happen as soon as the
1738 * ppp that we passed our ctty descriptor to closes it.
1739 * NOTE: If this process dies, the passed descriptor becomes
1740 * invalid and will give a select() error by setting one
1741 * of the error fds, aborting the other ppp. We don't
1742 * want that to happen !
1752 bundle_HighestState(struct bundle *bundle)
1754 struct datalink *dl;
1755 int result = DATALINK_CLOSED;
1757 for (dl = bundle->links; dl; dl = dl->next)
1758 if (result < dl->state)
1765 bundle_Exception(struct bundle *bundle, int fd)
1767 struct datalink *dl;
1769 for (dl = bundle->links; dl; dl = dl->next)
1770 if (dl->physical->fd == fd) {
1771 datalink_Down(dl, CLOSE_NORMAL);
1779 bundle_AdjustFilters(struct bundle *bundle, struct ncpaddr *local,
1780 struct ncpaddr *remote)
1782 filter_AdjustAddr(&bundle->filter.in, local, remote, NULL);
1783 filter_AdjustAddr(&bundle->filter.out, local, remote, NULL);
1784 filter_AdjustAddr(&bundle->filter.dial, local, remote, NULL);
1785 filter_AdjustAddr(&bundle->filter.alive, local, remote, NULL);
1789 bundle_AdjustDNS(struct bundle *bundle)
1791 struct in_addr *dns = bundle->ncp.ipcp.ns.dns;
1793 filter_AdjustAddr(&bundle->filter.in, NULL, NULL, dns);
1794 filter_AdjustAddr(&bundle->filter.out, NULL, NULL, dns);
1795 filter_AdjustAddr(&bundle->filter.dial, NULL, NULL, dns);
1796 filter_AdjustAddr(&bundle->filter.alive, NULL, NULL, dns);
1800 bundle_CalculateBandwidth(struct bundle *bundle)
1802 struct datalink *dl;
1803 int sp, overhead, maxoverhead;
1805 bundle->bandwidth = 0;
1806 bundle->iface->mtu = 0;
1809 for (dl = bundle->links; dl; dl = dl->next) {
1810 overhead = ccp_MTUOverhead(&dl->physical->link.ccp);
1811 if (maxoverhead < overhead)
1812 maxoverhead = overhead;
1813 if (dl->state == DATALINK_OPEN) {
1814 if ((sp = dl->mp.bandwidth) == 0 &&
1815 (sp = physical_GetSpeed(dl->physical)) == 0)
1816 log_Printf(LogDEBUG, "%s: %s: Cannot determine bandwidth\n",
1817 dl->name, dl->physical->name.full);
1819 bundle->bandwidth += sp;
1820 if (!bundle->ncp.mp.active) {
1821 bundle->iface->mtu = dl->physical->link.lcp.his_mru;
1827 if(bundle->bandwidth == 0)
1828 bundle->bandwidth = 115200; /* Shrug */
1830 if (bundle->ncp.mp.active) {
1831 bundle->iface->mtu = bundle->ncp.mp.peer_mrru;
1832 overhead = ccp_MTUOverhead(&bundle->ncp.mp.link.ccp);
1833 if (maxoverhead < overhead)
1834 maxoverhead = overhead;
1835 } else if (!bundle->iface->mtu)
1836 bundle->iface->mtu = DEF_MRU;
1839 if (bundle->radius.valid && bundle->radius.mtu &&
1840 bundle->radius.mtu < bundle->iface->mtu) {
1841 log_Printf(LogLCP, "Reducing MTU to radius value %lu\n",
1842 bundle->radius.mtu);
1843 bundle->iface->mtu = bundle->radius.mtu;
1848 log_Printf(LogLCP, "Reducing MTU from %d to %d (CCP requirement)\n",
1849 bundle->iface->mtu, bundle->iface->mtu - maxoverhead);
1850 bundle->iface->mtu -= maxoverhead;
1853 tun_configure(bundle);
1855 route_UpdateMTU(bundle);
1859 bundle_AutoAdjust(struct bundle *bundle, int percent, int what)
1861 struct datalink *dl, *choice, *otherlinkup;
1863 choice = otherlinkup = NULL;
1864 for (dl = bundle->links; dl; dl = dl->next)
1865 if (dl->physical->type == PHYS_AUTO) {
1866 if (dl->state == DATALINK_OPEN) {
1867 if (what == AUTO_DOWN) {
1869 otherlinkup = choice;
1872 } else if (dl->state == DATALINK_CLOSED) {
1873 if (what == AUTO_UP) {
1878 /* An auto link in an intermediate state - forget it for the moment */
1882 } else if (dl->state == DATALINK_OPEN && what == AUTO_DOWN)
1886 if (what == AUTO_UP) {
1887 log_Printf(LogPHASE, "%d%% saturation -> Opening link ``%s''\n",
1888 percent, choice->name);
1889 datalink_Up(choice, 1, 1);
1890 mp_CheckAutoloadTimer(&bundle->ncp.mp);
1891 } else if (otherlinkup) { /* Only bring the second-last link down */
1892 log_Printf(LogPHASE, "%d%% saturation -> Closing link ``%s''\n",
1893 percent, choice->name);
1894 datalink_Close(choice, CLOSE_STAYDOWN);
1895 mp_CheckAutoloadTimer(&bundle->ncp.mp);
1901 bundle_WantAutoloadTimer(struct bundle *bundle)
1903 struct datalink *dl;
1904 int autolink, opened;
1906 if (bundle->phase == PHASE_NETWORK) {
1907 for (autolink = opened = 0, dl = bundle->links; dl; dl = dl->next)
1908 if (dl->physical->type == PHYS_AUTO) {
1909 if (++autolink == 2 || (autolink == 1 && opened))
1910 /* Two auto links or one auto and one open in NETWORK phase */
1912 } else if (dl->state == DATALINK_OPEN) {
1915 /* One auto and one open link in NETWORK phase */
1924 bundle_ChangedPID(struct bundle *bundle)
1927 ioctl(bundle->dev.fd, TUNSIFPID, 0);
1932 bundle_Uptime(struct bundle *bundle)
1935 return time(NULL) - bundle->upat;