2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 1998 Brian Somers <brian@Awfulhak.org>
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 #include <sys/param.h>
32 #include <sys/socket.h>
33 #include <netinet/in.h>
35 #include <net/if_tun.h> /* For TUNS* ioctls */
36 #include <net/route.h>
37 #include <netinet/in_systm.h>
38 #include <netinet/ip.h>
69 #include "throughput.h"
70 #include "slcompress.h"
75 #include "descriptor.h"
104 #define SCATTER_SEGMENTS 7 /* version, datalink, name, physical,
105 throughput, throughput, device */
107 #define SEND_MAXFD 3 /* Max file descriptors passed through
108 the local domain socket */
110 static int bundle_RemainingIdleTime(struct bundle *);
112 static const char * const PhaseNames[] = {
113 "Dead", "Establish", "Authenticate", "Network", "Terminate"
117 bundle_PhaseName(struct bundle *bundle)
119 return bundle->phase <= PHASE_TERMINATE ?
120 PhaseNames[bundle->phase] : "unknown";
124 bundle_NewPhase(struct bundle *bundle, u_int new)
126 if (new == bundle->phase)
129 if (new <= PHASE_TERMINATE)
130 log_Printf(LogPHASE, "bundle: %s\n", PhaseNames[new]);
136 MPPE_MasterKeyValid = 0;
138 log_DisplayPrompts();
141 case PHASE_ESTABLISH:
145 case PHASE_AUTHENTICATE:
147 log_DisplayPrompts();
151 if (ncp_fsmStart(&bundle->ncp, bundle)) {
153 log_DisplayPrompts();
155 log_Printf(LogPHASE, "bundle: All NCPs are disabled\n");
156 bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
160 case PHASE_TERMINATE:
162 mp_Down(&bundle->ncp.mp);
163 log_DisplayPrompts();
169 bundle_LayerStart(void *v __unused, struct fsm *fp __unused)
171 /* The given FSM is about to start up ! */
176 bundle_Notify(struct bundle *bundle, char c)
178 if (bundle->notify.fd != -1) {
181 ret = write(bundle->notify.fd, &c, 1);
182 if (c != EX_REDIAL && c != EX_RECONNECT) {
184 log_Printf(LogCHAT, "Parent notified of %s\n",
185 c == EX_NORMAL ? "success" : "failure");
187 log_Printf(LogERROR, "Failed to notify parent of success\n");
188 close(bundle->notify.fd);
189 bundle->notify.fd = -1;
191 log_Printf(LogCHAT, "Parent notified of %s\n", ex_desc(c));
193 log_Printf(LogERROR, "Failed to notify parent of %s\n", ex_desc(c));
198 bundle_ClearQueues(void *v)
200 struct bundle *bundle = (struct bundle *)v;
203 log_Printf(LogPHASE, "Clearing choked output queue\n");
204 timer_Stop(&bundle->choked.timer);
209 * We've had a full queue for PACKET_DEL_SECS seconds without being
210 * able to get rid of any of the packets. We've probably given up
211 * on the redials at this point, and the queued data has almost
212 * definitely been timed out by the layer above. As this is preventing
213 * us from reading the TUN_NAME device (we don't want to buffer stuff
214 * indefinitely), we may as well nuke this data and start with a clean
217 * Unfortunately, this has the side effect of shafting any compression
218 * dictionaries in use (causing the relevant RESET_REQ/RESET_ACK).
221 ncp_DeleteQueues(&bundle->ncp);
222 for (dl = bundle->links; dl; dl = dl->next)
223 physical_DeleteQueue(dl->physical);
227 bundle_LinkAdded(struct bundle *bundle, struct datalink *dl)
229 bundle->phys_type.all |= dl->physical->type;
230 if (dl->state == DATALINK_OPEN)
231 bundle->phys_type.open |= dl->physical->type;
234 if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
235 != bundle->phys_type.open && bundle->session.timer.state == TIMER_STOPPED)
236 if (bundle->radius.sessiontime)
237 bundle_StartSessionTimer(bundle, 0);
240 if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
241 != bundle->phys_type.open && bundle->idle.timer.state == TIMER_STOPPED)
242 /* We may need to start our idle timer */
243 bundle_StartIdleTimer(bundle, 0);
247 bundle_LinksRemoved(struct bundle *bundle)
251 bundle->phys_type.all = bundle->phys_type.open = 0;
252 for (dl = bundle->links; dl; dl = dl->next)
253 bundle_LinkAdded(bundle, dl);
255 bundle_CalculateBandwidth(bundle);
256 mp_CheckAutoloadTimer(&bundle->ncp.mp);
258 if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
259 == bundle->phys_type.open) {
261 if (bundle->radius.sessiontime)
262 bundle_StopSessionTimer(bundle);
264 bundle_StopIdleTimer(bundle);
269 bundle_LayerUp(void *v, struct fsm *fp)
272 * The given fsm is now up
273 * If it's an LCP, adjust our phys_mode.open value and check the
275 * If it's the first NCP, calculate our bandwidth
276 * If it's the first NCP, set our ``upat'' time
277 * If it's the first NCP, start the idle timer.
278 * If it's an NCP, tell our -background parent to go away.
279 * If it's the first NCP, start the autoload timer
281 struct bundle *bundle = (struct bundle *)v;
283 if (fp->proto == PROTO_LCP) {
284 struct physical *p = link2physical(fp->link);
286 bundle_LinkAdded(bundle, p->dl);
287 mp_CheckAutoloadTimer(&bundle->ncp.mp);
288 } else if (isncp(fp->proto)) {
289 if (ncp_LayersOpen(&fp->bundle->ncp) == 1) {
290 bundle_CalculateBandwidth(fp->bundle);
293 if (bundle->radius.sessiontime)
294 bundle_StartSessionTimer(bundle, 0);
296 bundle_StartIdleTimer(bundle, 0);
297 mp_CheckAutoloadTimer(&fp->bundle->ncp.mp);
299 bundle_Notify(bundle, EX_NORMAL);
300 } else if (fp->proto == PROTO_CCP)
301 bundle_CalculateBandwidth(fp->bundle); /* Against ccp_MTUOverhead */
305 bundle_LayerDown(void *v, struct fsm *fp)
308 * The given FSM has been told to come down.
309 * If it's our last NCP, stop the idle timer.
310 * If it's our last NCP, clear our ``upat'' value.
311 * If it's our last NCP, stop the autoload timer
312 * If it's an LCP, adjust our phys_type.open value and any timers.
313 * If it's an LCP and we're in multilink mode, adjust our tun
314 * If it's the last LCP, down all NCPs
315 * speed and make sure our minimum sequence number is adjusted.
318 struct bundle *bundle = (struct bundle *)v;
320 if (isncp(fp->proto)) {
321 if (ncp_LayersOpen(&fp->bundle->ncp) == 0) {
323 if (bundle->radius.sessiontime)
324 bundle_StopSessionTimer(bundle);
326 bundle_StopIdleTimer(bundle);
328 mp_StopAutoloadTimer(&bundle->ncp.mp);
330 } else if (fp->proto == PROTO_LCP) {
332 struct datalink *lost;
335 bundle_LinksRemoved(bundle); /* adjust timers & phys_type values */
339 for (dl = bundle->links; dl; dl = dl->next) {
340 if (fp == &dl->physical->link.lcp.fsm)
342 else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
346 if (bundle->ncp.mp.active) {
347 bundle_CalculateBandwidth(bundle);
350 mp_LinkLost(&bundle->ncp.mp, lost);
352 log_Printf(LogALERT, "Oops, lost an unrecognised datalink (%s) !\n",
356 if (!others_active) {
357 /* Down the NCPs. We don't expect to get fsm_Close()d ourself ! */
358 ncp2initial(&bundle->ncp);
359 mp_Down(&bundle->ncp.mp);
365 bundle_LayerFinish(void *v, struct fsm *fp)
367 /* The given fsm is now down (fp cannot be NULL)
369 * If it's the last NCP, fsm_Close all LCPs
370 * If it's the last NCP, bring any MP layer down
373 struct bundle *bundle = (struct bundle *)v;
376 if (isncp(fp->proto) && !ncp_LayersUnfinished(&bundle->ncp)) {
377 if (bundle_Phase(bundle) != PHASE_DEAD)
378 bundle_NewPhase(bundle, PHASE_TERMINATE);
379 for (dl = bundle->links; dl; dl = dl->next)
380 if (dl->state == DATALINK_OPEN)
381 datalink_Close(dl, CLOSE_STAYDOWN);
383 mp_Down(&bundle->ncp.mp);
388 bundle_Close(struct bundle *bundle, const char *name, int how)
391 * Please close the given datalink.
392 * If name == NULL or name is the last datalink, fsm_Close all NCPs
394 * If it isn't the last datalink, just Close that datalink.
397 struct datalink *dl, *this_dl;
403 for (dl = bundle->links; dl; dl = dl->next) {
404 if (name && !strcasecmp(name, dl->name))
406 if (name == NULL || this_dl == dl) {
409 datalink_DontHangup(dl);
412 datalink_StayDown(dl);
415 } else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
419 if (name && this_dl == NULL) {
420 log_Printf(LogWARN, "%s: Invalid datalink name\n", name);
424 if (!others_active) {
426 if (bundle->radius.sessiontime)
427 bundle_StopSessionTimer(bundle);
429 bundle_StopIdleTimer(bundle);
430 if (ncp_LayersUnfinished(&bundle->ncp))
431 ncp_Close(&bundle->ncp);
433 ncp2initial(&bundle->ncp);
434 mp_Down(&bundle->ncp.mp);
435 for (dl = bundle->links; dl; dl = dl->next)
436 datalink_Close(dl, how);
438 } else if (this_dl && this_dl->state != DATALINK_CLOSED &&
439 this_dl->state != DATALINK_HANGUP)
440 datalink_Close(this_dl, how);
444 bundle_Down(struct bundle *bundle, int how)
448 for (dl = bundle->links; dl; dl = dl->next)
449 datalink_Down(dl, how);
453 bundle_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
455 struct bundle *bundle = descriptor2bundle(d);
463 /* If there are aren't many packets queued, look for some more. */
464 for (nlinks = 0, dl = bundle->links; dl; dl = dl->next)
468 queued = r ? ncp_FillPhysicalQueues(&bundle->ncp, bundle) :
469 ncp_QueueLen(&bundle->ncp);
471 if (r && (bundle->phase == PHASE_NETWORK ||
472 bundle->phys_type.all & PHYS_AUTO)) {
473 /* enough surplus so that we can tell if we're getting swamped */
474 ifqueue = nlinks > bundle->cfg.ifqueue ? nlinks : bundle->cfg.ifqueue;
475 if (queued < ifqueue) {
476 /* Not enough - select() for more */
477 if (bundle->choked.timer.state == TIMER_RUNNING)
478 timer_Stop(&bundle->choked.timer); /* Not needed any more */
479 FD_SET(bundle->dev.fd, r);
480 if (*n < bundle->dev.fd + 1)
481 *n = bundle->dev.fd + 1;
482 log_Printf(LogTIMER, "%s: fdset(r) %d\n", TUN_NAME, bundle->dev.fd);
484 } else if (bundle->choked.timer.state == TIMER_STOPPED) {
485 bundle->choked.timer.func = bundle_ClearQueues;
486 bundle->choked.timer.name = "output choke";
487 bundle->choked.timer.load = bundle->cfg.choked.timeout * SECTICKS;
488 bundle->choked.timer.arg = bundle;
489 timer_Start(&bundle->choked.timer);
495 result += descriptor_UpdateSet(&bundle->radius.desc, r, w, e, n);
498 /* Which links need a select() ? */
499 for (dl = bundle->links; dl; dl = dl->next)
500 result += descriptor_UpdateSet(&dl->desc, r, w, e, n);
503 * This *MUST* be called after the datalink UpdateSet()s as it
504 * might be ``holding'' one of the datalinks (death-row) and
505 * wants to be able to de-select() it from the descriptor set.
507 result += descriptor_UpdateSet(&bundle->ncp.mp.server.desc, r, w, e, n);
513 bundle_IsSet(struct fdescriptor *d, const fd_set *fdset)
515 struct bundle *bundle = descriptor2bundle(d);
518 for (dl = bundle->links; dl; dl = dl->next)
519 if (descriptor_IsSet(&dl->desc, fdset))
523 if (descriptor_IsSet(&bundle->radius.desc, fdset))
527 if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
530 return FD_ISSET(bundle->dev.fd, fdset);
534 bundle_DescriptorRead(struct fdescriptor *d __unused, struct bundle *bundle,
541 if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
542 descriptor_Read(&bundle->ncp.mp.server.desc, bundle, fdset);
544 for (dl = bundle->links; dl; dl = dl->next)
545 if (descriptor_IsSet(&dl->desc, fdset))
546 descriptor_Read(&dl->desc, bundle, fdset);
549 if (descriptor_IsSet(&bundle->radius.desc, fdset))
550 descriptor_Read(&bundle->radius.desc, bundle, fdset);
553 if (FD_ISSET(bundle->dev.fd, fdset)) {
559 if (bundle->dev.header) {
560 data = (u_char *)&tun;
564 sz = sizeof tun.data;
567 /* something to read from tun */
569 n = read(bundle->dev.fd, data, sz);
571 log_Printf(LogWARN, "%s: read: %s\n", bundle->dev.Name, strerror(errno));
575 if (bundle->dev.header) {
576 n -= sz - sizeof tun.data;
578 log_Printf(LogERROR, "%s: read: Got only %d bytes of data !\n",
579 bundle->dev.Name, n);
582 af = ntohl(tun.header.family);
584 if (af != AF_INET && af != AF_INET6)
588 /* XXX: Should be maintaining drop/family counts ! */
593 if (af == AF_INET && ((struct ip *)tun.data)->ip_dst.s_addr ==
594 bundle->ncp.ipcp.my_ip.s_addr) {
595 /* we've been asked to send something addressed *to* us :( */
596 if (Enabled(bundle, OPT_LOOPBACK)) {
597 pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.in,
600 n += sz - sizeof tun.data;
601 write(bundle->dev.fd, data, n);
602 log_Printf(LogDEBUG, "Looped back packet addressed to myself\n");
606 log_Printf(LogDEBUG, "Oops - forwarding packet addressed to myself\n");
610 * Process on-demand dialup. Output packets are queued within the tunnel
611 * device until the appropriate NCP is opened.
614 if (bundle_Phase(bundle) == PHASE_DEAD) {
616 * Note, we must be in AUTO mode :-/ otherwise our interface should
617 * *not* be UP and we can't receive data
619 pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.dial,
622 bundle_Open(bundle, NULL, PHYS_AUTO, 0);
625 * Drop the packet. If we were to queue it, we'd just end up with
626 * a pile of timed-out data in our output queue by the time we get
627 * around to actually dialing. We'd also prematurely reach the
628 * threshold at which we stop select()ing to read() the tun
629 * device - breaking auto-dial.
635 pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.out,
638 /* Prepend the number of seconds timeout given in the filter */
639 tun.header.timeout = secs;
640 ncp_Enqueue(&bundle->ncp, af, pri, (char *)&tun, n + sizeof tun.header);
646 bundle_DescriptorWrite(struct fdescriptor *d __unused, struct bundle *bundle,
652 /* This is not actually necessary as struct mpserver doesn't Write() */
653 if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
654 if (descriptor_Write(&bundle->ncp.mp.server.desc, bundle, fdset) == 1)
657 for (dl = bundle->links; dl; dl = dl->next)
658 if (descriptor_IsSet(&dl->desc, fdset))
659 switch (descriptor_Write(&dl->desc, bundle, fdset)) {
661 datalink_ComeDown(dl, CLOSE_NORMAL);
671 bundle_LockTun(struct bundle *bundle)
674 char pidfile[PATH_MAX];
676 snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
677 lockfile = ID0fopen(pidfile, "w");
678 if (lockfile != NULL) {
679 fprintf(lockfile, "%d\n", (int)getpid());
682 log_Printf(LogERROR, "Warning: Can't create %s: %s\n",
683 pidfile, strerror(errno));
687 bundle_UnlockTun(struct bundle *bundle)
689 char pidfile[PATH_MAX];
691 snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
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(__FreeBSD__) && !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(__FreeBSD__) && !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(__FreeBSD__) && !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, NULL);
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.optmask = (1ull << OPT_IDCHECK) | (1ull << OPT_LOOPBACK) |
832 (1ull << OPT_SROUTES) | (1ull << OPT_TCPMSSFIXUP) |
833 (1ull << OPT_THROUGHPUT) | (1ull << OPT_UTMP) |
834 (1ull << OPT_NAS_IP_ADDRESS) |
835 (1ull << OPT_NAS_IDENTIFIER);
837 opt_enable(&bundle, OPT_IPCP);
838 if (probe.ipv6_available)
839 opt_enable(&bundle, OPT_IPV6CP);
841 *bundle.cfg.label = '\0';
842 bundle.cfg.ifqueue = DEF_IFQUEUE;
843 bundle.cfg.choked.timeout = CHOKED_TIMEOUT;
844 bundle.phys_type.all = type;
845 bundle.phys_type.open = 0;
848 bundle.links = datalink_Create("deflink", &bundle, type);
849 if (bundle.links == NULL) {
850 log_Printf(LogALERT, "Cannot create data link: %s\n", strerror(errno));
851 iface_Free(bundle.iface);
853 close(bundle.dev.fd);
857 bundle.desc.type = BUNDLE_DESCRIPTOR;
858 bundle.desc.UpdateSet = bundle_UpdateSet;
859 bundle.desc.IsSet = bundle_IsSet;
860 bundle.desc.Read = bundle_DescriptorRead;
861 bundle.desc.Write = bundle_DescriptorWrite;
863 ncp_Init(&bundle.ncp, &bundle);
865 memset(&bundle.filter, '\0', sizeof bundle.filter);
866 bundle.filter.in.fragok = bundle.filter.in.logok = 1;
867 bundle.filter.in.name = "IN";
868 bundle.filter.out.fragok = bundle.filter.out.logok = 1;
869 bundle.filter.out.name = "OUT";
870 bundle.filter.dial.name = "DIAL";
871 bundle.filter.dial.logok = 1;
872 bundle.filter.alive.name = "ALIVE";
873 bundle.filter.alive.logok = 1;
876 for (i = 0; i < MAXFILTERS; i++) {
877 bundle.filter.in.rule[i].f_action = A_NONE;
878 bundle.filter.out.rule[i].f_action = A_NONE;
879 bundle.filter.dial.rule[i].f_action = A_NONE;
880 bundle.filter.alive.rule[i].f_action = A_NONE;
883 memset(&bundle.idle.timer, '\0', sizeof bundle.idle.timer);
884 bundle.idle.done = 0;
885 bundle.notify.fd = -1;
886 memset(&bundle.choked.timer, '\0', sizeof bundle.choked.timer);
888 radius_Init(&bundle.radius);
891 /* Clean out any leftover crud */
892 iface_Clear(bundle.iface, &bundle.ncp, 0, IFACE_CLEAR_ALL);
894 bundle_LockTun(&bundle);
900 bundle_DownInterface(struct bundle *bundle)
902 route_IfDelete(bundle, 1);
903 iface_ClearFlags(bundle->iface->name, IFF_UP);
907 bundle_Destroy(struct bundle *bundle)
912 * Clean up the interface. We don't really need to do the timer_Stop()s,
913 * mp_Down(), iface_Clear() and bundle_DownInterface() unless we're getting
914 * out under exceptional conditions such as a descriptor exception.
916 timer_Stop(&bundle->idle.timer);
917 timer_Stop(&bundle->choked.timer);
918 mp_Down(&bundle->ncp.mp);
919 iface_Clear(bundle->iface, &bundle->ncp, 0, IFACE_CLEAR_ALL);
920 bundle_DownInterface(bundle);
923 /* Tell the radius server the bad news */
924 radius_Destroy(&bundle->radius);
927 /* Again, these are all DATALINK_CLOSED unless we're abending */
930 dl = datalink_Destroy(dl);
932 ncp_Destroy(&bundle->ncp);
934 close(bundle->dev.fd);
935 bundle_UnlockTun(bundle);
937 /* In case we never made PHASE_NETWORK */
938 bundle_Notify(bundle, EX_ERRDEAD);
940 iface_Destroy(bundle->iface);
941 bundle->iface = NULL;
945 bundle_LinkClosed(struct bundle *bundle, struct datalink *dl)
948 * Our datalink has closed.
949 * CleanDatalinks() (called from DoLoop()) will remove closed
950 * BACKGROUND, FOREGROUND and DIRECT links.
951 * If it's the last data link, enter phase DEAD.
953 * NOTE: dl may not be in our list (bundle_SendDatalink()) !
956 struct datalink *odl;
959 log_SetTtyCommandMode(dl);
962 for (odl = bundle->links; odl; odl = odl->next)
963 if (odl != dl && odl->state != DATALINK_CLOSED)
967 if (dl->physical->type != PHYS_AUTO) /* Not in -auto mode */
968 bundle_DownInterface(bundle);
969 ncp2initial(&bundle->ncp);
970 mp_Down(&bundle->ncp.mp);
971 bundle_NewPhase(bundle, PHASE_DEAD);
973 if (bundle->radius.sessiontime)
974 bundle_StopSessionTimer(bundle);
976 bundle_StopIdleTimer(bundle);
981 bundle_Open(struct bundle *bundle, const char *name, int mask, int force)
984 * Please open the given datalink, or all if name == NULL
988 for (dl = bundle->links; dl; dl = dl->next)
989 if (name == NULL || !strcasecmp(dl->name, name)) {
990 if ((mask & dl->physical->type) &&
991 (dl->state == DATALINK_CLOSED ||
992 (force && dl->state == DATALINK_OPENING &&
993 dl->dial.timer.state == TIMER_RUNNING) ||
994 dl->state == DATALINK_READY)) {
995 timer_Stop(&dl->dial.timer); /* We're finished with this */
996 datalink_Up(dl, 1, 1);
997 if (mask & PHYS_AUTO)
998 break; /* Only one AUTO link at a time */
1006 bundle2datalink(struct bundle *bundle, const char *name)
1008 struct datalink *dl;
1011 for (dl = bundle->links; dl; dl = dl->next)
1012 if (!strcasecmp(dl->name, name))
1014 } else if (bundle->links && !bundle->links->next)
1015 return bundle->links;
1021 bundle_ShowLinks(struct cmdargs const *arg)
1023 struct datalink *dl;
1024 struct pppThroughput *t;
1025 unsigned long long octets;
1028 for (dl = arg->bundle->links; dl; dl = dl->next) {
1029 octets = MAX(dl->physical->link.stats.total.in.OctetsPerSecond,
1030 dl->physical->link.stats.total.out.OctetsPerSecond);
1032 prompt_Printf(arg->prompt, "Name: %s [%s, %s]",
1033 dl->name, mode2Nam(dl->physical->type), datalink_State(dl));
1034 if (dl->physical->link.stats.total.rolling && dl->state == DATALINK_OPEN)
1035 prompt_Printf(arg->prompt, " bandwidth %d, %llu bps (%llu bytes/sec)",
1036 dl->mp.bandwidth ? dl->mp.bandwidth :
1037 physical_GetSpeed(dl->physical),
1038 octets * 8, octets);
1039 prompt_Printf(arg->prompt, "\n");
1042 t = &arg->bundle->ncp.mp.link.stats.total;
1043 octets = MAX(t->in.OctetsPerSecond, t->out.OctetsPerSecond);
1044 secs = t->downtime ? 0 : throughput_uptime(t);
1045 if (secs > t->SamplePeriod)
1046 secs = t->SamplePeriod;
1048 prompt_Printf(arg->prompt, "Currently averaging %llu bps (%llu bytes/sec)"
1049 " over the last %d secs\n", octets * 8, octets, secs);
1055 optval(struct bundle *bundle, int opt)
1057 return Enabled(bundle, opt) ? "enabled" : "disabled";
1061 bundle_ShowStatus(struct cmdargs const *arg)
1065 prompt_Printf(arg->prompt, "Phase %s\n", bundle_PhaseName(arg->bundle));
1066 prompt_Printf(arg->prompt, " Device: %s\n", arg->bundle->dev.Name);
1067 prompt_Printf(arg->prompt, " Interface: %s @ %lubps",
1068 arg->bundle->iface->name, arg->bundle->bandwidth);
1070 if (arg->bundle->upat) {
1071 int secs = bundle_Uptime(arg->bundle);
1073 prompt_Printf(arg->prompt, ", up time %d:%02d:%02d", secs / 3600,
1074 (secs / 60) % 60, secs % 60);
1076 prompt_Printf(arg->prompt, "\n Queued: %lu of %u\n",
1077 (unsigned long)ncp_QueueLen(&arg->bundle->ncp),
1078 arg->bundle->cfg.ifqueue);
1080 prompt_Printf(arg->prompt, "\nDefaults:\n");
1081 prompt_Printf(arg->prompt, " Label: %s\n",
1082 arg->bundle->cfg.label);
1083 prompt_Printf(arg->prompt, " Auth name: %s\n",
1084 arg->bundle->cfg.auth.name);
1085 prompt_Printf(arg->prompt, " Diagnostic socket: ");
1086 if (*server.cfg.sockname != '\0') {
1087 prompt_Printf(arg->prompt, "%s", server.cfg.sockname);
1088 if (server.cfg.mask != (mode_t)-1)
1089 prompt_Printf(arg->prompt, ", mask 0%03o", (int)server.cfg.mask);
1090 prompt_Printf(arg->prompt, "%s\n", server.fd == -1 ? " (not open)" : "");
1091 } else if (server.cfg.port != 0)
1092 prompt_Printf(arg->prompt, "TCP port %d%s\n", server.cfg.port,
1093 server.fd == -1 ? " (not open)" : "");
1095 prompt_Printf(arg->prompt, "none\n");
1097 prompt_Printf(arg->prompt, " Choked Timer: %us\n",
1098 arg->bundle->cfg.choked.timeout);
1101 radius_Show(&arg->bundle->radius, arg->prompt);
1104 prompt_Printf(arg->prompt, " Idle Timer: ");
1105 if (arg->bundle->cfg.idle.timeout) {
1106 prompt_Printf(arg->prompt, "%us", arg->bundle->cfg.idle.timeout);
1107 if (arg->bundle->cfg.idle.min_timeout)
1108 prompt_Printf(arg->prompt, ", min %us",
1109 arg->bundle->cfg.idle.min_timeout);
1110 remaining = bundle_RemainingIdleTime(arg->bundle);
1111 if (remaining != -1)
1112 prompt_Printf(arg->prompt, " (%ds remaining)", remaining);
1113 prompt_Printf(arg->prompt, "\n");
1115 prompt_Printf(arg->prompt, "disabled\n");
1117 prompt_Printf(arg->prompt, " Filter Decap: %-20.20s",
1118 optval(arg->bundle, OPT_FILTERDECAP));
1119 prompt_Printf(arg->prompt, " ID check: %s\n",
1120 optval(arg->bundle, OPT_IDCHECK));
1121 prompt_Printf(arg->prompt, " Iface-Alias: %-20.20s",
1122 optval(arg->bundle, OPT_IFACEALIAS));
1124 prompt_Printf(arg->prompt, " IPCP: %s\n",
1125 optval(arg->bundle, OPT_IPCP));
1126 prompt_Printf(arg->prompt, " IPV6CP: %-20.20s",
1127 optval(arg->bundle, OPT_IPV6CP));
1129 prompt_Printf(arg->prompt, " Keep-Session: %s\n",
1130 optval(arg->bundle, OPT_KEEPSESSION));
1131 prompt_Printf(arg->prompt, " Loopback: %-20.20s",
1132 optval(arg->bundle, OPT_LOOPBACK));
1133 prompt_Printf(arg->prompt, " PasswdAuth: %s\n",
1134 optval(arg->bundle, OPT_PASSWDAUTH));
1135 prompt_Printf(arg->prompt, " Proxy: %-20.20s",
1136 optval(arg->bundle, OPT_PROXY));
1137 prompt_Printf(arg->prompt, " Proxyall: %s\n",
1138 optval(arg->bundle, OPT_PROXYALL));
1139 prompt_Printf(arg->prompt, " Sticky Routes: %-20.20s",
1140 optval(arg->bundle, OPT_SROUTES));
1141 prompt_Printf(arg->prompt, " TCPMSS Fixup: %s\n",
1142 optval(arg->bundle, OPT_TCPMSSFIXUP));
1143 prompt_Printf(arg->prompt, " Throughput: %-20.20s",
1144 optval(arg->bundle, OPT_THROUGHPUT));
1145 prompt_Printf(arg->prompt, " Utmp Logging: %s\n",
1146 optval(arg->bundle, OPT_UTMP));
1147 prompt_Printf(arg->prompt, " NAS-IP-Address: %-20.20s",
1148 optval(arg->bundle, OPT_NAS_IP_ADDRESS));
1149 prompt_Printf(arg->prompt, " NAS-Identifier: %s\n",
1150 optval(arg->bundle, OPT_NAS_IDENTIFIER));
1156 bundle_IdleTimeout(void *v)
1158 struct bundle *bundle = (struct bundle *)v;
1160 log_Printf(LogPHASE, "Idle timer expired\n");
1161 bundle_StopIdleTimer(bundle);
1162 bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
1166 * Start Idle timer. If timeout is reached, we call bundle_Close() to
1167 * close LCP and link.
1170 bundle_StartIdleTimer(struct bundle *bundle, unsigned secs)
1172 timer_Stop(&bundle->idle.timer);
1173 if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) !=
1174 bundle->phys_type.open && bundle->cfg.idle.timeout) {
1175 time_t now = time(NULL);
1178 secs = bundle->cfg.idle.timeout;
1180 /* We want at least `secs' */
1181 if (bundle->cfg.idle.min_timeout > secs && bundle->upat) {
1182 unsigned up = now - bundle->upat;
1184 if (bundle->cfg.idle.min_timeout > up &&
1185 bundle->cfg.idle.min_timeout - up > (long long)secs)
1186 /* Only increase from the current `remaining' value */
1187 secs = bundle->cfg.idle.min_timeout - up;
1189 bundle->idle.timer.func = bundle_IdleTimeout;
1190 bundle->idle.timer.name = "idle";
1191 bundle->idle.timer.load = secs * SECTICKS;
1192 bundle->idle.timer.arg = bundle;
1193 timer_Start(&bundle->idle.timer);
1194 bundle->idle.done = now + secs;
1199 bundle_SetIdleTimer(struct bundle *bundle, unsigned timeout,
1200 unsigned min_timeout)
1202 bundle->cfg.idle.timeout = timeout;
1203 bundle->cfg.idle.min_timeout = min_timeout;
1204 if (ncp_LayersOpen(&bundle->ncp))
1205 bundle_StartIdleTimer(bundle, 0);
1209 bundle_StopIdleTimer(struct bundle *bundle)
1211 timer_Stop(&bundle->idle.timer);
1212 bundle->idle.done = 0;
1216 bundle_RemainingIdleTime(struct bundle *bundle)
1218 if (bundle->idle.done)
1219 return bundle->idle.done - time(NULL);
1226 bundle_SessionTimeout(void *v)
1228 struct bundle *bundle = (struct bundle *)v;
1230 log_Printf(LogPHASE, "Session-Timeout timer expired\n");
1231 bundle_StopSessionTimer(bundle);
1232 bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
1236 bundle_StartSessionTimer(struct bundle *bundle, unsigned secs)
1238 timer_Stop(&bundle->session.timer);
1239 if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) !=
1240 bundle->phys_type.open && bundle->radius.sessiontime) {
1241 time_t now = time(NULL);
1244 secs = bundle->radius.sessiontime;
1246 bundle->session.timer.func = bundle_SessionTimeout;
1247 bundle->session.timer.name = "session";
1248 bundle->session.timer.load = secs * SECTICKS;
1249 bundle->session.timer.arg = bundle;
1250 timer_Start(&bundle->session.timer);
1251 bundle->session.done = now + secs;
1256 bundle_StopSessionTimer(struct bundle *bundle)
1258 timer_Stop(&bundle->session.timer);
1259 bundle->session.done = 0;
1265 bundle_IsDead(struct bundle *bundle)
1267 return !bundle->links || (bundle->phase == PHASE_DEAD && bundle->CleaningUp);
1270 static struct datalink *
1271 bundle_DatalinkLinkout(struct bundle *bundle, struct datalink *dl)
1273 struct datalink **dlp;
1275 for (dlp = &bundle->links; *dlp; dlp = &(*dlp)->next)
1279 bundle_LinksRemoved(bundle);
1287 bundle_DatalinkLinkin(struct bundle *bundle, struct datalink *dl)
1289 struct datalink **dlp = &bundle->links;
1292 dlp = &(*dlp)->next;
1297 bundle_LinkAdded(bundle, dl);
1298 mp_CheckAutoloadTimer(&bundle->ncp.mp);
1302 bundle_CleanDatalinks(struct bundle *bundle)
1304 struct datalink **dlp = &bundle->links;
1308 if ((*dlp)->state == DATALINK_CLOSED &&
1309 (*dlp)->physical->type &
1310 (PHYS_DIRECT|PHYS_BACKGROUND|PHYS_FOREGROUND)) {
1311 *dlp = datalink_Destroy(*dlp);
1314 dlp = &(*dlp)->next;
1317 bundle_LinksRemoved(bundle);
1321 bundle_DatalinkClone(struct bundle *bundle, struct datalink *dl,
1324 if (bundle2datalink(bundle, name)) {
1325 log_Printf(LogWARN, "Clone: %s: name already exists\n", name);
1329 bundle_DatalinkLinkin(bundle, datalink_Clone(dl, name));
1334 bundle_DatalinkRemove(struct bundle *bundle, struct datalink *dl)
1336 dl = bundle_DatalinkLinkout(bundle, dl);
1338 datalink_Destroy(dl);
1342 bundle_SetLabel(struct bundle *bundle, const char *label)
1345 strncpy(bundle->cfg.label, label, sizeof bundle->cfg.label - 1);
1347 *bundle->cfg.label = '\0';
1351 bundle_GetLabel(struct bundle *bundle)
1353 return *bundle->cfg.label ? bundle->cfg.label : NULL;
1359 struct iovec iov[SCATTER_SEGMENTS];
1360 int niov, expect, f;
1362 iov[0].iov_len = strlen(Version) + 1;
1363 iov[0].iov_base = NULL;
1365 if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1366 log_Printf(LogERROR, "Cannot determine space required for link\n");
1370 for (f = expect = 0; f < niov; f++)
1371 expect += iov[f].iov_len;
1377 bundle_ReceiveDatalink(struct bundle *bundle, int s)
1379 char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int) * SEND_MAXFD];
1380 int niov, expect, f, *fd, nfd, onfd;
1382 struct iovec iov[SCATTER_SEGMENTS];
1383 struct cmsghdr *cmsg;
1385 struct datalink *dl;
1388 log_Printf(LogPHASE, "Receiving datalink\n");
1391 * Create our scatter/gather array - passing NULL gets the space
1392 * allocation requirement rather than actually flattening the
1395 iov[0].iov_len = strlen(Version) + 1;
1396 iov[0].iov_base = NULL;
1398 if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1399 log_Printf(LogERROR, "Cannot determine space required for link\n");
1403 /* Allocate the scatter/gather array for recvmsg() */
1404 for (f = expect = 0; f < niov; f++) {
1405 if ((iov[f].iov_base = malloc(iov[f].iov_len)) == NULL) {
1406 log_Printf(LogERROR, "Cannot allocate space to receive link\n");
1410 expect += iov[f].iov_len;
1413 /* Set up our message */
1414 cmsg = (struct cmsghdr *)cmsgbuf;
1415 cmsg->cmsg_len = sizeof cmsgbuf;
1416 cmsg->cmsg_level = SOL_SOCKET;
1417 cmsg->cmsg_type = 0;
1419 memset(&msg, '\0', sizeof msg);
1420 msg.msg_name = NULL;
1421 msg.msg_namelen = 0;
1423 msg.msg_iovlen = 1; /* Only send the version at the first pass */
1424 msg.msg_control = cmsgbuf;
1425 msg.msg_controllen = sizeof cmsgbuf;
1427 log_Printf(LogDEBUG, "Expecting %u scatter/gather bytes\n",
1428 (unsigned)iov[0].iov_len);
1430 if ((got = recvmsg(s, &msg, MSG_WAITALL)) != (ssize_t)iov[0].iov_len) {
1432 log_Printf(LogERROR, "Failed recvmsg: %s\n", strerror(errno));
1434 log_Printf(LogERROR, "Failed recvmsg: Got %zd, not %u\n",
1435 got, (unsigned)iov[0].iov_len);
1437 free(iov[niov].iov_base);
1441 if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) {
1442 log_Printf(LogERROR, "Recvmsg: no descriptors received !\n");
1444 free(iov[niov].iov_base);
1448 fd = (int *)CMSG_DATA(cmsg);
1449 nfd = ((caddr_t)cmsg + cmsg->cmsg_len - (caddr_t)fd) / sizeof(int);
1452 log_Printf(LogERROR, "Recvmsg: %d descriptor%s received (too few) !\n",
1453 nfd, nfd == 1 ? "" : "s");
1457 free(iov[niov].iov_base);
1462 * We've successfully received two or more open file descriptors
1463 * through our socket, plus a version string. Make sure it's the
1464 * correct version, and drop the connection if it's not.
1466 if (strncmp(Version, iov[0].iov_base, iov[0].iov_len)) {
1467 log_Printf(LogWARN, "Cannot receive datalink, incorrect version"
1468 " (\"%.*s\", not \"%s\")\n", (int)iov[0].iov_len,
1469 (char *)iov[0].iov_base, Version);
1473 free(iov[niov].iov_base);
1478 * Everything looks good. Send the other side our process id so that
1479 * they can transfer lock ownership, and wait for them to send the
1483 if ((got = write(fd[1], &pid, sizeof pid)) != sizeof pid) {
1485 log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1487 log_Printf(LogERROR, "Failed write: Got %zd, not %d\n", got,
1492 free(iov[niov].iov_base);
1496 if ((got = readv(fd[1], iov + 1, niov - 1)) != expect) {
1498 log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1500 log_Printf(LogERROR, "Failed write: Got %zd, not %d\n", got, expect);
1504 free(iov[niov].iov_base);
1509 onfd = nfd; /* We've got this many in our array */
1510 nfd -= 2; /* Don't include p->fd and our reply descriptor */
1511 niov = 1; /* Skip the version id */
1512 dl = iov2datalink(bundle, iov, &niov, sizeof iov / sizeof *iov, fd[0],
1517 log_Printf(LogERROR, "bundle_ReceiveDatalink: Failed to handle %d "
1518 "auxiliary file descriptors (%d remain)\n", onfd, nfd);
1519 datalink_Destroy(dl);
1524 bundle_DatalinkLinkin(bundle, dl);
1525 datalink_AuthOk(dl);
1526 bundle_CalculateBandwidth(dl->bundle);
1535 free(iov[0].iov_base);
1539 bundle_SendDatalink(struct datalink *dl, int s, struct sockaddr_un *sun)
1541 char cmsgbuf[CMSG_SPACE(sizeof(int) * SEND_MAXFD)];
1542 const char *constlock;
1544 struct cmsghdr *cmsg;
1546 struct iovec iov[SCATTER_SEGMENTS];
1547 int niov, f, expect, newsid, fd[SEND_MAXFD], nfd, reply[2];
1551 log_Printf(LogPHASE, "Transmitting datalink %s\n", dl->name);
1553 /* Record the base device name for a lock transfer later */
1554 constlock = physical_LockedDevice(dl->physical);
1556 lock = alloca(strlen(constlock) + 1);
1557 strcpy(lock, constlock);
1561 bundle_LinkClosed(dl->bundle, dl);
1562 bundle_DatalinkLinkout(dl->bundle, dl);
1564 /* Build our scatter/gather array */
1565 iov[0].iov_len = strlen(Version) + 1;
1566 iov[0].iov_base = strdup(Version);
1570 fd[0] = datalink2iov(dl, iov, &niov, SCATTER_SEGMENTS, fd + 2, &nfd);
1572 if (fd[0] != -1 && socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, reply) != -1) {
1574 * fd[1] is used to get the peer process id back, then to confirm that
1575 * we've transferred any device locks to that process id.
1579 nfd += 2; /* Include fd[0] and fd[1] */
1580 memset(&msg, '\0', sizeof msg);
1582 msg.msg_name = NULL;
1583 msg.msg_namelen = 0;
1585 * Only send the version to start... We used to send the whole lot, but
1586 * this caused problems with our RECVBUF size as a single link is about
1587 * 22k ! This way, we should bump into no limits.
1591 msg.msg_control = cmsgbuf;
1592 msg.msg_controllen = CMSG_SPACE(sizeof(int) * nfd);
1595 cmsg = (struct cmsghdr *)cmsgbuf;
1596 cmsg->cmsg_len = msg.msg_controllen;
1597 cmsg->cmsg_level = SOL_SOCKET;
1598 cmsg->cmsg_type = SCM_RIGHTS;
1600 for (f = 0; f < nfd; f++)
1601 *((int *)CMSG_DATA(cmsg) + f) = fd[f];
1603 for (f = 1, expect = 0; f < niov; f++)
1604 expect += iov[f].iov_len;
1606 if (setsockopt(reply[0], SOL_SOCKET, SO_SNDBUF, &expect, sizeof(int)) == -1)
1607 log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1609 if (setsockopt(reply[1], SOL_SOCKET, SO_RCVBUF, &expect, sizeof(int)) == -1)
1610 log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1613 log_Printf(LogDEBUG, "Sending %d descriptor%s and %u bytes in scatter"
1614 "/gather array\n", nfd, nfd == 1 ? "" : "s",
1615 (unsigned)iov[0].iov_len);
1617 if ((got = sendmsg(s, &msg, 0)) == -1)
1618 log_Printf(LogERROR, "Failed sendmsg: %s: %s\n",
1619 sun->sun_path, strerror(errno));
1620 else if (got != (ssize_t)iov[0].iov_len)
1621 log_Printf(LogERROR, "%s: Failed initial sendmsg: Only sent %zd of %u\n",
1622 sun->sun_path, got, (unsigned)iov[0].iov_len);
1624 /* We must get the ACK before closing the descriptor ! */
1627 if ((got = read(reply[0], &newpid, sizeof newpid)) == sizeof newpid) {
1628 log_Printf(LogDEBUG, "Received confirmation from pid %ld\n",
1630 if (lock && (res = ID0uu_lock_txfr(lock, newpid)) != UU_LOCK_OK)
1631 log_Printf(LogERROR, "uu_lock_txfr: %s\n", uu_lockerr(res));
1633 log_Printf(LogDEBUG, "Transmitting link (%d bytes)\n", expect);
1634 if ((got = writev(reply[0], iov + 1, niov - 1)) != expect) {
1636 log_Printf(LogERROR, "%s: Failed writev: %s\n",
1637 sun->sun_path, strerror(errno));
1639 log_Printf(LogERROR, "%s: Failed writev: Wrote %zd of %d\n",
1640 sun->sun_path, got, expect);
1642 } else if (got == -1)
1643 log_Printf(LogERROR, "%s: Failed socketpair read: %s\n",
1644 sun->sun_path, strerror(errno));
1646 log_Printf(LogERROR, "%s: Failed socketpair read: Got %zd of %d\n",
1647 sun->sun_path, got, (int)(sizeof newpid));
1653 newsid = Enabled(dl->bundle, OPT_KEEPSESSION) ||
1654 tcgetpgrp(fd[0]) == getpgrp();
1658 bundle_setsid(dl->bundle, got != -1);
1663 free(iov[niov].iov_base);
1667 bundle_RenameDatalink(struct bundle *bundle, struct datalink *ndl,
1670 struct datalink *dl;
1672 if (!strcasecmp(ndl->name, name))
1675 for (dl = bundle->links; dl; dl = dl->next)
1676 if (!strcasecmp(dl->name, name))
1679 datalink_Rename(ndl, name);
1684 bundle_SetMode(struct bundle *bundle, struct datalink *dl, int mode)
1688 omode = dl->physical->type;
1692 if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO))
1693 /* First auto link */
1694 if (bundle->ncp.ipcp.peer_ip.s_addr == INADDR_ANY) {
1695 log_Printf(LogWARN, "You must `set ifaddr' or `open' before"
1696 " changing mode to %s\n", mode2Nam(mode));
1700 if (!datalink_SetMode(dl, mode))
1703 if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO) &&
1704 bundle->phase != PHASE_NETWORK)
1705 /* First auto link, we need an interface */
1706 ipcp_InterfaceUp(&bundle->ncp.ipcp);
1708 /* Regenerate phys_type and adjust idle timer */
1709 bundle_LinksRemoved(bundle);
1715 bundle_setsid(struct bundle *bundle, int holdsession)
1718 * Lose the current session. This means getting rid of our pid
1719 * too so that the tty device will really go away, and any getty
1720 * etc will be allowed to restart.
1725 struct datalink *dl;
1727 if (!holdsession && bundle_IsDead(bundle)) {
1729 * No need to lose our session after all... we're going away anyway
1731 * We should really stop the timer and pause if holdsession is set and
1732 * the bundle's dead, but that leaves other resources lying about :-(
1738 if (pipe(fds) == -1) {
1739 log_Printf(LogERROR, "pipe: %s\n", strerror(errno));
1742 switch ((pid = fork())) {
1744 log_Printf(LogERROR, "fork: %s\n", strerror(errno));
1750 read(fds[0], &done, 1); /* uu_locks are mine ! */
1752 if (pipe(fds) == -1) {
1753 log_Printf(LogERROR, "pipe(2): %s\n", strerror(errno));
1756 switch ((pid = fork())) {
1758 log_Printf(LogERROR, "fork(2): %s\n", strerror(errno));
1764 bundle_LockTun(bundle); /* update pid */
1765 read(fds[0], &done, 1); /* uu_locks are mine ! */
1768 bundle_ChangedPID(bundle);
1769 log_Printf(LogDEBUG, "%ld -> %ld: %s session control\n",
1770 (long)orig, (long)getpid(),
1771 holdsession ? "Passed" : "Dropped");
1772 timer_InitService(0); /* Start the Timer Service */
1776 /* Give away all our physical locks (to the final process) */
1777 for (dl = bundle->links; dl; dl = dl->next)
1778 if (dl->state != DATALINK_CLOSED)
1779 physical_ChangedPid(dl->physical, pid);
1780 write(fds[1], "!", 1); /* done */
1788 /* Give away all our physical locks (to the intermediate process) */
1789 for (dl = bundle->links; dl; dl = dl->next)
1790 if (dl->state != DATALINK_CLOSED)
1791 physical_ChangedPid(dl->physical, pid);
1792 write(fds[1], "!", 1); /* done */
1797 timer_TermService();
1798 signal(SIGPIPE, SIG_DFL);
1799 signal(SIGALRM, SIG_DFL);
1800 signal(SIGHUP, SIG_DFL);
1801 signal(SIGTERM, SIG_DFL);
1802 signal(SIGINT, SIG_DFL);
1803 signal(SIGQUIT, SIG_DFL);
1804 for (fd = getdtablesize(); fd >= 0; fd--)
1807 * Reap the intermediate process. As we're not exiting but the
1808 * intermediate is, we don't want it to become defunct.
1810 waitpid(pid, &status, 0);
1811 /* Tweak our process arguments.... */
1812 SetTitle("session owner");
1814 setuid(ID0realuid());
1817 * Hang around for a HUP. This should happen as soon as the
1818 * ppp that we passed our ctty descriptor to closes it.
1819 * NOTE: If this process dies, the passed descriptor becomes
1820 * invalid and will give a select() error by setting one
1821 * of the error fds, aborting the other ppp. We don't
1822 * want that to happen !
1832 bundle_HighestState(struct bundle *bundle)
1834 struct datalink *dl;
1835 unsigned result = DATALINK_CLOSED;
1837 for (dl = bundle->links; dl; dl = dl->next)
1838 if (result < dl->state)
1845 bundle_Exception(struct bundle *bundle, int fd)
1847 struct datalink *dl;
1849 for (dl = bundle->links; dl; dl = dl->next)
1850 if (dl->physical->fd == fd) {
1851 datalink_Down(dl, CLOSE_NORMAL);
1859 bundle_AdjustFilters(struct bundle *bundle, struct ncpaddr *local,
1860 struct ncpaddr *remote)
1862 filter_AdjustAddr(&bundle->filter.in, local, remote, NULL);
1863 filter_AdjustAddr(&bundle->filter.out, local, remote, NULL);
1864 filter_AdjustAddr(&bundle->filter.dial, local, remote, NULL);
1865 filter_AdjustAddr(&bundle->filter.alive, local, remote, NULL);
1869 bundle_AdjustDNS(struct bundle *bundle)
1871 struct in_addr *dns = bundle->ncp.ipcp.ns.dns;
1873 filter_AdjustAddr(&bundle->filter.in, NULL, NULL, dns);
1874 filter_AdjustAddr(&bundle->filter.out, NULL, NULL, dns);
1875 filter_AdjustAddr(&bundle->filter.dial, NULL, NULL, dns);
1876 filter_AdjustAddr(&bundle->filter.alive, NULL, NULL, dns);
1880 bundle_CalculateBandwidth(struct bundle *bundle)
1882 struct datalink *dl;
1883 int sp, overhead, maxoverhead;
1885 bundle->bandwidth = 0;
1886 bundle->iface->mtu = 0;
1889 for (dl = bundle->links; dl; dl = dl->next) {
1890 overhead = ccp_MTUOverhead(&dl->physical->link.ccp);
1891 if (maxoverhead < overhead)
1892 maxoverhead = overhead;
1893 if (dl->state == DATALINK_OPEN) {
1894 if ((sp = dl->mp.bandwidth) == 0 &&
1895 (sp = physical_GetSpeed(dl->physical)) == 0)
1896 log_Printf(LogDEBUG, "%s: %s: Cannot determine bandwidth\n",
1897 dl->name, dl->physical->name.full);
1899 bundle->bandwidth += sp;
1900 if (!bundle->ncp.mp.active) {
1901 bundle->iface->mtu = dl->physical->link.lcp.his_mru;
1907 if (bundle->bandwidth == 0)
1908 bundle->bandwidth = 115200; /* Shrug */
1910 if (bundle->ncp.mp.active) {
1911 bundle->iface->mtu = bundle->ncp.mp.peer_mrru;
1912 overhead = ccp_MTUOverhead(&bundle->ncp.mp.link.ccp);
1913 if (maxoverhead < overhead)
1914 maxoverhead = overhead;
1915 } else if (!bundle->iface->mtu)
1916 bundle->iface->mtu = DEF_MRU;
1919 if (bundle->radius.valid && bundle->radius.mtu &&
1920 bundle->radius.mtu < bundle->iface->mtu) {
1921 log_Printf(LogLCP, "Reducing MTU to radius value %lu\n",
1922 bundle->radius.mtu);
1923 bundle->iface->mtu = bundle->radius.mtu;
1928 log_Printf(LogLCP, "Reducing MTU from %lu to %lu (CCP requirement)\n",
1929 bundle->iface->mtu, bundle->iface->mtu - maxoverhead);
1930 bundle->iface->mtu -= maxoverhead;
1933 tun_configure(bundle);
1935 route_UpdateMTU(bundle);
1939 bundle_AutoAdjust(struct bundle *bundle, int percent, int what)
1941 struct datalink *dl, *choice, *otherlinkup;
1943 choice = otherlinkup = NULL;
1944 for (dl = bundle->links; dl; dl = dl->next)
1945 if (dl->physical->type == PHYS_AUTO) {
1946 if (dl->state == DATALINK_OPEN) {
1947 if (what == AUTO_DOWN) {
1949 otherlinkup = choice;
1952 } else if (dl->state == DATALINK_CLOSED) {
1953 if (what == AUTO_UP) {
1958 /* An auto link in an intermediate state - forget it for the moment */
1962 } else if (dl->state == DATALINK_OPEN && what == AUTO_DOWN)
1966 if (what == AUTO_UP) {
1967 log_Printf(LogPHASE, "%d%% saturation -> Opening link ``%s''\n",
1968 percent, choice->name);
1969 datalink_Up(choice, 1, 1);
1970 mp_CheckAutoloadTimer(&bundle->ncp.mp);
1971 } else if (otherlinkup) { /* Only bring the second-last link down */
1972 log_Printf(LogPHASE, "%d%% saturation -> Closing link ``%s''\n",
1973 percent, choice->name);
1974 datalink_Close(choice, CLOSE_STAYDOWN);
1975 mp_CheckAutoloadTimer(&bundle->ncp.mp);
1981 bundle_WantAutoloadTimer(struct bundle *bundle)
1983 struct datalink *dl;
1984 int autolink, opened;
1986 if (bundle->phase == PHASE_NETWORK) {
1987 for (autolink = opened = 0, dl = bundle->links; dl; dl = dl->next)
1988 if (dl->physical->type == PHYS_AUTO) {
1989 if (++autolink == 2 || (autolink == 1 && opened))
1990 /* Two auto links or one auto and one open in NETWORK phase */
1992 } else if (dl->state == DATALINK_OPEN) {
1995 /* One auto and one open link in NETWORK phase */
2004 bundle_ChangedPID(struct bundle *bundle)
2007 ioctl(bundle->dev.fd, TUNSIFPID, 0);
2012 bundle_Uptime(struct bundle *bundle)
2015 return time(NULL) - bundle->upat;