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
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>
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>
68 #include "throughput.h"
69 #include "slcompress.h"
74 #include "descriptor.h"
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"
116 bundle_PhaseName(struct bundle *bundle)
118 return bundle->phase <= PHASE_TERMINATE ?
119 PhaseNames[bundle->phase] : "unknown";
123 bundle_NewPhase(struct bundle *bundle, u_int new)
125 if (new == bundle->phase)
128 if (new <= PHASE_TERMINATE)
129 log_Printf(LogPHASE, "bundle: %s\n", PhaseNames[new]);
135 MPPE_MasterKeyValid = 0;
137 log_DisplayPrompts();
140 case PHASE_ESTABLISH:
144 case PHASE_AUTHENTICATE:
146 log_DisplayPrompts();
150 if (ncp_fsmStart(&bundle->ncp, bundle)) {
152 log_DisplayPrompts();
154 log_Printf(LogPHASE, "bundle: All NCPs are disabled\n");
155 bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
159 case PHASE_TERMINATE:
161 mp_Down(&bundle->ncp.mp);
162 log_DisplayPrompts();
168 bundle_LayerStart(void *v __unused, struct fsm *fp __unused)
170 /* The given FSM is about to start up ! */
175 bundle_Notify(struct bundle *bundle, char c)
177 if (bundle->notify.fd != -1) {
180 ret = write(bundle->notify.fd, &c, 1);
181 if (c != EX_REDIAL && c != EX_RECONNECT) {
183 log_Printf(LogCHAT, "Parent notified of %s\n",
184 c == EX_NORMAL ? "success" : "failure");
186 log_Printf(LogERROR, "Failed to notify parent of success\n");
187 close(bundle->notify.fd);
188 bundle->notify.fd = -1;
190 log_Printf(LogCHAT, "Parent notified of %s\n", ex_desc(c));
192 log_Printf(LogERROR, "Failed to notify parent of %s\n", ex_desc(c));
197 bundle_ClearQueues(void *v)
199 struct bundle *bundle = (struct bundle *)v;
202 log_Printf(LogPHASE, "Clearing choked output queue\n");
203 timer_Stop(&bundle->choked.timer);
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
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);
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;
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);
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);
246 bundle_LinksRemoved(struct bundle *bundle)
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) {
260 if (bundle->radius.sessiontime)
261 bundle_StopSessionTimer(bundle);
263 bundle_StopIdleTimer(bundle);
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
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);
292 if (bundle->radius.sessiontime)
293 bundle_StartSessionTimer(bundle, 0);
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 */
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) {
322 if (bundle->radius.sessiontime)
323 bundle_StopSessionTimer(bundle);
325 bundle_StopIdleTimer(bundle);
327 mp_StopAutoloadTimer(&bundle->ncp.mp);
329 } else if (fp->proto == PROTO_LCP) {
331 struct datalink *lost;
334 bundle_LinksRemoved(bundle); /* adjust timers & phys_type values */
338 for (dl = bundle->links; dl; dl = dl->next) {
339 if (fp == &dl->physical->link.lcp.fsm)
341 else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
345 if (bundle->ncp.mp.active) {
346 bundle_CalculateBandwidth(bundle);
349 mp_LinkLost(&bundle->ncp.mp, lost);
351 log_Printf(LogALERT, "Oops, lost an unrecognised datalink (%s) !\n",
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);
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;
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);
382 mp_Down(&bundle->ncp.mp);
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
393 * If it isn't the last datalink, just Close that datalink.
396 struct datalink *dl, *this_dl;
402 for (dl = bundle->links; dl; dl = dl->next) {
403 if (name && !strcasecmp(name, dl->name))
405 if (name == NULL || this_dl == dl) {
408 datalink_DontHangup(dl);
411 datalink_StayDown(dl);
414 } else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
418 if (name && this_dl == NULL) {
419 log_Printf(LogWARN, "%s: Invalid datalink name\n", name);
423 if (!others_active) {
425 if (bundle->radius.sessiontime)
426 bundle_StopSessionTimer(bundle);
428 bundle_StopIdleTimer(bundle);
429 if (ncp_LayersUnfinished(&bundle->ncp))
430 ncp_Close(&bundle->ncp);
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);
443 bundle_Down(struct bundle *bundle, int how)
447 for (dl = bundle->links; dl; dl = dl->next)
448 datalink_Down(dl, how);
452 bundle_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
454 struct bundle *bundle = descriptor2bundle(d);
462 /* If there are aren't many packets queued, look for some more. */
463 for (nlinks = 0, dl = bundle->links; dl; dl = dl->next)
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);
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);
494 result += descriptor_UpdateSet(&bundle->radius.desc, r, w, e, n);
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);
512 bundle_IsSet(struct fdescriptor *d, const fd_set *fdset)
514 struct bundle *bundle = descriptor2bundle(d);
517 for (dl = bundle->links; dl; dl = dl->next)
518 if (descriptor_IsSet(&dl->desc, fdset))
522 if (descriptor_IsSet(&bundle->radius.desc, fdset))
526 if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
529 return FD_ISSET(bundle->dev.fd, fdset);
533 bundle_DescriptorRead(struct fdescriptor *d __unused, struct bundle *bundle,
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);
548 if (descriptor_IsSet(&bundle->radius.desc, fdset))
549 descriptor_Read(&bundle->radius.desc, bundle, fdset);
552 if (FD_ISSET(bundle->dev.fd, fdset)) {
558 if (bundle->dev.header) {
559 data = (u_char *)&tun;
563 sz = sizeof tun.data;
566 /* something to read from tun */
568 n = read(bundle->dev.fd, data, sz);
570 log_Printf(LogWARN, "%s: read: %s\n", bundle->dev.Name, strerror(errno));
574 if (bundle->dev.header) {
575 n -= sz - sizeof tun.data;
577 log_Printf(LogERROR, "%s: read: Got only %d bytes of data !\n",
578 bundle->dev.Name, n);
581 af = ntohl(tun.header.family);
583 if (af != AF_INET && af != AF_INET6)
587 /* XXX: Should be maintaining drop/family counts ! */
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,
599 n += sz - sizeof tun.data;
600 write(bundle->dev.fd, data, n);
601 log_Printf(LogDEBUG, "Looped back packet addressed to myself\n");
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,
621 bundle_Open(bundle, NULL, PHYS_AUTO, 0);
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.
634 pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.out,
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);
645 bundle_DescriptorWrite(struct fdescriptor *d __unused, struct bundle *bundle,
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)
656 for (dl = bundle->links; dl; dl = dl->next)
657 if (descriptor_IsSet(&dl->desc, fdset))
658 switch (descriptor_Write(&dl->desc, bundle, fdset)) {
660 datalink_ComeDown(dl, CLOSE_NORMAL);
670 bundle_LockTun(struct bundle *bundle)
673 char pidfilename[PATH_MAX];
675 snprintf(pidfilename, sizeof pidfilename, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
676 lockfile = ID0fopen(pidfilename, "w");
677 if (lockfile != NULL) {
678 fprintf(lockfile, "%d\n", (int)getpid());
682 log_Printf(LogERROR, "Warning: Can't create %s: %s\n",
683 pidfilename, strerror(errno));
687 bundle_UnlockTun(struct bundle *bundle)
689 char pidfilename[PATH_MAX];
691 snprintf(pidfilename, sizeof pidfilename, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
692 ID0unlink(pidfilename);
696 bundle_Create(const char *prefix, int type, int unit)
698 static struct bundle bundle; /* there can be only one */
699 int enoentcount, err, minunit, maxunit;
701 #if defined(__DragonFly__) && !defined(NOKLDLOAD)
704 #if defined(TUNSIFMODE) || defined(TUNSLMODE) || defined(TUNSIFHEAD)
708 if (bundle.iface != NULL) { /* Already allocated ! */
709 log_Printf(LogALERT, "bundle_Create: There's only one BUNDLE !\n");
722 #if defined(__DragonFly__) && !defined(NOKLDLOAD)
725 for (bundle.unit = minunit; bundle.unit != maxunit; bundle.unit++) {
726 snprintf(bundle.dev.Name, sizeof bundle.dev.Name, "%s%d",
727 prefix, bundle.unit);
728 bundle.dev.fd = ID0open(bundle.dev.Name, O_RDWR);
729 if (bundle.dev.fd >= 0)
731 else if (errno == ENXIO || errno == ENOENT) {
732 #if defined(__DragonFly__) && !defined(NOKLDLOAD)
733 if (bundle.unit == minunit && !kldtried++) {
735 * Attempt to load the tunnel interface KLD if it isn't loaded
738 if (loadmodules(LOAD_VERBOSLY, "if_tun", NULL))
743 if (errno != ENOENT || ++enoentcount > 2) {
751 if (bundle.dev.fd < 0) {
753 log_Printf(LogWARN, "No available tunnel devices found (%s)\n",
756 log_Printf(LogWARN, "%s%d: %s\n", prefix, unit, strerror(err));
760 log_SetTun(bundle.unit);
762 ifname = strrchr(bundle.dev.Name, '/');
764 ifname = bundle.dev.Name;
768 bundle.iface = iface_Create(ifname);
769 if (bundle.iface == NULL) {
770 close(bundle.dev.fd);
775 /* Make sure we're POINTOPOINT & IFF_MULTICAST */
776 iff = IFF_POINTOPOINT | IFF_MULTICAST;
777 if (ID0ioctl(bundle.dev.fd, TUNSIFMODE, &iff) < 0)
778 log_Printf(LogERROR, "bundle_Create: ioctl(TUNSIFMODE): %s\n",
783 /* Make sure we're not prepending sockaddrs */
785 if (ID0ioctl(bundle.dev.fd, TUNSLMODE, &iff) < 0)
786 log_Printf(LogERROR, "bundle_Create: ioctl(TUNSLMODE): %s\n",
791 /* We want the address family please ! */
793 if (ID0ioctl(bundle.dev.fd, TUNSIFHEAD, &iff) < 0) {
794 log_Printf(LogERROR, "bundle_Create: ioctl(TUNSIFHEAD): %s\n",
796 bundle.dev.header = 0;
798 bundle.dev.header = 1;
801 /* Always present for OpenBSD */
802 bundle.dev.header = 1;
805 * If TUNSIFHEAD isn't available and we're not OpenBSD, assume
806 * everything's AF_INET (hopefully the tun device won't pass us
809 bundle.dev.header = 0;
813 log_Printf(LogPHASE, "Using interface: %s\n", ifname);
815 bundle.bandwidth = 0;
816 bundle.routing_seq = 0;
817 bundle.phase = PHASE_DEAD;
818 bundle.CleaningUp = 0;
819 bundle.NatEnabled = 0;
821 bundle.fsm.LayerStart = bundle_LayerStart;
822 bundle.fsm.LayerUp = bundle_LayerUp;
823 bundle.fsm.LayerDown = bundle_LayerDown;
824 bundle.fsm.LayerFinish = bundle_LayerFinish;
825 bundle.fsm.object = &bundle;
827 bundle.cfg.idle.timeout = NCP_IDLE_TIMEOUT;
828 bundle.cfg.idle.min_timeout = 0;
829 *bundle.cfg.auth.name = '\0';
830 *bundle.cfg.auth.key = '\0';
831 bundle.cfg.opt = OPT_IDCHECK | OPT_LOOPBACK | OPT_SROUTES | OPT_TCPMSSFIXUP |
832 OPT_THROUGHPUT | OPT_UTMP;
834 bundle.cfg.opt |= OPT_IPCP;
835 if (probe.ipv6_available)
836 bundle.cfg.opt |= OPT_IPV6CP;
838 *bundle.cfg.label = '\0';
839 bundle.cfg.ifqueue = DEF_IFQUEUE;
840 bundle.cfg.choked.timeout = CHOKED_TIMEOUT;
841 bundle.phys_type.all = type;
842 bundle.phys_type.open = 0;
845 bundle.links = datalink_Create("deflink", &bundle, type);
846 if (bundle.links == NULL) {
847 log_Printf(LogALERT, "Cannot create data link: %s\n", strerror(errno));
848 iface_Destroy(bundle.iface);
850 close(bundle.dev.fd);
854 bundle.desc.type = BUNDLE_DESCRIPTOR;
855 bundle.desc.UpdateSet = bundle_UpdateSet;
856 bundle.desc.IsSet = bundle_IsSet;
857 bundle.desc.Read = bundle_DescriptorRead;
858 bundle.desc.Write = bundle_DescriptorWrite;
860 ncp_Init(&bundle.ncp, &bundle);
862 memset(&bundle.filter, '\0', sizeof bundle.filter);
863 bundle.filter.in.fragok = bundle.filter.in.logok = 1;
864 bundle.filter.in.name = "IN";
865 bundle.filter.out.fragok = bundle.filter.out.logok = 1;
866 bundle.filter.out.name = "OUT";
867 bundle.filter.dial.name = "DIAL";
868 bundle.filter.dial.logok = 1;
869 bundle.filter.alive.name = "ALIVE";
870 bundle.filter.alive.logok = 1;
873 for (i = 0; i < MAXFILTERS; i++) {
874 bundle.filter.in.rule[i].f_action = A_NONE;
875 bundle.filter.out.rule[i].f_action = A_NONE;
876 bundle.filter.dial.rule[i].f_action = A_NONE;
877 bundle.filter.alive.rule[i].f_action = A_NONE;
880 memset(&bundle.idle.timer, '\0', sizeof bundle.idle.timer);
881 bundle.idle.done = 0;
882 bundle.notify.fd = -1;
883 memset(&bundle.choked.timer, '\0', sizeof bundle.choked.timer);
885 radius_Init(&bundle.radius);
888 /* Clean out any leftover crud */
889 iface_Clear(bundle.iface, &bundle.ncp, 0, IFACE_CLEAR_ALL);
891 bundle_LockTun(&bundle);
897 bundle_DownInterface(struct bundle *bundle)
899 route_IfDelete(bundle, 1);
900 iface_ClearFlags(bundle->iface->name, IFF_UP);
904 bundle_Destroy(struct bundle *bundle)
909 * Clean up the interface. We don't really need to do the timer_Stop()s,
910 * mp_Down(), iface_Clear() and bundle_DownInterface() unless we're getting
911 * out under exceptional conditions such as a descriptor exception.
913 timer_Stop(&bundle->idle.timer);
914 timer_Stop(&bundle->choked.timer);
915 mp_Down(&bundle->ncp.mp);
916 iface_Clear(bundle->iface, &bundle->ncp, 0, IFACE_CLEAR_ALL);
917 bundle_DownInterface(bundle);
920 /* Tell the radius server the bad news */
921 radius_Destroy(&bundle->radius);
924 /* Again, these are all DATALINK_CLOSED unless we're abending */
927 dl = datalink_Destroy(dl);
929 ncp_Destroy(&bundle->ncp);
931 close(bundle->dev.fd);
932 bundle_UnlockTun(bundle);
934 /* In case we never made PHASE_NETWORK */
935 bundle_Notify(bundle, EX_ERRDEAD);
937 iface_Destroy(bundle->iface);
938 bundle->iface = NULL;
942 bundle_LinkClosed(struct bundle *bundle, struct datalink *dl)
945 * Our datalink has closed.
946 * CleanDatalinks() (called from DoLoop()) will remove closed
947 * BACKGROUND, FOREGROUND and DIRECT links.
948 * If it's the last data link, enter phase DEAD.
950 * NOTE: dl may not be in our list (bundle_SendDatalink()) !
953 struct datalink *odl;
956 log_SetTtyCommandMode(dl);
959 for (odl = bundle->links; odl; odl = odl->next)
960 if (odl != dl && odl->state != DATALINK_CLOSED)
964 if (dl->physical->type != PHYS_AUTO) /* Not in -auto mode */
965 bundle_DownInterface(bundle);
966 ncp2initial(&bundle->ncp);
967 mp_Down(&bundle->ncp.mp);
968 bundle_NewPhase(bundle, PHASE_DEAD);
970 if (bundle->radius.sessiontime)
971 bundle_StopSessionTimer(bundle);
973 bundle_StopIdleTimer(bundle);
978 bundle_Open(struct bundle *bundle, const char *name, int mask, int force)
981 * Please open the given datalink, or all if name == NULL
985 for (dl = bundle->links; dl; dl = dl->next)
986 if (name == NULL || !strcasecmp(dl->name, name)) {
987 if ((mask & dl->physical->type) &&
988 (dl->state == DATALINK_CLOSED ||
989 (force && dl->state == DATALINK_OPENING &&
990 dl->dial.timer.state == TIMER_RUNNING) ||
991 dl->state == DATALINK_READY)) {
992 timer_Stop(&dl->dial.timer); /* We're finished with this */
993 datalink_Up(dl, 1, 1);
994 if (mask & PHYS_AUTO)
995 break; /* Only one AUTO link at a time */
1003 bundle2datalink(struct bundle *bundle, const char *name)
1005 struct datalink *dl;
1008 for (dl = bundle->links; dl; dl = dl->next)
1009 if (!strcasecmp(dl->name, name))
1011 } else if (bundle->links && !bundle->links->next)
1012 return bundle->links;
1018 bundle_ShowLinks(struct cmdargs const *arg)
1020 struct datalink *dl;
1021 struct pppThroughput *t;
1022 unsigned long long octets;
1025 for (dl = arg->bundle->links; dl; dl = dl->next) {
1026 octets = MAX(dl->physical->link.stats.total.in.OctetsPerSecond,
1027 dl->physical->link.stats.total.out.OctetsPerSecond);
1029 prompt_Printf(arg->prompt, "Name: %s [%s, %s]",
1030 dl->name, mode2Nam(dl->physical->type), datalink_State(dl));
1031 if (dl->physical->link.stats.total.rolling && dl->state == DATALINK_OPEN)
1032 prompt_Printf(arg->prompt, " bandwidth %d, %llu bps (%llu bytes/sec)",
1033 dl->mp.bandwidth ? dl->mp.bandwidth :
1034 physical_GetSpeed(dl->physical),
1035 octets * 8, octets);
1036 prompt_Printf(arg->prompt, "\n");
1039 t = &arg->bundle->ncp.mp.link.stats.total;
1040 octets = MAX(t->in.OctetsPerSecond, t->out.OctetsPerSecond);
1041 secs = t->downtime ? 0 : throughput_uptime(t);
1042 if (secs > t->SamplePeriod)
1043 secs = t->SamplePeriod;
1045 prompt_Printf(arg->prompt, "Currently averaging %llu bps (%llu bytes/sec)"
1046 " over the last %d secs\n", octets * 8, octets, secs);
1052 optval(struct bundle *bundle, int bit)
1054 return (bundle->cfg.opt & bit) ? "enabled" : "disabled";
1058 bundle_ShowStatus(struct cmdargs const *arg)
1062 prompt_Printf(arg->prompt, "Phase %s\n", bundle_PhaseName(arg->bundle));
1063 prompt_Printf(arg->prompt, " Device: %s\n", arg->bundle->dev.Name);
1064 prompt_Printf(arg->prompt, " Interface: %s @ %lubps",
1065 arg->bundle->iface->name, arg->bundle->bandwidth);
1067 if (arg->bundle->upat) {
1068 int secs = bundle_Uptime(arg->bundle);
1070 prompt_Printf(arg->prompt, ", up time %d:%02d:%02d", secs / 3600,
1071 (secs / 60) % 60, secs % 60);
1073 prompt_Printf(arg->prompt, "\n Queued: %lu of %u\n",
1074 (unsigned long)ncp_QueueLen(&arg->bundle->ncp),
1075 arg->bundle->cfg.ifqueue);
1077 prompt_Printf(arg->prompt, "\nDefaults:\n");
1078 prompt_Printf(arg->prompt, " Label: %s\n",
1079 arg->bundle->cfg.label);
1080 prompt_Printf(arg->prompt, " Auth name: %s\n",
1081 arg->bundle->cfg.auth.name);
1082 prompt_Printf(arg->prompt, " Diagnostic socket: ");
1083 if (*server.cfg.sockname != '\0') {
1084 prompt_Printf(arg->prompt, "%s", server.cfg.sockname);
1085 if (server.cfg.mask != (mode_t)-1)
1086 prompt_Printf(arg->prompt, ", mask 0%03o", (int)server.cfg.mask);
1087 prompt_Printf(arg->prompt, "%s\n", server.fd == -1 ? " (not open)" : "");
1088 } else if (server.cfg.port != 0)
1089 prompt_Printf(arg->prompt, "TCP port %d%s\n", server.cfg.port,
1090 server.fd == -1 ? " (not open)" : "");
1092 prompt_Printf(arg->prompt, "none\n");
1094 prompt_Printf(arg->prompt, " Choked Timer: %us\n",
1095 arg->bundle->cfg.choked.timeout);
1098 radius_Show(&arg->bundle->radius, arg->prompt);
1101 prompt_Printf(arg->prompt, " Idle Timer: ");
1102 if (arg->bundle->cfg.idle.timeout) {
1103 prompt_Printf(arg->prompt, "%us", arg->bundle->cfg.idle.timeout);
1104 if (arg->bundle->cfg.idle.min_timeout)
1105 prompt_Printf(arg->prompt, ", min %us",
1106 arg->bundle->cfg.idle.min_timeout);
1107 remaining = bundle_RemainingIdleTime(arg->bundle);
1108 if (remaining != -1)
1109 prompt_Printf(arg->prompt, " (%ds remaining)", remaining);
1110 prompt_Printf(arg->prompt, "\n");
1112 prompt_Printf(arg->prompt, "disabled\n");
1114 prompt_Printf(arg->prompt, " Filter Decap: %-20.20s",
1115 optval(arg->bundle, OPT_FILTERDECAP));
1116 prompt_Printf(arg->prompt, " ID check: %s\n",
1117 optval(arg->bundle, OPT_IDCHECK));
1118 prompt_Printf(arg->prompt, " Iface-Alias: %-20.20s",
1119 optval(arg->bundle, OPT_IFACEALIAS));
1121 prompt_Printf(arg->prompt, " IPCP: %s\n",
1122 optval(arg->bundle, OPT_IPCP));
1123 prompt_Printf(arg->prompt, " IPV6CP: %-20.20s",
1124 optval(arg->bundle, OPT_IPV6CP));
1126 prompt_Printf(arg->prompt, " Keep-Session: %s\n",
1127 optval(arg->bundle, OPT_KEEPSESSION));
1128 prompt_Printf(arg->prompt, " Loopback: %-20.20s",
1129 optval(arg->bundle, OPT_LOOPBACK));
1130 prompt_Printf(arg->prompt, " PasswdAuth: %s\n",
1131 optval(arg->bundle, OPT_PASSWDAUTH));
1132 prompt_Printf(arg->prompt, " Proxy: %-20.20s",
1133 optval(arg->bundle, OPT_PROXY));
1134 prompt_Printf(arg->prompt, " Proxyall: %s\n",
1135 optval(arg->bundle, OPT_PROXYALL));
1136 prompt_Printf(arg->prompt, " Sticky Routes: %-20.20s",
1137 optval(arg->bundle, OPT_SROUTES));
1138 prompt_Printf(arg->prompt, " TCPMSS Fixup: %s\n",
1139 optval(arg->bundle, OPT_TCPMSSFIXUP));
1140 prompt_Printf(arg->prompt, " Throughput: %-20.20s",
1141 optval(arg->bundle, OPT_THROUGHPUT));
1142 prompt_Printf(arg->prompt, " Utmp Logging: %s\n",
1143 optval(arg->bundle, OPT_UTMP));
1149 bundle_IdleTimeout(void *v)
1151 struct bundle *bundle = (struct bundle *)v;
1153 log_Printf(LogPHASE, "Idle timer expired\n");
1154 bundle_StopIdleTimer(bundle);
1155 bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
1159 * Start Idle timer. If timeout is reached, we call bundle_Close() to
1160 * close LCP and link.
1163 bundle_StartIdleTimer(struct bundle *bundle, unsigned secs)
1165 timer_Stop(&bundle->idle.timer);
1166 if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) !=
1167 bundle->phys_type.open && bundle->cfg.idle.timeout) {
1168 time_t now = time(NULL);
1171 secs = bundle->cfg.idle.timeout;
1173 /* We want at least `secs' */
1174 if (bundle->cfg.idle.min_timeout > secs && bundle->upat) {
1175 unsigned up = now - bundle->upat;
1177 if (bundle->cfg.idle.min_timeout > up &&
1178 bundle->cfg.idle.min_timeout - up > (long long)secs)
1179 /* Only increase from the current `remaining' value */
1180 secs = bundle->cfg.idle.min_timeout - up;
1182 bundle->idle.timer.func = bundle_IdleTimeout;
1183 bundle->idle.timer.name = "idle";
1184 bundle->idle.timer.load = secs * SECTICKS;
1185 bundle->idle.timer.arg = bundle;
1186 timer_Start(&bundle->idle.timer);
1187 bundle->idle.done = now + secs;
1192 bundle_SetIdleTimer(struct bundle *bundle, unsigned timeout,
1193 unsigned min_timeout)
1195 bundle->cfg.idle.timeout = timeout;
1196 bundle->cfg.idle.min_timeout = min_timeout;
1197 if (ncp_LayersOpen(&bundle->ncp))
1198 bundle_StartIdleTimer(bundle, 0);
1202 bundle_StopIdleTimer(struct bundle *bundle)
1204 timer_Stop(&bundle->idle.timer);
1205 bundle->idle.done = 0;
1209 bundle_RemainingIdleTime(struct bundle *bundle)
1211 if (bundle->idle.done)
1212 return bundle->idle.done - time(NULL);
1219 bundle_SessionTimeout(void *v)
1221 struct bundle *bundle = (struct bundle *)v;
1223 log_Printf(LogPHASE, "Session-Timeout timer expired\n");
1224 bundle_StopSessionTimer(bundle);
1225 bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
1229 bundle_StartSessionTimer(struct bundle *bundle, unsigned secs)
1231 timer_Stop(&bundle->session.timer);
1232 if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) !=
1233 bundle->phys_type.open && bundle->radius.sessiontime) {
1234 time_t now = time(NULL);
1237 secs = bundle->radius.sessiontime;
1239 bundle->session.timer.func = bundle_SessionTimeout;
1240 bundle->session.timer.name = "session";
1241 bundle->session.timer.load = secs * SECTICKS;
1242 bundle->session.timer.arg = bundle;
1243 timer_Start(&bundle->session.timer);
1244 bundle->session.done = now + secs;
1249 bundle_StopSessionTimer(struct bundle *bundle)
1251 timer_Stop(&bundle->session.timer);
1252 bundle->session.done = 0;
1258 bundle_IsDead(struct bundle *bundle)
1260 return !bundle->links || (bundle->phase == PHASE_DEAD && bundle->CleaningUp);
1263 static struct datalink *
1264 bundle_DatalinkLinkout(struct bundle *bundle, struct datalink *dl)
1266 struct datalink **dlp;
1268 for (dlp = &bundle->links; *dlp; dlp = &(*dlp)->next)
1272 bundle_LinksRemoved(bundle);
1280 bundle_DatalinkLinkin(struct bundle *bundle, struct datalink *dl)
1282 struct datalink **dlp = &bundle->links;
1285 dlp = &(*dlp)->next;
1290 bundle_LinkAdded(bundle, dl);
1291 mp_CheckAutoloadTimer(&bundle->ncp.mp);
1295 bundle_CleanDatalinks(struct bundle *bundle)
1297 struct datalink **dlp = &bundle->links;
1301 if ((*dlp)->state == DATALINK_CLOSED &&
1302 (*dlp)->physical->type &
1303 (PHYS_DIRECT|PHYS_BACKGROUND|PHYS_FOREGROUND)) {
1304 *dlp = datalink_Destroy(*dlp);
1307 dlp = &(*dlp)->next;
1310 bundle_LinksRemoved(bundle);
1314 bundle_DatalinkClone(struct bundle *bundle, struct datalink *dl,
1317 if (bundle2datalink(bundle, name)) {
1318 log_Printf(LogWARN, "Clone: %s: name already exists\n", name);
1322 bundle_DatalinkLinkin(bundle, datalink_Clone(dl, name));
1327 bundle_DatalinkRemove(struct bundle *bundle, struct datalink *dl)
1329 dl = bundle_DatalinkLinkout(bundle, dl);
1331 datalink_Destroy(dl);
1335 bundle_SetLabel(struct bundle *bundle, const char *label)
1338 strncpy(bundle->cfg.label, label, sizeof bundle->cfg.label - 1);
1340 *bundle->cfg.label = '\0';
1344 bundle_GetLabel(struct bundle *bundle)
1346 return *bundle->cfg.label ? bundle->cfg.label : NULL;
1350 bundle_LinkSize(void)
1352 struct iovec iov[SCATTER_SEGMENTS];
1353 int niov, expect, f;
1355 iov[0].iov_len = strlen(Version) + 1;
1356 iov[0].iov_base = NULL;
1358 if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1359 log_Printf(LogERROR, "Cannot determine space required for link\n");
1363 for (f = expect = 0; f < niov; f++)
1364 expect += iov[f].iov_len;
1370 bundle_ReceiveDatalink(struct bundle *bundle, int s)
1372 char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int) * SEND_MAXFD];
1373 int niov, expect, f, *fd, nfd, onfd;
1375 struct iovec iov[SCATTER_SEGMENTS];
1376 struct cmsghdr *cmsg;
1378 struct datalink *dl;
1381 log_Printf(LogPHASE, "Receiving datalink\n");
1384 * Create our scatter/gather array - passing NULL gets the space
1385 * allocation requirement rather than actually flattening the
1388 iov[0].iov_len = strlen(Version) + 1;
1389 iov[0].iov_base = NULL;
1391 if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1392 log_Printf(LogERROR, "Cannot determine space required for link\n");
1396 /* Allocate the scatter/gather array for recvmsg() */
1397 for (f = expect = 0; f < niov; f++) {
1398 if ((iov[f].iov_base = malloc(iov[f].iov_len)) == NULL) {
1399 log_Printf(LogERROR, "Cannot allocate space to receive link\n");
1403 expect += iov[f].iov_len;
1406 /* Set up our message */
1407 cmsg = (struct cmsghdr *)cmsgbuf;
1408 cmsg->cmsg_len = sizeof cmsgbuf;
1409 cmsg->cmsg_level = SOL_SOCKET;
1410 cmsg->cmsg_type = 0;
1412 memset(&msg, '\0', sizeof msg);
1413 msg.msg_name = NULL;
1414 msg.msg_namelen = 0;
1416 msg.msg_iovlen = 1; /* Only send the version at the first pass */
1417 msg.msg_control = cmsgbuf;
1418 msg.msg_controllen = sizeof cmsgbuf;
1420 log_Printf(LogDEBUG, "Expecting %u scatter/gather bytes\n",
1421 (unsigned)iov[0].iov_len);
1423 if ((got = recvmsg(s, &msg, MSG_WAITALL)) != (ssize_t)iov[0].iov_len) {
1425 log_Printf(LogERROR, "Failed recvmsg: %s\n", strerror(errno));
1427 log_Printf(LogERROR, "Failed recvmsg: Got %zu, not %u\n",
1428 got, (unsigned)iov[0].iov_len);
1430 free(iov[niov].iov_base);
1434 if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) {
1435 log_Printf(LogERROR, "Recvmsg: no descriptors received !\n");
1437 free(iov[niov].iov_base);
1441 fd = (int *)CMSG_DATA(cmsg);
1442 nfd = ((caddr_t)cmsg + cmsg->cmsg_len - (caddr_t)fd) / sizeof(int);
1445 log_Printf(LogERROR, "Recvmsg: %d descriptor%s received (too few) !\n",
1446 nfd, nfd == 1 ? "" : "s");
1450 free(iov[niov].iov_base);
1455 * We've successfully received two or more open file descriptors
1456 * through our socket, plus a version string. Make sure it's the
1457 * correct version, and drop the connection if it's not.
1459 if (strncmp(Version, iov[0].iov_base, iov[0].iov_len)) {
1460 log_Printf(LogWARN, "Cannot receive datalink, incorrect version"
1461 " (\"%.*s\", not \"%s\")\n", (int)iov[0].iov_len,
1462 (char *)iov[0].iov_base, Version);
1466 free(iov[niov].iov_base);
1471 * Everything looks good. Send the other side our process id so that
1472 * they can transfer lock ownership, and wait for them to send the
1476 if ((got = write(fd[1], &pid, sizeof pid)) != sizeof pid) {
1478 log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1480 log_Printf(LogERROR, "Failed write: Got %zu, not %d\n", got,
1485 free(iov[niov].iov_base);
1489 if ((got = readv(fd[1], iov + 1, niov - 1)) != expect) {
1491 log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1493 log_Printf(LogERROR, "Failed write: Got %zu, not %d\n", got, expect);
1497 free(iov[niov].iov_base);
1502 onfd = nfd; /* We've got this many in our array */
1503 nfd -= 2; /* Don't include p->fd and our reply descriptor */
1504 niov = 1; /* Skip the version id */
1505 dl = iov2datalink(bundle, iov, &niov, sizeof iov / sizeof *iov, fd[0],
1510 log_Printf(LogERROR, "bundle_ReceiveDatalink: Failed to handle %d "
1511 "auxiliary file descriptors (%d remain)\n", onfd, nfd);
1512 datalink_Destroy(dl);
1517 bundle_DatalinkLinkin(bundle, dl);
1518 datalink_AuthOk(dl);
1519 bundle_CalculateBandwidth(dl->bundle);
1528 free(iov[0].iov_base);
1532 bundle_SendDatalink(struct datalink *dl, int s, struct sockaddr_un *sun)
1534 char cmsgbuf[CMSG_SPACE(sizeof(int) * SEND_MAXFD)];
1535 const char *constlock;
1537 struct cmsghdr *cmsg;
1539 struct iovec iov[SCATTER_SEGMENTS];
1540 int niov, f, expect, newsid, fd[SEND_MAXFD], nfd, reply[2];
1544 log_Printf(LogPHASE, "Transmitting datalink %s\n", dl->name);
1546 /* Record the base device name for a lock transfer later */
1547 constlock = physical_LockedDevice(dl->physical);
1549 lock = alloca(strlen(constlock) + 1);
1550 strcpy(lock, constlock);
1554 bundle_LinkClosed(dl->bundle, dl);
1555 bundle_DatalinkLinkout(dl->bundle, dl);
1557 /* Build our scatter/gather array */
1558 iov[0].iov_len = strlen(Version) + 1;
1559 iov[0].iov_base = strdup(Version);
1563 fd[0] = datalink2iov(dl, iov, &niov, SCATTER_SEGMENTS, fd + 2, &nfd);
1565 if (fd[0] != -1 && socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, reply) != -1) {
1567 * fd[1] is used to get the peer process id back, then to confirm that
1568 * we've transferred any device locks to that process id.
1572 nfd += 2; /* Include fd[0] and fd[1] */
1573 memset(&msg, '\0', sizeof msg);
1575 msg.msg_name = NULL;
1576 msg.msg_namelen = 0;
1578 * Only send the version to start... We used to send the whole lot, but
1579 * this caused problems with our RECVBUF size as a single link is about
1580 * 22k ! This way, we should bump into no limits.
1584 msg.msg_control = cmsgbuf;
1585 msg.msg_controllen = CMSG_SPACE(sizeof(int) * nfd);
1588 cmsg = (struct cmsghdr *)cmsgbuf;
1589 cmsg->cmsg_len = msg.msg_controllen;
1590 cmsg->cmsg_level = SOL_SOCKET;
1591 cmsg->cmsg_type = SCM_RIGHTS;
1593 for (f = 0; f < nfd; f++)
1594 *((int *)CMSG_DATA(cmsg) + f) = fd[f];
1596 for (f = 1, expect = 0; f < niov; f++)
1597 expect += iov[f].iov_len;
1599 if (setsockopt(reply[0], SOL_SOCKET, SO_SNDBUF, &expect, sizeof(int)) == -1)
1600 log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1602 if (setsockopt(reply[1], SOL_SOCKET, SO_RCVBUF, &expect, sizeof(int)) == -1)
1603 log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1606 log_Printf(LogDEBUG, "Sending %d descriptor%s and %u bytes in scatter"
1607 "/gather array\n", nfd, nfd == 1 ? "" : "s",
1608 (unsigned)iov[0].iov_len);
1610 if ((got = sendmsg(s, &msg, 0)) == -1)
1611 log_Printf(LogERROR, "Failed sendmsg: %s: %s\n",
1612 sun->sun_path, strerror(errno));
1613 else if (got != (ssize_t)iov[0].iov_len)
1614 log_Printf(LogERROR, "%s: Failed initial sendmsg: Only sent %zu of %u\n",
1615 sun->sun_path, got, (unsigned)iov[0].iov_len);
1617 /* We must get the ACK before closing the descriptor ! */
1620 if ((got = read(reply[0], &newpid, sizeof newpid)) == sizeof newpid) {
1621 log_Printf(LogDEBUG, "Received confirmation from pid %ld\n",
1623 if (lock && (res = ID0uu_lock_txfr(lock, newpid)) != UU_LOCK_OK)
1624 log_Printf(LogERROR, "uu_lock_txfr: %s\n", uu_lockerr(res));
1626 log_Printf(LogDEBUG, "Transmitting link (%d bytes)\n", expect);
1627 if ((got = writev(reply[0], iov + 1, niov - 1)) != expect) {
1629 log_Printf(LogERROR, "%s: Failed writev: %s\n",
1630 sun->sun_path, strerror(errno));
1632 log_Printf(LogERROR, "%s: Failed writev: Wrote %zu of %d\n",
1633 sun->sun_path, got, expect);
1635 } else if (got == -1)
1636 log_Printf(LogERROR, "%s: Failed socketpair read: %s\n",
1637 sun->sun_path, strerror(errno));
1639 log_Printf(LogERROR, "%s: Failed socketpair read: Got %zu of %d\n",
1640 sun->sun_path, got, (int)(sizeof newpid));
1646 newsid = Enabled(dl->bundle, OPT_KEEPSESSION) ||
1647 tcgetpgrp(fd[0]) == getpgrp();
1651 bundle_setsid(dl->bundle, got != -1);
1656 free(iov[niov].iov_base);
1660 bundle_RenameDatalink(struct bundle *bundle, struct datalink *ndl,
1663 struct datalink *dl;
1665 if (!strcasecmp(ndl->name, name))
1668 for (dl = bundle->links; dl; dl = dl->next)
1669 if (!strcasecmp(dl->name, name))
1672 datalink_Rename(ndl, name);
1677 bundle_SetMode(struct bundle *bundle, struct datalink *dl, int mode)
1681 omode = dl->physical->type;
1685 if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO))
1686 /* First auto link */
1687 if (bundle->ncp.ipcp.peer_ip.s_addr == INADDR_ANY) {
1688 log_Printf(LogWARN, "You must `set ifaddr' or `open' before"
1689 " changing mode to %s\n", mode2Nam(mode));
1693 if (!datalink_SetMode(dl, mode))
1696 if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO) &&
1697 bundle->phase != PHASE_NETWORK)
1698 /* First auto link, we need an interface */
1699 ipcp_InterfaceUp(&bundle->ncp.ipcp);
1701 /* Regenerate phys_type and adjust idle timer */
1702 bundle_LinksRemoved(bundle);
1708 bundle_setsid(struct bundle *bundle, int holdsession)
1711 * Lose the current session. This means getting rid of our pid
1712 * too so that the tty device will really go away, and any getty
1713 * etc will be allowed to restart.
1718 struct datalink *dl;
1720 if (!holdsession && bundle_IsDead(bundle)) {
1722 * No need to lose our session after all... we're going away anyway
1724 * We should really stop the timer and pause if holdsession is set and
1725 * the bundle's dead, but that leaves other resources lying about :-(
1731 if (pipe(fds) == -1) {
1732 log_Printf(LogERROR, "pipe: %s\n", strerror(errno));
1735 switch ((pid = fork())) {
1737 log_Printf(LogERROR, "fork: %s\n", strerror(errno));
1743 read(fds[0], &done, 1); /* uu_locks are mine ! */
1745 if (pipe(fds) == -1) {
1746 log_Printf(LogERROR, "pipe(2): %s\n", strerror(errno));
1749 switch ((pid = fork())) {
1751 log_Printf(LogERROR, "fork(2): %s\n", strerror(errno));
1757 bundle_LockTun(bundle); /* update pid */
1758 read(fds[0], &done, 1); /* uu_locks are mine ! */
1761 bundle_ChangedPID(bundle);
1762 log_Printf(LogDEBUG, "%ld -> %ld: %s session control\n",
1763 (long)orig, (long)getpid(),
1764 holdsession ? "Passed" : "Dropped");
1765 timer_InitService(0); /* Start the Timer Service */
1769 /* Give away all our physical locks (to the final process) */
1770 for (dl = bundle->links; dl; dl = dl->next)
1771 if (dl->state != DATALINK_CLOSED)
1772 physical_ChangedPid(dl->physical, pid);
1773 write(fds[1], "!", 1); /* done */
1781 /* Give away all our physical locks (to the intermediate process) */
1782 for (dl = bundle->links; dl; dl = dl->next)
1783 if (dl->state != DATALINK_CLOSED)
1784 physical_ChangedPid(dl->physical, pid);
1785 write(fds[1], "!", 1); /* done */
1790 timer_TermService();
1791 signal(SIGPIPE, SIG_DFL);
1792 signal(SIGALRM, SIG_DFL);
1793 signal(SIGHUP, SIG_DFL);
1794 signal(SIGTERM, SIG_DFL);
1795 signal(SIGINT, SIG_DFL);
1796 signal(SIGQUIT, SIG_DFL);
1797 for (fd = getdtablesize(); fd >= 0; fd--)
1800 * Reap the intermediate process. As we're not exiting but the
1801 * intermediate is, we don't want it to become defunct.
1803 waitpid(pid, &status, 0);
1804 /* Tweak our process arguments.... */
1805 SetTitle("session owner");
1807 setuid(ID0realuid());
1810 * Hang around for a HUP. This should happen as soon as the
1811 * ppp that we passed our ctty descriptor to closes it.
1812 * NOTE: If this process dies, the passed descriptor becomes
1813 * invalid and will give a select() error by setting one
1814 * of the error fds, aborting the other ppp. We don't
1815 * want that to happen !
1825 bundle_HighestState(struct bundle *bundle)
1827 struct datalink *dl;
1828 unsigned result = DATALINK_CLOSED;
1830 for (dl = bundle->links; dl; dl = dl->next)
1831 if (result < dl->state)
1838 bundle_Exception(struct bundle *bundle, int fd)
1840 struct datalink *dl;
1842 for (dl = bundle->links; dl; dl = dl->next)
1843 if (dl->physical->fd == fd) {
1844 datalink_Down(dl, CLOSE_NORMAL);
1852 bundle_AdjustFilters(struct bundle *bundle, struct ncpaddr *local,
1853 struct ncpaddr *remote)
1855 filter_AdjustAddr(&bundle->filter.in, local, remote, NULL);
1856 filter_AdjustAddr(&bundle->filter.out, local, remote, NULL);
1857 filter_AdjustAddr(&bundle->filter.dial, local, remote, NULL);
1858 filter_AdjustAddr(&bundle->filter.alive, local, remote, NULL);
1862 bundle_AdjustDNS(struct bundle *bundle)
1864 struct in_addr *dns = bundle->ncp.ipcp.ns.dns;
1866 filter_AdjustAddr(&bundle->filter.in, NULL, NULL, dns);
1867 filter_AdjustAddr(&bundle->filter.out, NULL, NULL, dns);
1868 filter_AdjustAddr(&bundle->filter.dial, NULL, NULL, dns);
1869 filter_AdjustAddr(&bundle->filter.alive, NULL, NULL, dns);
1873 bundle_CalculateBandwidth(struct bundle *bundle)
1875 struct datalink *dl;
1876 int sp, overhead, maxoverhead;
1878 bundle->bandwidth = 0;
1879 bundle->iface->mtu = 0;
1882 for (dl = bundle->links; dl; dl = dl->next) {
1883 overhead = ccp_MTUOverhead(&dl->physical->link.ccp);
1884 if (maxoverhead < overhead)
1885 maxoverhead = overhead;
1886 if (dl->state == DATALINK_OPEN) {
1887 if ((sp = dl->mp.bandwidth) == 0 &&
1888 (sp = physical_GetSpeed(dl->physical)) == 0)
1889 log_Printf(LogDEBUG, "%s: %s: Cannot determine bandwidth\n",
1890 dl->name, dl->physical->name.full);
1892 bundle->bandwidth += sp;
1893 if (!bundle->ncp.mp.active) {
1894 bundle->iface->mtu = dl->physical->link.lcp.his_mru;
1900 if (bundle->bandwidth == 0)
1901 bundle->bandwidth = 115200; /* Shrug */
1903 if (bundle->ncp.mp.active) {
1904 bundle->iface->mtu = bundle->ncp.mp.peer_mrru;
1905 overhead = ccp_MTUOverhead(&bundle->ncp.mp.link.ccp);
1906 if (maxoverhead < overhead)
1907 maxoverhead = overhead;
1908 } else if (!bundle->iface->mtu)
1909 bundle->iface->mtu = DEF_MRU;
1912 if (bundle->radius.valid && bundle->radius.mtu &&
1913 bundle->radius.mtu < bundle->iface->mtu) {
1914 log_Printf(LogLCP, "Reducing MTU to radius value %lu\n",
1915 bundle->radius.mtu);
1916 bundle->iface->mtu = bundle->radius.mtu;
1921 log_Printf(LogLCP, "Reducing MTU from %lu to %lu (CCP requirement)\n",
1922 bundle->iface->mtu, bundle->iface->mtu - maxoverhead);
1923 bundle->iface->mtu -= maxoverhead;
1926 tun_configure(bundle);
1928 route_UpdateMTU(bundle);
1932 bundle_AutoAdjust(struct bundle *bundle, int percent, int what)
1934 struct datalink *dl, *choice, *otherlinkup;
1936 choice = otherlinkup = NULL;
1937 for (dl = bundle->links; dl; dl = dl->next)
1938 if (dl->physical->type == PHYS_AUTO) {
1939 if (dl->state == DATALINK_OPEN) {
1940 if (what == AUTO_DOWN) {
1942 otherlinkup = choice;
1945 } else if (dl->state == DATALINK_CLOSED) {
1946 if (what == AUTO_UP) {
1951 /* An auto link in an intermediate state - forget it for the moment */
1955 } else if (dl->state == DATALINK_OPEN && what == AUTO_DOWN)
1959 if (what == AUTO_UP) {
1960 log_Printf(LogPHASE, "%d%% saturation -> Opening link ``%s''\n",
1961 percent, choice->name);
1962 datalink_Up(choice, 1, 1);
1963 mp_CheckAutoloadTimer(&bundle->ncp.mp);
1964 } else if (otherlinkup) { /* Only bring the second-last link down */
1965 log_Printf(LogPHASE, "%d%% saturation -> Closing link ``%s''\n",
1966 percent, choice->name);
1967 datalink_Close(choice, CLOSE_STAYDOWN);
1968 mp_CheckAutoloadTimer(&bundle->ncp.mp);
1974 bundle_WantAutoloadTimer(struct bundle *bundle)
1976 struct datalink *dl;
1977 int autolink, opened;
1979 if (bundle->phase == PHASE_NETWORK) {
1980 for (autolink = opened = 0, dl = bundle->links; dl; dl = dl->next)
1981 if (dl->physical->type == PHYS_AUTO) {
1982 if (++autolink == 2 || (autolink == 1 && opened))
1983 /* Two auto links or one auto and one open in NETWORK phase */
1985 } else if (dl->state == DATALINK_OPEN) {
1988 /* One auto and one open link in NETWORK phase */
1997 bundle_ChangedPID(struct bundle *bundle)
2000 ioctl(bundle->dev.fd, TUNSIFPID, 0);
2005 bundle_Uptime(struct bundle *bundle)
2008 return time(NULL) - bundle->upat;