2 * Copyright (c) 1998 Brian Somers <brian@Awfulhak.org>
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 #include <sys/param.h>
30 #include <sys/socket.h>
31 #include <netinet/in.h>
33 #include <net/if_tun.h> /* For TUNS* ioctls */
34 #include <arpa/inet.h>
35 #include <net/route.h>
36 #include <netinet/in_systm.h>
37 #include <netinet/ip.h>
53 #if defined(__FreeBSD__) && !defined(NOKLDLOAD)
54 #include <sys/linker.h>
55 #include <sys/module.h>
71 #include "throughput.h"
72 #include "slcompress.h"
75 #include "descriptor.h"
98 #define SCATTER_SEGMENTS 6 /* version, datalink, name, physical,
101 #define SEND_MAXFD 3 /* Max file descriptors passed through
102 the local domain socket */
104 static int bundle_RemainingIdleTime(struct bundle *);
106 static const char * const PhaseNames[] = {
107 "Dead", "Establish", "Authenticate", "Network", "Terminate"
111 bundle_PhaseName(struct bundle *bundle)
113 return bundle->phase <= PHASE_TERMINATE ?
114 PhaseNames[bundle->phase] : "unknown";
118 bundle_NewPhase(struct bundle *bundle, u_int new)
120 if (new == bundle->phase)
123 if (new <= PHASE_TERMINATE)
124 log_Printf(LogPHASE, "bundle: %s\n", PhaseNames[new]);
128 log_DisplayPrompts();
132 case PHASE_ESTABLISH:
136 case PHASE_AUTHENTICATE:
138 log_DisplayPrompts();
142 fsm_Up(&bundle->ncp.ipcp.fsm);
143 fsm_Open(&bundle->ncp.ipcp.fsm);
145 log_DisplayPrompts();
148 case PHASE_TERMINATE:
150 mp_Down(&bundle->ncp.mp);
151 log_DisplayPrompts();
157 bundle_LayerStart(void *v, struct fsm *fp)
159 /* The given FSM is about to start up ! */
164 bundle_Notify(struct bundle *bundle, char c)
166 if (bundle->notify.fd != -1) {
169 ret = write(bundle->notify.fd, &c, 1);
170 if (c != EX_REDIAL && c != EX_RECONNECT) {
172 log_Printf(LogCHAT, "Parent notified of %s\n",
173 c == EX_NORMAL ? "success" : "failure");
175 log_Printf(LogERROR, "Failed to notify parent of success\n");
176 close(bundle->notify.fd);
177 bundle->notify.fd = -1;
179 log_Printf(LogCHAT, "Parent notified of %s\n", ex_desc(c));
181 log_Printf(LogERROR, "Failed to notify parent of %s\n", ex_desc(c));
186 bundle_ClearQueues(void *v)
188 struct bundle *bundle = (struct bundle *)v;
191 log_Printf(LogPHASE, "Clearing choked output queue\n");
192 timer_Stop(&bundle->choked.timer);
197 * We've had a full queue for PACKET_DEL_SECS seconds without being
198 * able to get rid of any of the packets. We've probably given up
199 * on the redials at this point, and the queued data has almost
200 * definitely been timed out by the layer above. As this is preventing
201 * us from reading the TUN_NAME device (we don't want to buffer stuff
202 * indefinitely), we may as well nuke this data and start with a clean
205 * Unfortunately, this has the side effect of shafting any compression
206 * dictionaries in use (causing the relevant RESET_REQ/RESET_ACK).
209 ip_DeleteQueue(&bundle->ncp.ipcp);
210 mp_DeleteQueue(&bundle->ncp.mp);
211 for (dl = bundle->links; dl; dl = dl->next)
212 physical_DeleteQueue(dl->physical);
216 bundle_LinkAdded(struct bundle *bundle, struct datalink *dl)
218 bundle->phys_type.all |= dl->physical->type;
219 if (dl->state == DATALINK_OPEN)
220 bundle->phys_type.open |= dl->physical->type;
222 if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
223 != bundle->phys_type.open && bundle->idle.timer.state == TIMER_STOPPED)
224 /* We may need to start our idle timer */
225 bundle_StartIdleTimer(bundle);
229 bundle_LinksRemoved(struct bundle *bundle)
233 bundle->phys_type.all = bundle->phys_type.open = 0;
234 for (dl = bundle->links; dl; dl = dl->next)
235 bundle_LinkAdded(bundle, dl);
237 bundle_CalculateBandwidth(bundle);
238 mp_CheckAutoloadTimer(&bundle->ncp.mp);
240 if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL))
241 == bundle->phys_type.open)
242 bundle_StopIdleTimer(bundle);
246 bundle_LayerUp(void *v, struct fsm *fp)
249 * The given fsm is now up
250 * If it's an LCP, adjust our phys_mode.open value and check the
252 * If it's the first NCP, calculate our bandwidth
253 * If it's the first NCP, set our ``upat'' time
254 * If it's the first NCP, start the idle timer.
255 * If it's an NCP, tell our -background parent to go away.
256 * If it's the first NCP, start the autoload timer
258 struct bundle *bundle = (struct bundle *)v;
260 if (fp->proto == PROTO_LCP) {
261 struct physical *p = link2physical(fp->link);
263 bundle_LinkAdded(bundle, p->dl);
264 mp_CheckAutoloadTimer(&bundle->ncp.mp);
265 } else if (fp->proto == PROTO_IPCP) {
266 bundle_CalculateBandwidth(fp->bundle);
268 bundle_StartIdleTimer(bundle);
269 bundle_Notify(bundle, EX_NORMAL);
270 mp_CheckAutoloadTimer(&fp->bundle->ncp.mp);
275 bundle_LayerDown(void *v, struct fsm *fp)
278 * The given FSM has been told to come down.
279 * If it's our last NCP, stop the idle timer.
280 * If it's our last NCP, clear our ``upat'' value.
281 * If it's our last NCP, stop the autoload timer
282 * If it's an LCP, adjust our phys_type.open value and any timers.
283 * If it's an LCP and we're in multilink mode, adjust our tun
284 * If it's the last LCP, down all NCPs
285 * speed and make sure our minimum sequence number is adjusted.
288 struct bundle *bundle = (struct bundle *)v;
290 if (fp->proto == PROTO_IPCP) {
291 bundle_StopIdleTimer(bundle);
293 mp_StopAutoloadTimer(&bundle->ncp.mp);
294 } else if (fp->proto == PROTO_LCP) {
296 struct datalink *lost;
299 bundle_LinksRemoved(bundle); /* adjust timers & phys_type values */
303 for (dl = bundle->links; dl; dl = dl->next) {
304 if (fp == &dl->physical->link.lcp.fsm)
306 else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
310 if (bundle->ncp.mp.active) {
311 bundle_CalculateBandwidth(bundle);
314 mp_LinkLost(&bundle->ncp.mp, lost);
316 log_Printf(LogALERT, "Oops, lost an unrecognised datalink (%s) !\n",
321 /* Down the NCPs. We don't expect to get fsm_Close()d ourself ! */
322 fsm2initial(&bundle->ncp.ipcp.fsm);
327 bundle_LayerFinish(void *v, struct fsm *fp)
329 /* The given fsm is now down (fp cannot be NULL)
331 * If it's the last NCP, fsm_Close all LCPs
334 struct bundle *bundle = (struct bundle *)v;
337 if (fp->proto == PROTO_IPCP) {
338 if (bundle_Phase(bundle) != PHASE_DEAD)
339 bundle_NewPhase(bundle, PHASE_TERMINATE);
340 for (dl = bundle->links; dl; dl = dl->next)
341 if (dl->state == DATALINK_OPEN)
342 datalink_Close(dl, CLOSE_STAYDOWN);
348 bundle_LinkIsUp(const struct bundle *bundle)
350 return bundle->ncp.ipcp.fsm.state == ST_OPENED;
354 bundle_Close(struct bundle *bundle, const char *name, int how)
357 * Please close the given datalink.
358 * If name == NULL or name is the last datalink, fsm_Close all NCPs
360 * If it isn't the last datalink, just Close that datalink.
363 struct datalink *dl, *this_dl;
369 for (dl = bundle->links; dl; dl = dl->next) {
370 if (name && !strcasecmp(name, dl->name))
372 if (name == NULL || this_dl == dl) {
375 datalink_DontHangup(dl);
378 datalink_StayDown(dl);
381 } else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP)
385 if (name && this_dl == NULL) {
386 log_Printf(LogWARN, "%s: Invalid datalink name\n", name);
390 if (!others_active) {
391 bundle_StopIdleTimer(bundle);
392 if (bundle->ncp.ipcp.fsm.state > ST_CLOSED ||
393 bundle->ncp.ipcp.fsm.state == ST_STARTING)
394 fsm_Close(&bundle->ncp.ipcp.fsm);
396 fsm2initial(&bundle->ncp.ipcp.fsm);
397 for (dl = bundle->links; dl; dl = dl->next)
398 datalink_Close(dl, how);
400 } else if (this_dl && this_dl->state != DATALINK_CLOSED &&
401 this_dl->state != DATALINK_HANGUP)
402 datalink_Close(this_dl, how);
406 bundle_Down(struct bundle *bundle, int how)
410 for (dl = bundle->links; dl; dl = dl->next)
411 datalink_Down(dl, how);
415 bundle_FillQueues(struct bundle *bundle)
419 if (bundle->ncp.mp.active)
420 total = mp_FillQueues(bundle);
425 for (total = 0, dl = bundle->links; dl; dl = dl->next)
426 if (dl->state == DATALINK_OPEN) {
427 add = link_QueueLen(&dl->physical->link);
428 if (add == 0 && dl->physical->out == NULL)
429 add = ip_PushPacket(&dl->physical->link, bundle);
434 return total + ip_QueueLen(&bundle->ncp.ipcp);
438 bundle_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n)
440 struct bundle *bundle = descriptor2bundle(d);
447 /* If there are aren't many packets queued, look for some more. */
448 for (nlinks = 0, dl = bundle->links; dl; dl = dl->next)
452 queued = r ? bundle_FillQueues(bundle) : ip_QueueLen(&bundle->ncp.ipcp);
454 if (r && (bundle->phase == PHASE_NETWORK ||
455 bundle->phys_type.all & PHYS_AUTO)) {
456 /* enough surplus so that we can tell if we're getting swamped */
458 /* Not enough - select() for more */
459 if (bundle->choked.timer.state == TIMER_RUNNING)
460 timer_Stop(&bundle->choked.timer); /* Not needed any more */
461 FD_SET(bundle->dev.fd, r);
462 if (*n < bundle->dev.fd + 1)
463 *n = bundle->dev.fd + 1;
464 log_Printf(LogTIMER, "%s: fdset(r) %d\n", TUN_NAME, bundle->dev.fd);
466 } else if (bundle->choked.timer.state == TIMER_STOPPED) {
467 bundle->choked.timer.func = bundle_ClearQueues;
468 bundle->choked.timer.name = "output choke";
469 bundle->choked.timer.load = bundle->cfg.choked.timeout * SECTICKS;
470 bundle->choked.timer.arg = bundle;
471 timer_Start(&bundle->choked.timer);
477 result += descriptor_UpdateSet(&bundle->radius.desc, r, w, e, n);
480 /* Which links need a select() ? */
481 for (dl = bundle->links; dl; dl = dl->next)
482 result += descriptor_UpdateSet(&dl->desc, r, w, e, n);
485 * This *MUST* be called after the datalink UpdateSet()s as it
486 * might be ``holding'' one of the datalinks (death-row) and
487 * wants to be able to de-select() it from the descriptor set.
489 result += descriptor_UpdateSet(&bundle->ncp.mp.server.desc, r, w, e, n);
495 bundle_IsSet(struct fdescriptor *d, const fd_set *fdset)
497 struct bundle *bundle = descriptor2bundle(d);
500 for (dl = bundle->links; dl; dl = dl->next)
501 if (descriptor_IsSet(&dl->desc, fdset))
505 if (descriptor_IsSet(&bundle->radius.desc, fdset))
509 if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
512 return FD_ISSET(bundle->dev.fd, fdset);
516 bundle_DescriptorRead(struct fdescriptor *d, struct bundle *bundle,
521 if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
522 descriptor_Read(&bundle->ncp.mp.server.desc, bundle, fdset);
524 for (dl = bundle->links; dl; dl = dl->next)
525 if (descriptor_IsSet(&dl->desc, fdset))
526 descriptor_Read(&dl->desc, bundle, fdset);
529 if (descriptor_IsSet(&bundle->radius.desc, fdset))
530 descriptor_Read(&bundle->radius.desc, bundle, fdset);
533 if (FD_ISSET(bundle->dev.fd, fdset)) {
539 if (bundle->dev.header) {
544 sz = sizeof tun.data;
547 /* something to read from tun */
549 n = read(bundle->dev.fd, data, sz);
551 log_Printf(LogWARN, "%s: read: %s\n", bundle->dev.Name, strerror(errno));
555 if (bundle->dev.header) {
556 n -= sz - sizeof tun.data;
558 log_Printf(LogERROR, "%s: read: Got only %d bytes of data !\n",
559 bundle->dev.Name, n);
562 if (ntohl(tun.family) != AF_INET)
563 /* XXX: Should be maintaining drop/family counts ! */
567 if (((struct ip *)tun.data)->ip_dst.s_addr ==
568 bundle->ncp.ipcp.my_ip.s_addr) {
569 /* we've been asked to send something addressed *to* us :( */
570 if (Enabled(bundle, OPT_LOOPBACK)) {
571 pri = PacketCheck(bundle, tun.data, n, &bundle->filter.in);
573 n += sz - sizeof tun.data;
574 write(bundle->dev.fd, data, n);
575 log_Printf(LogDEBUG, "Looped back packet addressed to myself\n");
579 log_Printf(LogDEBUG, "Oops - forwarding packet addressed to myself\n");
583 * Process on-demand dialup. Output packets are queued within tunnel
584 * device until IPCP is opened.
587 if (bundle_Phase(bundle) == PHASE_DEAD) {
589 * Note, we must be in AUTO mode :-/ otherwise our interface should
590 * *not* be UP and we can't receive data
592 if ((pri = PacketCheck(bundle, tun.data, n, &bundle->filter.dial)) >= 0)
593 bundle_Open(bundle, NULL, PHYS_AUTO, 0);
596 * Drop the packet. If we were to queue it, we'd just end up with
597 * a pile of timed-out data in our output queue by the time we get
598 * around to actually dialing. We'd also prematurely reach the
599 * threshold at which we stop select()ing to read() the tun
600 * device - breaking auto-dial.
605 pri = PacketCheck(bundle, tun.data, n, &bundle->filter.out);
607 ip_Enqueue(&bundle->ncp.ipcp, pri, tun.data, n);
612 bundle_DescriptorWrite(struct fdescriptor *d, struct bundle *bundle,
618 /* This is not actually necessary as struct mpserver doesn't Write() */
619 if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset))
620 descriptor_Write(&bundle->ncp.mp.server.desc, bundle, fdset);
622 for (dl = bundle->links; dl; dl = dl->next)
623 if (descriptor_IsSet(&dl->desc, fdset))
624 result += descriptor_Write(&dl->desc, bundle, fdset);
630 bundle_LockTun(struct bundle *bundle)
633 char pidfile[MAXPATHLEN];
635 snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
636 lockfile = ID0fopen(pidfile, "w");
637 if (lockfile != NULL) {
638 fprintf(lockfile, "%d\n", (int)getpid());
641 #ifndef RELEASE_CRUNCH
643 log_Printf(LogERROR, "Warning: Can't create %s: %s\n",
644 pidfile, strerror(errno));
649 bundle_UnlockTun(struct bundle *bundle)
651 char pidfile[MAXPATHLEN];
653 snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit);
658 bundle_Create(const char *prefix, int type, int unit)
660 static struct bundle bundle; /* there can be only one */
661 int enoentcount, err, minunit, maxunit;
663 #if defined(__FreeBSD__) && !defined(NOKLDLOAD)
666 #if defined(TUNSIFMODE) || defined(TUNSLMODE) || defined(TUNSIFHEAD)
670 if (bundle.iface != NULL) { /* Already allocated ! */
671 log_Printf(LogALERT, "bundle_Create: There's only one BUNDLE !\n");
684 #if defined(__FreeBSD__) && !defined(NOKLDLOAD)
687 for (bundle.unit = minunit; bundle.unit != maxunit; bundle.unit++) {
688 snprintf(bundle.dev.Name, sizeof bundle.dev.Name, "%s%d",
689 prefix, bundle.unit);
690 bundle.dev.fd = ID0open(bundle.dev.Name, O_RDWR);
691 if (bundle.dev.fd >= 0)
693 else if (errno == ENXIO) {
694 #if defined(__FreeBSD__) && !defined(NOKLDLOAD)
695 if (bundle.unit == minunit && !kldtried++) {
697 * Attempt to load the tunnel interface KLD if it isn't loaded
700 if (modfind("if_tun") == -1) {
701 if (ID0kldload("if_tun") != -1) {
705 log_Printf(LogWARN, "kldload: if_tun: %s\n", strerror(errno));
711 } else if (errno == ENOENT) {
712 if (++enoentcount > 2)
718 if (bundle.dev.fd < 0) {
720 log_Printf(LogWARN, "No available tunnel devices found (%s)\n",
723 log_Printf(LogWARN, "%s%d: %s\n", prefix, unit, strerror(err));
727 log_SetTun(bundle.unit);
729 ifname = strrchr(bundle.dev.Name, '/');
731 ifname = bundle.dev.Name;
735 bundle.iface = iface_Create(ifname);
736 if (bundle.iface == NULL) {
737 close(bundle.dev.fd);
742 /* Make sure we're POINTOPOINT */
743 iff = IFF_POINTOPOINT;
744 if (ID0ioctl(bundle.dev.fd, TUNSIFMODE, &iff) < 0)
745 log_Printf(LogERROR, "bundle_Create: ioctl(TUNSIFMODE): %s\n",
750 /* Make sure we're not prepending sockaddrs */
752 if (ID0ioctl(bundle.dev.fd, TUNSLMODE, &iff) < 0)
753 log_Printf(LogERROR, "bundle_Create: ioctl(TUNSLMODE): %s\n",
758 /* We want the address family please ! */
760 if (ID0ioctl(bundle.dev.fd, TUNSIFHEAD, &iff) < 0) {
761 log_Printf(LogERROR, "bundle_Create: ioctl(TUNSIFHEAD): %s\n",
763 bundle.dev.header = 0;
765 bundle.dev.header = 1;
768 /* Always present for OpenBSD */
769 bundle.dev.header = 1;
772 * If TUNSIFHEAD isn't available and we're not OpenBSD, assume
773 * everything's AF_INET (hopefully the tun device won't pass us
776 bundle.dev.header = 0;
780 if (!iface_SetFlags(bundle.iface, IFF_UP)) {
781 iface_Destroy(bundle.iface);
783 close(bundle.dev.fd);
787 log_Printf(LogPHASE, "Using interface: %s\n", ifname);
789 bundle.bandwidth = 0;
790 bundle.routing_seq = 0;
791 bundle.phase = PHASE_DEAD;
792 bundle.CleaningUp = 0;
793 bundle.NatEnabled = 0;
795 bundle.fsm.LayerStart = bundle_LayerStart;
796 bundle.fsm.LayerUp = bundle_LayerUp;
797 bundle.fsm.LayerDown = bundle_LayerDown;
798 bundle.fsm.LayerFinish = bundle_LayerFinish;
799 bundle.fsm.object = &bundle;
801 bundle.cfg.idle.timeout = NCP_IDLE_TIMEOUT;
802 bundle.cfg.idle.min_timeout = 0;
803 *bundle.cfg.auth.name = '\0';
804 *bundle.cfg.auth.key = '\0';
805 bundle.cfg.opt = OPT_SROUTES | OPT_IDCHECK | OPT_LOOPBACK |
806 OPT_THROUGHPUT | OPT_UTMP;
807 *bundle.cfg.label = '\0';
808 bundle.cfg.mtu = DEF_MTU;
809 bundle.cfg.choked.timeout = CHOKED_TIMEOUT;
810 bundle.phys_type.all = type;
811 bundle.phys_type.open = 0;
814 bundle.links = datalink_Create("deflink", &bundle, type);
815 if (bundle.links == NULL) {
816 log_Printf(LogALERT, "Cannot create data link: %s\n", strerror(errno));
817 iface_Destroy(bundle.iface);
819 close(bundle.dev.fd);
823 bundle.desc.type = BUNDLE_DESCRIPTOR;
824 bundle.desc.UpdateSet = bundle_UpdateSet;
825 bundle.desc.IsSet = bundle_IsSet;
826 bundle.desc.Read = bundle_DescriptorRead;
827 bundle.desc.Write = bundle_DescriptorWrite;
829 mp_Init(&bundle.ncp.mp, &bundle);
831 /* Send over the first physical link by default */
832 ipcp_Init(&bundle.ncp.ipcp, &bundle, &bundle.links->physical->link,
835 memset(&bundle.filter, '\0', sizeof bundle.filter);
836 bundle.filter.in.fragok = bundle.filter.in.logok = 1;
837 bundle.filter.in.name = "IN";
838 bundle.filter.out.fragok = bundle.filter.out.logok = 1;
839 bundle.filter.out.name = "OUT";
840 bundle.filter.dial.name = "DIAL";
841 bundle.filter.dial.logok = 1;
842 bundle.filter.alive.name = "ALIVE";
843 bundle.filter.alive.logok = 1;
846 for (i = 0; i < MAXFILTERS; i++) {
847 bundle.filter.in.rule[i].f_action = A_NONE;
848 bundle.filter.out.rule[i].f_action = A_NONE;
849 bundle.filter.dial.rule[i].f_action = A_NONE;
850 bundle.filter.alive.rule[i].f_action = A_NONE;
853 memset(&bundle.idle.timer, '\0', sizeof bundle.idle.timer);
854 bundle.idle.done = 0;
855 bundle.notify.fd = -1;
856 memset(&bundle.choked.timer, '\0', sizeof bundle.choked.timer);
858 radius_Init(&bundle.radius);
861 /* Clean out any leftover crud */
862 iface_Clear(bundle.iface, IFACE_CLEAR_ALL);
864 bundle_LockTun(&bundle);
870 bundle_DownInterface(struct bundle *bundle)
872 route_IfDelete(bundle, 1);
873 iface_ClearFlags(bundle->iface, IFF_UP);
877 bundle_Destroy(struct bundle *bundle)
882 * Clean up the interface. We don't need to timer_Stop()s, mp_Down(),
883 * ipcp_CleanInterface() and bundle_DownInterface() unless we're getting
884 * out under exceptional conditions such as a descriptor exception.
886 timer_Stop(&bundle->idle.timer);
887 timer_Stop(&bundle->choked.timer);
888 mp_Down(&bundle->ncp.mp);
889 ipcp_CleanInterface(&bundle->ncp.ipcp);
890 bundle_DownInterface(bundle);
893 /* Tell the radius server the bad news */
894 radius_Destroy(&bundle->radius);
897 /* Again, these are all DATALINK_CLOSED unless we're abending */
900 dl = datalink_Destroy(dl);
902 ipcp_Destroy(&bundle->ncp.ipcp);
904 close(bundle->dev.fd);
905 bundle_UnlockTun(bundle);
907 /* In case we never made PHASE_NETWORK */
908 bundle_Notify(bundle, EX_ERRDEAD);
910 iface_Destroy(bundle->iface);
911 bundle->iface = NULL;
915 struct rt_msghdr m_rtm;
920 bundle_SetRoute(struct bundle *bundle, int cmd, struct in_addr dst,
921 struct in_addr gateway, struct in_addr mask, int bang, int ssh)
927 struct sockaddr_in rtdata;
931 cmdstr = (cmd == RTM_ADD ? "Add!" : "Delete!");
933 cmdstr = (cmd == RTM_ADD ? "Add" : "Delete");
934 s = ID0socket(PF_ROUTE, SOCK_RAW, 0);
936 log_Printf(LogERROR, "bundle_SetRoute: socket(): %s\n", strerror(errno));
939 memset(&rtmes, '\0', sizeof rtmes);
940 rtmes.m_rtm.rtm_version = RTM_VERSION;
941 rtmes.m_rtm.rtm_type = cmd;
942 rtmes.m_rtm.rtm_addrs = RTA_DST;
943 rtmes.m_rtm.rtm_seq = ++bundle->routing_seq;
944 rtmes.m_rtm.rtm_pid = getpid();
945 rtmes.m_rtm.rtm_flags = RTF_UP | RTF_GATEWAY | RTF_STATIC;
947 if (cmd == RTM_ADD || cmd == RTM_CHANGE) {
948 if (bundle->ncp.ipcp.cfg.sendpipe > 0) {
949 rtmes.m_rtm.rtm_rmx.rmx_sendpipe = bundle->ncp.ipcp.cfg.sendpipe;
950 rtmes.m_rtm.rtm_inits |= RTV_SPIPE;
952 if (bundle->ncp.ipcp.cfg.recvpipe > 0) {
953 rtmes.m_rtm.rtm_rmx.rmx_recvpipe = bundle->ncp.ipcp.cfg.recvpipe;
954 rtmes.m_rtm.rtm_inits |= RTV_RPIPE;
958 memset(&rtdata, '\0', sizeof rtdata);
959 rtdata.sin_len = sizeof rtdata;
960 rtdata.sin_family = AF_INET;
962 rtdata.sin_addr = dst;
965 memcpy(cp, &rtdata, rtdata.sin_len);
966 cp += rtdata.sin_len;
967 if (cmd == RTM_ADD) {
968 if (gateway.s_addr == INADDR_ANY) {
970 log_Printf(LogERROR, "bundle_SetRoute: Cannot add a route with"
971 " destination 0.0.0.0\n");
975 rtdata.sin_addr = gateway;
976 memcpy(cp, &rtdata, rtdata.sin_len);
977 cp += rtdata.sin_len;
978 rtmes.m_rtm.rtm_addrs |= RTA_GATEWAY;
982 if (dst.s_addr == INADDR_ANY)
983 mask.s_addr = INADDR_ANY;
985 if (cmd == RTM_ADD || dst.s_addr == INADDR_ANY) {
986 rtdata.sin_addr = mask;
987 memcpy(cp, &rtdata, rtdata.sin_len);
988 cp += rtdata.sin_len;
989 rtmes.m_rtm.rtm_addrs |= RTA_NETMASK;
992 nb = cp - (char *) &rtmes;
993 rtmes.m_rtm.rtm_msglen = nb;
994 wb = ID0write(s, &rtmes, nb);
996 log_Printf(LogTCPIP, "bundle_SetRoute failure:\n");
997 log_Printf(LogTCPIP, "bundle_SetRoute: Cmd = %s\n", cmdstr);
998 log_Printf(LogTCPIP, "bundle_SetRoute: Dst = %s\n", inet_ntoa(dst));
999 log_Printf(LogTCPIP, "bundle_SetRoute: Gateway = %s\n",
1000 inet_ntoa(gateway));
1001 log_Printf(LogTCPIP, "bundle_SetRoute: Mask = %s\n", inet_ntoa(mask));
1003 if (cmd == RTM_ADD && (rtmes.m_rtm.rtm_errno == EEXIST ||
1004 (rtmes.m_rtm.rtm_errno == 0 && errno == EEXIST))) {
1006 log_Printf(LogWARN, "Add route failed: %s already exists\n",
1007 dst.s_addr == 0 ? "default" : inet_ntoa(dst));
1008 result = 0; /* Don't add to our dynamic list */
1010 rtmes.m_rtm.rtm_type = cmd = RTM_CHANGE;
1011 if ((wb = ID0write(s, &rtmes, nb)) < 0)
1014 } else if (cmd == RTM_DELETE &&
1015 (rtmes.m_rtm.rtm_errno == ESRCH ||
1016 (rtmes.m_rtm.rtm_errno == 0 && errno == ESRCH))) {
1018 log_Printf(LogWARN, "Del route failed: %s: Non-existent\n",
1020 } else if (rtmes.m_rtm.rtm_errno == 0) {
1021 if (!ssh || errno != ENETUNREACH)
1022 log_Printf(LogWARN, "%s route failed: %s: errno: %s\n", cmdstr,
1023 inet_ntoa(dst), strerror(errno));
1025 log_Printf(LogWARN, "%s route failed: %s: %s\n",
1026 cmdstr, inet_ntoa(dst), strerror(rtmes.m_rtm.rtm_errno));
1028 log_Printf(LogDEBUG, "wrote %d: cmd = %s, dst = %x, gateway = %x\n",
1029 wb, cmdstr, (unsigned)dst.s_addr, (unsigned)gateway.s_addr);
1036 bundle_LinkClosed(struct bundle *bundle, struct datalink *dl)
1039 * Our datalink has closed.
1040 * CleanDatalinks() (called from DoLoop()) will remove closed
1041 * BACKGROUND, FOREGROUND and DIRECT links.
1042 * If it's the last data link, enter phase DEAD.
1044 * NOTE: dl may not be in our list (bundle_SendDatalink()) !
1047 struct datalink *odl;
1050 log_SetTtyCommandMode(dl);
1053 for (odl = bundle->links; odl; odl = odl->next)
1054 if (odl != dl && odl->state != DATALINK_CLOSED)
1058 if (dl->physical->type != PHYS_AUTO) /* Not in -auto mode */
1059 bundle_DownInterface(bundle);
1060 fsm2initial(&bundle->ncp.ipcp.fsm);
1061 bundle_NewPhase(bundle, PHASE_DEAD);
1062 bundle_StopIdleTimer(bundle);
1067 bundle_Open(struct bundle *bundle, const char *name, int mask, int force)
1070 * Please open the given datalink, or all if name == NULL
1072 struct datalink *dl;
1074 for (dl = bundle->links; dl; dl = dl->next)
1075 if (name == NULL || !strcasecmp(dl->name, name)) {
1076 if ((mask & dl->physical->type) &&
1077 (dl->state == DATALINK_CLOSED ||
1078 (force && dl->state == DATALINK_OPENING &&
1079 dl->dial.timer.state == TIMER_RUNNING))) {
1080 if (force) /* Ignore redial timeout ? */
1081 timer_Stop(&dl->dial.timer);
1082 datalink_Up(dl, 1, 1);
1083 if (mask & PHYS_AUTO)
1084 /* Only one AUTO link at a time */
1093 bundle2datalink(struct bundle *bundle, const char *name)
1095 struct datalink *dl;
1098 for (dl = bundle->links; dl; dl = dl->next)
1099 if (!strcasecmp(dl->name, name))
1101 } else if (bundle->links && !bundle->links->next)
1102 return bundle->links;
1108 bundle_ShowLinks(struct cmdargs const *arg)
1110 struct datalink *dl;
1111 struct pppThroughput *t;
1114 for (dl = arg->bundle->links; dl; dl = dl->next) {
1115 prompt_Printf(arg->prompt, "Name: %s [%s, %s]",
1116 dl->name, mode2Nam(dl->physical->type), datalink_State(dl));
1117 if (dl->physical->link.throughput.rolling && dl->state == DATALINK_OPEN)
1118 prompt_Printf(arg->prompt, " bandwidth %d, %llu bps (%llu bytes/sec)",
1119 dl->mp.bandwidth ? dl->mp.bandwidth :
1120 physical_GetSpeed(dl->physical),
1121 dl->physical->link.throughput.OctetsPerSecond * 8,
1122 dl->physical->link.throughput.OctetsPerSecond);
1123 prompt_Printf(arg->prompt, "\n");
1126 t = &arg->bundle->ncp.mp.link.throughput;
1127 secs = t->downtime ? 0 : throughput_uptime(t);
1128 if (secs > t->SamplePeriod)
1129 secs = t->SamplePeriod;
1131 prompt_Printf(arg->prompt, "Currently averaging %llu bps (%llu bytes/sec)"
1132 " over the last %d secs\n", t->OctetsPerSecond * 8,
1133 t->OctetsPerSecond, secs);
1139 optval(struct bundle *bundle, int bit)
1141 return (bundle->cfg.opt & bit) ? "enabled" : "disabled";
1145 bundle_ShowStatus(struct cmdargs const *arg)
1149 prompt_Printf(arg->prompt, "Phase %s\n", bundle_PhaseName(arg->bundle));
1150 prompt_Printf(arg->prompt, " Device: %s\n", arg->bundle->dev.Name);
1151 prompt_Printf(arg->prompt, " Interface: %s @ %lubps",
1152 arg->bundle->iface->name, arg->bundle->bandwidth);
1154 if (arg->bundle->upat) {
1155 int secs = time(NULL) - arg->bundle->upat;
1157 prompt_Printf(arg->prompt, ", up time %d:%02d:%02d", secs / 3600,
1158 (secs / 60) % 60, secs % 60);
1161 prompt_Printf(arg->prompt, "\n\nDefaults:\n");
1162 prompt_Printf(arg->prompt, " Label: %s\n", arg->bundle->cfg.label);
1163 prompt_Printf(arg->prompt, " Auth name: %s\n",
1164 arg->bundle->cfg.auth.name);
1166 prompt_Printf(arg->prompt, " Choked Timer: %ds\n",
1167 arg->bundle->cfg.choked.timeout);
1170 radius_Show(&arg->bundle->radius, arg->prompt);
1173 prompt_Printf(arg->prompt, " Idle Timer: ");
1174 if (arg->bundle->cfg.idle.timeout) {
1175 prompt_Printf(arg->prompt, "%ds", arg->bundle->cfg.idle.timeout);
1176 if (arg->bundle->cfg.idle.min_timeout)
1177 prompt_Printf(arg->prompt, ", min %ds",
1178 arg->bundle->cfg.idle.min_timeout);
1179 remaining = bundle_RemainingIdleTime(arg->bundle);
1180 if (remaining != -1)
1181 prompt_Printf(arg->prompt, " (%ds remaining)", remaining);
1182 prompt_Printf(arg->prompt, "\n");
1184 prompt_Printf(arg->prompt, "disabled\n");
1185 prompt_Printf(arg->prompt, " MTU: ");
1186 if (arg->bundle->cfg.mtu)
1187 prompt_Printf(arg->prompt, "%d\n", arg->bundle->cfg.mtu);
1189 prompt_Printf(arg->prompt, "unspecified\n");
1191 prompt_Printf(arg->prompt, " sendpipe: ");
1192 if (arg->bundle->ncp.ipcp.cfg.sendpipe > 0)
1193 prompt_Printf(arg->prompt, "%-20ld", arg->bundle->ncp.ipcp.cfg.sendpipe);
1195 prompt_Printf(arg->prompt, "unspecified ");
1196 prompt_Printf(arg->prompt, " recvpipe: ");
1197 if (arg->bundle->ncp.ipcp.cfg.recvpipe > 0)
1198 prompt_Printf(arg->prompt, "%ld\n", arg->bundle->ncp.ipcp.cfg.recvpipe);
1200 prompt_Printf(arg->prompt, "unspecified\n");
1202 prompt_Printf(arg->prompt, " Sticky Routes: %-20.20s",
1203 optval(arg->bundle, OPT_SROUTES));
1204 prompt_Printf(arg->prompt, " ID check: %s\n",
1205 optval(arg->bundle, OPT_IDCHECK));
1206 prompt_Printf(arg->prompt, " Keep-Session: %-20.20s",
1207 optval(arg->bundle, OPT_KEEPSESSION));
1208 prompt_Printf(arg->prompt, " Loopback: %s\n",
1209 optval(arg->bundle, OPT_LOOPBACK));
1210 prompt_Printf(arg->prompt, " PasswdAuth: %-20.20s",
1211 optval(arg->bundle, OPT_PASSWDAUTH));
1212 prompt_Printf(arg->prompt, " Proxy: %s\n",
1213 optval(arg->bundle, OPT_PROXY));
1214 prompt_Printf(arg->prompt, " Proxyall: %-20.20s",
1215 optval(arg->bundle, OPT_PROXYALL));
1216 prompt_Printf(arg->prompt, " Throughput: %s\n",
1217 optval(arg->bundle, OPT_THROUGHPUT));
1218 prompt_Printf(arg->prompt, " Utmp Logging: %-20.20s",
1219 optval(arg->bundle, OPT_UTMP));
1220 prompt_Printf(arg->prompt, " Iface-Alias: %s\n",
1221 optval(arg->bundle, OPT_IFACEALIAS));
1227 bundle_IdleTimeout(void *v)
1229 struct bundle *bundle = (struct bundle *)v;
1231 log_Printf(LogPHASE, "Idle timer expired\n");
1232 bundle_StopIdleTimer(bundle);
1233 bundle_Close(bundle, NULL, CLOSE_STAYDOWN);
1237 * Start Idle timer. If timeout is reached, we call bundle_Close() to
1238 * close LCP and link.
1241 bundle_StartIdleTimer(struct bundle *bundle)
1243 timer_Stop(&bundle->idle.timer);
1244 if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) !=
1245 bundle->phys_type.open && bundle->cfg.idle.timeout) {
1248 secs = bundle->cfg.idle.timeout;
1249 if (bundle->cfg.idle.min_timeout > secs && bundle->upat) {
1250 int up = time(NULL) - bundle->upat;
1252 if ((long long)bundle->cfg.idle.min_timeout - up > (long long)secs)
1253 secs = bundle->cfg.idle.min_timeout - up;
1255 bundle->idle.timer.func = bundle_IdleTimeout;
1256 bundle->idle.timer.name = "idle";
1257 bundle->idle.timer.load = secs * SECTICKS;
1258 bundle->idle.timer.arg = bundle;
1259 timer_Start(&bundle->idle.timer);
1260 bundle->idle.done = time(NULL) + secs;
1265 bundle_SetIdleTimer(struct bundle *bundle, int timeout, int min_timeout)
1267 bundle->cfg.idle.timeout = timeout;
1268 if (min_timeout >= 0)
1269 bundle->cfg.idle.min_timeout = min_timeout;
1270 if (bundle_LinkIsUp(bundle))
1271 bundle_StartIdleTimer(bundle);
1275 bundle_StopIdleTimer(struct bundle *bundle)
1277 timer_Stop(&bundle->idle.timer);
1278 bundle->idle.done = 0;
1282 bundle_RemainingIdleTime(struct bundle *bundle)
1284 if (bundle->idle.done)
1285 return bundle->idle.done - time(NULL);
1290 bundle_IsDead(struct bundle *bundle)
1292 return !bundle->links || (bundle->phase == PHASE_DEAD && bundle->CleaningUp);
1295 static struct datalink *
1296 bundle_DatalinkLinkout(struct bundle *bundle, struct datalink *dl)
1298 struct datalink **dlp;
1300 for (dlp = &bundle->links; *dlp; dlp = &(*dlp)->next)
1304 bundle_LinksRemoved(bundle);
1312 bundle_DatalinkLinkin(struct bundle *bundle, struct datalink *dl)
1314 struct datalink **dlp = &bundle->links;
1317 dlp = &(*dlp)->next;
1322 bundle_LinkAdded(bundle, dl);
1323 mp_CheckAutoloadTimer(&bundle->ncp.mp);
1327 bundle_CleanDatalinks(struct bundle *bundle)
1329 struct datalink **dlp = &bundle->links;
1333 if ((*dlp)->state == DATALINK_CLOSED &&
1334 (*dlp)->physical->type &
1335 (PHYS_DIRECT|PHYS_BACKGROUND|PHYS_FOREGROUND)) {
1336 *dlp = datalink_Destroy(*dlp);
1339 dlp = &(*dlp)->next;
1342 bundle_LinksRemoved(bundle);
1346 bundle_DatalinkClone(struct bundle *bundle, struct datalink *dl,
1349 if (bundle2datalink(bundle, name)) {
1350 log_Printf(LogWARN, "Clone: %s: name already exists\n", name);
1354 bundle_DatalinkLinkin(bundle, datalink_Clone(dl, name));
1359 bundle_DatalinkRemove(struct bundle *bundle, struct datalink *dl)
1361 dl = bundle_DatalinkLinkout(bundle, dl);
1363 datalink_Destroy(dl);
1367 bundle_SetLabel(struct bundle *bundle, const char *label)
1370 strncpy(bundle->cfg.label, label, sizeof bundle->cfg.label - 1);
1372 *bundle->cfg.label = '\0';
1376 bundle_GetLabel(struct bundle *bundle)
1378 return *bundle->cfg.label ? bundle->cfg.label : NULL;
1384 struct iovec iov[SCATTER_SEGMENTS];
1385 int niov, expect, f;
1387 iov[0].iov_len = strlen(Version) + 1;
1388 iov[0].iov_base = NULL;
1390 if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1391 log_Printf(LogERROR, "Cannot determine space required for link\n");
1395 for (f = expect = 0; f < niov; f++)
1396 expect += iov[f].iov_len;
1402 bundle_ReceiveDatalink(struct bundle *bundle, int s)
1404 char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int) * SEND_MAXFD];
1405 int niov, expect, f, *fd, nfd, onfd, got;
1406 struct iovec iov[SCATTER_SEGMENTS];
1407 struct cmsghdr *cmsg;
1409 struct datalink *dl;
1412 log_Printf(LogPHASE, "Receiving datalink\n");
1415 * Create our scatter/gather array - passing NULL gets the space
1416 * allocation requirement rather than actually flattening the
1419 iov[0].iov_len = strlen(Version) + 1;
1420 iov[0].iov_base = NULL;
1422 if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) {
1423 log_Printf(LogERROR, "Cannot determine space required for link\n");
1427 /* Allocate the scatter/gather array for recvmsg() */
1428 for (f = expect = 0; f < niov; f++) {
1429 if ((iov[f].iov_base = malloc(iov[f].iov_len)) == NULL) {
1430 log_Printf(LogERROR, "Cannot allocate space to receive link\n");
1434 expect += iov[f].iov_len;
1437 /* Set up our message */
1438 cmsg = (struct cmsghdr *)cmsgbuf;
1439 cmsg->cmsg_len = sizeof cmsgbuf;
1440 cmsg->cmsg_level = SOL_SOCKET;
1441 cmsg->cmsg_type = 0;
1443 memset(&msg, '\0', sizeof msg);
1444 msg.msg_name = NULL;
1445 msg.msg_namelen = 0;
1447 msg.msg_iovlen = 1; /* Only send the version at the first pass */
1448 msg.msg_control = cmsgbuf;
1449 msg.msg_controllen = sizeof cmsgbuf;
1451 log_Printf(LogDEBUG, "Expecting %u scatter/gather bytes\n",
1452 (unsigned)iov[0].iov_len);
1454 if ((got = recvmsg(s, &msg, MSG_WAITALL)) != iov[0].iov_len) {
1456 log_Printf(LogERROR, "Failed recvmsg: %s\n", strerror(errno));
1458 log_Printf(LogERROR, "Failed recvmsg: Got %d, not %u\n",
1459 got, (unsigned)iov[0].iov_len);
1461 free(iov[niov].iov_base);
1465 if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) {
1466 log_Printf(LogERROR, "Recvmsg: no descriptors received !\n");
1468 free(iov[niov].iov_base);
1472 fd = (int *)(cmsg + 1);
1473 nfd = (cmsg->cmsg_len - sizeof *cmsg) / sizeof(int);
1476 log_Printf(LogERROR, "Recvmsg: %d descriptor%s received (too few) !\n",
1477 nfd, nfd == 1 ? "" : "s");
1481 free(iov[niov].iov_base);
1486 * We've successfully received two or more open file descriptors
1487 * through our socket, plus a version string. Make sure it's the
1488 * correct version, and drop the connection if it's not.
1490 if (strncmp(Version, iov[0].iov_base, iov[0].iov_len)) {
1491 log_Printf(LogWARN, "Cannot receive datalink, incorrect version"
1492 " (\"%.*s\", not \"%s\")\n", (int)iov[0].iov_len,
1493 (char *)iov[0].iov_base, Version);
1497 free(iov[niov].iov_base);
1502 * Everything looks good. Send the other side our process id so that
1503 * they can transfer lock ownership, and wait for them to send the
1507 if ((got = write(fd[1], &pid, sizeof pid)) != sizeof pid) {
1509 log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1511 log_Printf(LogERROR, "Failed write: Got %d, not %d\n", got,
1516 free(iov[niov].iov_base);
1520 if ((got = readv(fd[1], iov + 1, niov - 1)) != expect) {
1522 log_Printf(LogERROR, "Failed write: %s\n", strerror(errno));
1524 log_Printf(LogERROR, "Failed write: Got %d, not %d\n", got, expect);
1528 free(iov[niov].iov_base);
1533 onfd = nfd; /* We've got this many in our array */
1534 nfd -= 2; /* Don't include p->fd and our reply descriptor */
1535 niov = 1; /* Skip the version id */
1536 dl = iov2datalink(bundle, iov, &niov, sizeof iov / sizeof *iov, fd[0],
1541 log_Printf(LogERROR, "bundle_ReceiveDatalink: Failed to handle %d "
1542 "auxiliary file descriptors (%d remain)\n", onfd, nfd);
1543 datalink_Destroy(dl);
1548 bundle_DatalinkLinkin(bundle, dl);
1549 datalink_AuthOk(dl);
1550 bundle_CalculateBandwidth(dl->bundle);
1559 free(iov[0].iov_base);
1563 bundle_SendDatalink(struct datalink *dl, int s, struct sockaddr_un *sun)
1565 char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int) * SEND_MAXFD];
1566 const char *constlock;
1568 struct cmsghdr *cmsg;
1570 struct iovec iov[SCATTER_SEGMENTS];
1571 int niov, f, expect, newsid, fd[SEND_MAXFD], nfd, reply[2], got;
1574 log_Printf(LogPHASE, "Transmitting datalink %s\n", dl->name);
1576 /* Record the base device name for a lock transfer later */
1577 constlock = physical_LockedDevice(dl->physical);
1579 lock = alloca(strlen(constlock) + 1);
1580 strcpy(lock, constlock);
1584 bundle_LinkClosed(dl->bundle, dl);
1585 bundle_DatalinkLinkout(dl->bundle, dl);
1587 /* Build our scatter/gather array */
1588 iov[0].iov_len = strlen(Version) + 1;
1589 iov[0].iov_base = strdup(Version);
1593 fd[0] = datalink2iov(dl, iov, &niov, SCATTER_SEGMENTS, fd + 2, &nfd);
1595 if (fd[0] != -1 && socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, reply) != -1) {
1597 * fd[1] is used to get the peer process id back, then to confirm that
1598 * we've transferred any device locks to that process id.
1602 nfd += 2; /* Include fd[0] and fd[1] */
1603 memset(&msg, '\0', sizeof msg);
1605 msg.msg_name = NULL;
1606 msg.msg_namelen = 0;
1608 * Only send the version to start... We used to send the whole lot, but
1609 * this caused problems with our RECVBUF size as a single link is about
1610 * 22k ! This way, we should bump into no limits.
1614 msg.msg_control = cmsgbuf;
1615 msg.msg_controllen = sizeof *cmsg + sizeof(int) * nfd;
1618 cmsg = (struct cmsghdr *)cmsgbuf;
1619 cmsg->cmsg_len = msg.msg_controllen;
1620 cmsg->cmsg_level = SOL_SOCKET;
1621 cmsg->cmsg_type = SCM_RIGHTS;
1623 for (f = 0; f < nfd; f++)
1624 *((int *)(cmsg + 1) + f) = fd[f];
1626 for (f = 1, expect = 0; f < niov; f++)
1627 expect += iov[f].iov_len;
1629 if (setsockopt(reply[0], SOL_SOCKET, SO_SNDBUF, &expect, sizeof(int)) == -1)
1630 log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1632 if (setsockopt(reply[1], SOL_SOCKET, SO_RCVBUF, &expect, sizeof(int)) == -1)
1633 log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect,
1636 log_Printf(LogDEBUG, "Sending %d descriptor%s and %u bytes in scatter"
1637 "/gather array\n", nfd, nfd == 1 ? "" : "s",
1638 (unsigned)iov[0].iov_len);
1640 if ((got = sendmsg(s, &msg, 0)) == -1)
1641 log_Printf(LogERROR, "Failed sendmsg: %s: %s\n",
1642 sun->sun_path, strerror(errno));
1643 else if (got != iov[0].iov_len)
1644 log_Printf(LogERROR, "%s: Failed initial sendmsg: Only sent %d of %u\n",
1645 sun->sun_path, got, (unsigned)iov[0].iov_len);
1647 /* We must get the ACK before closing the descriptor ! */
1650 if ((got = read(reply[0], &newpid, sizeof newpid)) == sizeof newpid) {
1651 log_Printf(LogDEBUG, "Received confirmation from pid %d\n",
1653 if (lock && (res = ID0uu_lock_txfr(lock, newpid)) != UU_LOCK_OK)
1654 log_Printf(LogERROR, "uu_lock_txfr: %s\n", uu_lockerr(res));
1656 log_Printf(LogDEBUG, "Transmitting link (%d bytes)\n", expect);
1657 if ((got = writev(reply[0], iov + 1, niov - 1)) != expect) {
1659 log_Printf(LogERROR, "%s: Failed writev: %s\n",
1660 sun->sun_path, strerror(errno));
1662 log_Printf(LogERROR, "%s: Failed writev: Wrote %d of %d\n",
1663 sun->sun_path, got, expect);
1665 } else if (got == -1)
1666 log_Printf(LogERROR, "%s: Failed socketpair read: %s\n",
1667 sun->sun_path, strerror(errno));
1669 log_Printf(LogERROR, "%s: Failed socketpair read: Got %d of %d\n",
1670 sun->sun_path, got, (int)(sizeof newpid));
1676 newsid = Enabled(dl->bundle, OPT_KEEPSESSION) ||
1677 tcgetpgrp(fd[0]) == getpgrp();
1681 bundle_setsid(dl->bundle, got != -1);
1686 free(iov[niov].iov_base);
1690 bundle_RenameDatalink(struct bundle *bundle, struct datalink *ndl,
1693 struct datalink *dl;
1695 if (!strcasecmp(ndl->name, name))
1698 for (dl = bundle->links; dl; dl = dl->next)
1699 if (!strcasecmp(dl->name, name))
1702 datalink_Rename(ndl, name);
1707 bundle_SetMode(struct bundle *bundle, struct datalink *dl, int mode)
1711 omode = dl->physical->type;
1715 if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO))
1716 /* First auto link */
1717 if (bundle->ncp.ipcp.peer_ip.s_addr == INADDR_ANY) {
1718 log_Printf(LogWARN, "You must `set ifaddr' or `open' before"
1719 " changing mode to %s\n", mode2Nam(mode));
1723 if (!datalink_SetMode(dl, mode))
1726 if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO) &&
1727 bundle->phase != PHASE_NETWORK)
1728 /* First auto link, we need an interface */
1729 ipcp_InterfaceUp(&bundle->ncp.ipcp);
1731 /* Regenerate phys_type and adjust idle timer */
1732 bundle_LinksRemoved(bundle);
1738 bundle_setsid(struct bundle *bundle, int holdsession)
1741 * Lose the current session. This means getting rid of our pid
1742 * too so that the tty device will really go away, and any getty
1743 * etc will be allowed to restart.
1748 struct datalink *dl;
1750 if (!holdsession && bundle_IsDead(bundle)) {
1752 * No need to lose our session after all... we're going away anyway
1754 * We should really stop the timer and pause if holdsession is set and
1755 * the bundle's dead, but that leaves other resources lying about :-(
1761 if (pipe(fds) == -1) {
1762 log_Printf(LogERROR, "pipe: %s\n", strerror(errno));
1765 switch ((pid = fork())) {
1767 log_Printf(LogERROR, "fork: %s\n", strerror(errno));
1773 read(fds[0], &done, 1); /* uu_locks are mine ! */
1775 if (pipe(fds) == -1) {
1776 log_Printf(LogERROR, "pipe(2): %s\n", strerror(errno));
1779 switch ((pid = fork())) {
1781 log_Printf(LogERROR, "fork(2): %s\n", strerror(errno));
1787 bundle_LockTun(bundle); /* update pid */
1788 read(fds[0], &done, 1); /* uu_locks are mine ! */
1791 bundle_ChangedPID(bundle);
1792 log_Printf(LogDEBUG, "%d -> %d: %s session control\n",
1793 (int)orig, (int)getpid(),
1794 holdsession ? "Passed" : "Dropped");
1795 timer_InitService(0); /* Start the Timer Service */
1799 /* Give away all our physical locks (to the final process) */
1800 for (dl = bundle->links; dl; dl = dl->next)
1801 if (dl->state != DATALINK_CLOSED)
1802 physical_ChangedPid(dl->physical, pid);
1803 write(fds[1], "!", 1); /* done */
1811 /* Give away all our physical locks (to the intermediate process) */
1812 for (dl = bundle->links; dl; dl = dl->next)
1813 if (dl->state != DATALINK_CLOSED)
1814 physical_ChangedPid(dl->physical, pid);
1815 write(fds[1], "!", 1); /* done */
1820 timer_TermService();
1821 signal(SIGPIPE, SIG_DFL);
1822 signal(SIGALRM, SIG_DFL);
1823 signal(SIGHUP, SIG_DFL);
1824 signal(SIGTERM, SIG_DFL);
1825 signal(SIGINT, SIG_DFL);
1826 signal(SIGQUIT, SIG_DFL);
1827 for (fd = getdtablesize(); fd >= 0; fd--)
1830 * Reap the intermediate process. As we're not exiting but the
1831 * intermediate is, we don't want it to become defunct.
1833 waitpid(pid, &status, 0);
1834 /* Tweak our process arguments.... */
1835 ID0setproctitle("session owner");
1836 setuid(ID0realuid());
1838 * Hang around for a HUP. This should happen as soon as the
1839 * ppp that we passed our ctty descriptor to closes it.
1840 * NOTE: If this process dies, the passed descriptor becomes
1841 * invalid and will give a select() error by setting one
1842 * of the error fds, aborting the other ppp. We don't
1843 * want that to happen !
1853 bundle_HighestState(struct bundle *bundle)
1855 struct datalink *dl;
1856 int result = DATALINK_CLOSED;
1858 for (dl = bundle->links; dl; dl = dl->next)
1859 if (result < dl->state)
1866 bundle_Exception(struct bundle *bundle, int fd)
1868 struct datalink *dl;
1870 for (dl = bundle->links; dl; dl = dl->next)
1871 if (dl->physical->fd == fd) {
1872 datalink_Down(dl, CLOSE_NORMAL);
1880 bundle_AdjustFilters(struct bundle *bundle, struct in_addr *my_ip,
1881 struct in_addr *peer_ip)
1883 filter_AdjustAddr(&bundle->filter.in, my_ip, peer_ip, NULL);
1884 filter_AdjustAddr(&bundle->filter.out, my_ip, peer_ip, NULL);
1885 filter_AdjustAddr(&bundle->filter.dial, my_ip, peer_ip, NULL);
1886 filter_AdjustAddr(&bundle->filter.alive, my_ip, peer_ip, NULL);
1890 bundle_AdjustDNS(struct bundle *bundle, struct in_addr dns[2])
1892 filter_AdjustAddr(&bundle->filter.in, NULL, NULL, dns);
1893 filter_AdjustAddr(&bundle->filter.out, NULL, NULL, dns);
1894 filter_AdjustAddr(&bundle->filter.dial, NULL, NULL, dns);
1895 filter_AdjustAddr(&bundle->filter.alive, NULL, NULL, dns);
1899 bundle_CalculateBandwidth(struct bundle *bundle)
1901 struct datalink *dl;
1904 bundle->bandwidth = 0;
1906 for (dl = bundle->links; dl; dl = dl->next)
1907 if (dl->state == DATALINK_OPEN) {
1908 if ((sp = dl->mp.bandwidth) == 0 &&
1909 (sp = physical_GetSpeed(dl->physical)) == 0)
1910 log_Printf(LogDEBUG, "%s: %s: Cannot determine bandwidth\n",
1911 dl->name, dl->physical->name.full);
1913 bundle->bandwidth += sp;
1914 if (!bundle->ncp.mp.active) {
1915 mtu = dl->physical->link.lcp.his_mru;
1920 if(bundle->bandwidth == 0)
1921 bundle->bandwidth = 115200; /* Shrug */
1923 if (bundle->ncp.mp.active)
1924 mtu = bundle->ncp.mp.peer_mrru;
1929 if (bundle->radius.valid && bundle->radius.mtu && bundle->radius.mtu < mtu) {
1930 log_Printf(LogLCP, "Reducing MTU to radius value %lu\n",
1931 bundle->radius.mtu);
1932 mtu = bundle->radius.mtu;
1936 tun_configure(bundle, mtu);
1940 bundle_AutoAdjust(struct bundle *bundle, int percent, int what)
1942 struct datalink *dl, *choice, *otherlinkup;
1944 choice = otherlinkup = NULL;
1945 for (dl = bundle->links; dl; dl = dl->next)
1946 if (dl->physical->type == PHYS_AUTO) {
1947 if (dl->state == DATALINK_OPEN) {
1948 if (what == AUTO_DOWN) {
1950 otherlinkup = choice;
1953 } else if (dl->state == DATALINK_CLOSED) {
1954 if (what == AUTO_UP) {
1959 /* An auto link in an intermediate state - forget it for the moment */
1963 } else if (dl->state == DATALINK_OPEN && what == AUTO_DOWN)
1967 if (what == AUTO_UP) {
1968 log_Printf(LogPHASE, "%d%% saturation -> Opening link ``%s''\n",
1969 percent, choice->name);
1970 datalink_Up(choice, 1, 1);
1971 mp_StopAutoloadTimer(&bundle->ncp.mp);
1972 } else if (otherlinkup) { /* Only bring the second-last link down */
1973 log_Printf(LogPHASE, "%d%% saturation -> Closing link ``%s''\n",
1974 percent, choice->name);
1975 datalink_Close(choice, CLOSE_STAYDOWN);
1976 mp_StopAutoloadTimer(&bundle->ncp.mp);
1982 bundle_WantAutoloadTimer(struct bundle *bundle)
1984 struct datalink *dl;
1985 int autolink, opened;
1987 if (bundle->phase == PHASE_NETWORK) {
1988 for (autolink = opened = 0, dl = bundle->links; dl; dl = dl->next)
1989 if (dl->physical->type == PHYS_AUTO) {
1990 if (++autolink == 2 || (autolink == 1 && opened))
1991 /* Two auto links or one auto and one open in NETWORK phase */
1993 } else if (dl->state == DATALINK_OPEN) {
1996 /* One auto and one open link in NETWORK phase */
2005 bundle_ChangedPID(struct bundle *bundle)
2008 ioctl(bundle->dev.fd, TUNSIFPID, 0);