diff --git a/usr.sbin/ppp/bundle.c b/usr.sbin/ppp/bundle.c index 1af2924b8d56..91e92cf009bd 100644 --- a/usr.sbin/ppp/bundle.c +++ b/usr.sbin/ppp/bundle.c @@ -1,2018 +1,2018 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 1998 Brian Somers * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #include #include #include #include #include /* For TUNS* ioctls */ #include #include #include #include #include #include #ifdef __OpenBSD__ #include #else #include #endif #include #include #include #include #include #include #include #include #include #include "layer.h" #include "defs.h" #include "command.h" #include "mbuf.h" #include "log.h" #include "id.h" #include "timer.h" #include "fsm.h" #include "iplist.h" #include "lqr.h" #include "hdlc.h" #include "throughput.h" #include "slcompress.h" #include "ncpaddr.h" #include "ip.h" #include "ipcp.h" #include "filter.h" #include "descriptor.h" #include "route.h" #include "lcp.h" #include "ccp.h" #include "link.h" #include "mp.h" #ifndef NORADIUS #include "radius.h" #endif #include "ipv6cp.h" #include "ncp.h" #include "bundle.h" #include "async.h" #include "physical.h" #include "auth.h" #include "proto.h" #include "chap.h" #include "tun.h" #include "prompt.h" #include "chat.h" #include "cbcp.h" #include "datalink.h" #include "iface.h" #include "server.h" #include "probe.h" #ifndef NODES #include "mppe.h" #endif #define SCATTER_SEGMENTS 7 /* version, datalink, name, physical, throughput, throughput, device */ #define SEND_MAXFD 3 /* Max file descriptors passed through the local domain socket */ static int bundle_RemainingIdleTime(struct bundle *); static const char * const PhaseNames[] = { "Dead", "Establish", "Authenticate", "Network", "Terminate" }; const char * bundle_PhaseName(struct bundle *bundle) { return bundle->phase <= PHASE_TERMINATE ? PhaseNames[bundle->phase] : "unknown"; } void bundle_NewPhase(struct bundle *bundle, u_int new) { if (new == bundle->phase) return; if (new <= PHASE_TERMINATE) log_Printf(LogPHASE, "bundle: %s\n", PhaseNames[new]); switch (new) { case PHASE_DEAD: bundle->phase = new; #ifndef NODES MPPE_MasterKeyValid = 0; #endif log_DisplayPrompts(); break; case PHASE_ESTABLISH: bundle->phase = new; break; case PHASE_AUTHENTICATE: bundle->phase = new; log_DisplayPrompts(); break; case PHASE_NETWORK: if (ncp_fsmStart(&bundle->ncp, bundle)) { bundle->phase = new; log_DisplayPrompts(); } else { log_Printf(LogPHASE, "bundle: All NCPs are disabled\n"); bundle_Close(bundle, NULL, CLOSE_STAYDOWN); } break; case PHASE_TERMINATE: bundle->phase = new; mp_Down(&bundle->ncp.mp); log_DisplayPrompts(); break; } } static void bundle_LayerStart(void *v __unused, struct fsm *fp __unused) { /* The given FSM is about to start up ! */ } void bundle_Notify(struct bundle *bundle, char c) { if (bundle->notify.fd != -1) { int ret; ret = write(bundle->notify.fd, &c, 1); if (c != EX_REDIAL && c != EX_RECONNECT) { if (ret == 1) log_Printf(LogCHAT, "Parent notified of %s\n", c == EX_NORMAL ? "success" : "failure"); else log_Printf(LogERROR, "Failed to notify parent of success\n"); close(bundle->notify.fd); bundle->notify.fd = -1; } else if (ret == 1) log_Printf(LogCHAT, "Parent notified of %s\n", ex_desc(c)); else log_Printf(LogERROR, "Failed to notify parent of %s\n", ex_desc(c)); } } static void bundle_ClearQueues(void *v) { struct bundle *bundle = (struct bundle *)v; struct datalink *dl; log_Printf(LogPHASE, "Clearing choked output queue\n"); timer_Stop(&bundle->choked.timer); /* * Emergency time: * * We've had a full queue for PACKET_DEL_SECS seconds without being * able to get rid of any of the packets. We've probably given up * on the redials at this point, and the queued data has almost * definitely been timed out by the layer above. As this is preventing * us from reading the TUN_NAME device (we don't want to buffer stuff * indefinitely), we may as well nuke this data and start with a clean * slate ! * * Unfortunately, this has the side effect of shafting any compression * dictionaries in use (causing the relevant RESET_REQ/RESET_ACK). */ ncp_DeleteQueues(&bundle->ncp); for (dl = bundle->links; dl; dl = dl->next) physical_DeleteQueue(dl->physical); } static void bundle_LinkAdded(struct bundle *bundle, struct datalink *dl) { bundle->phys_type.all |= dl->physical->type; if (dl->state == DATALINK_OPEN) bundle->phys_type.open |= dl->physical->type; #ifndef NORADIUS if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) != bundle->phys_type.open && bundle->session.timer.state == TIMER_STOPPED) if (bundle->radius.sessiontime) bundle_StartSessionTimer(bundle, 0); #endif if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) != bundle->phys_type.open && bundle->idle.timer.state == TIMER_STOPPED) /* We may need to start our idle timer */ bundle_StartIdleTimer(bundle, 0); } void bundle_LinksRemoved(struct bundle *bundle) { struct datalink *dl; bundle->phys_type.all = bundle->phys_type.open = 0; for (dl = bundle->links; dl; dl = dl->next) bundle_LinkAdded(bundle, dl); bundle_CalculateBandwidth(bundle); mp_CheckAutoloadTimer(&bundle->ncp.mp); if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) == bundle->phys_type.open) { #ifndef NORADIUS if (bundle->radius.sessiontime) bundle_StopSessionTimer(bundle); #endif bundle_StopIdleTimer(bundle); } } static void bundle_LayerUp(void *v, struct fsm *fp) { /* * The given fsm is now up * If it's an LCP, adjust our phys_mode.open value and check the * autoload timer. * If it's the first NCP, calculate our bandwidth * If it's the first NCP, set our ``upat'' time * If it's the first NCP, start the idle timer. * If it's an NCP, tell our -background parent to go away. * If it's the first NCP, start the autoload timer */ struct bundle *bundle = (struct bundle *)v; if (fp->proto == PROTO_LCP) { struct physical *p = link2physical(fp->link); bundle_LinkAdded(bundle, p->dl); mp_CheckAutoloadTimer(&bundle->ncp.mp); } else if (isncp(fp->proto)) { if (ncp_LayersOpen(&fp->bundle->ncp) == 1) { bundle_CalculateBandwidth(fp->bundle); time(&bundle->upat); #ifndef NORADIUS if (bundle->radius.sessiontime) bundle_StartSessionTimer(bundle, 0); #endif bundle_StartIdleTimer(bundle, 0); mp_CheckAutoloadTimer(&fp->bundle->ncp.mp); } bundle_Notify(bundle, EX_NORMAL); } else if (fp->proto == PROTO_CCP) bundle_CalculateBandwidth(fp->bundle); /* Against ccp_MTUOverhead */ } static void bundle_LayerDown(void *v, struct fsm *fp) { /* * The given FSM has been told to come down. * If it's our last NCP, stop the idle timer. * If it's our last NCP, clear our ``upat'' value. * If it's our last NCP, stop the autoload timer * If it's an LCP, adjust our phys_type.open value and any timers. * If it's an LCP and we're in multilink mode, adjust our tun * If it's the last LCP, down all NCPs * speed and make sure our minimum sequence number is adjusted. */ struct bundle *bundle = (struct bundle *)v; if (isncp(fp->proto)) { if (ncp_LayersOpen(&fp->bundle->ncp) == 0) { #ifndef NORADIUS if (bundle->radius.sessiontime) bundle_StopSessionTimer(bundle); #endif bundle_StopIdleTimer(bundle); bundle->upat = 0; mp_StopAutoloadTimer(&bundle->ncp.mp); } } else if (fp->proto == PROTO_LCP) { struct datalink *dl; struct datalink *lost; int others_active; bundle_LinksRemoved(bundle); /* adjust timers & phys_type values */ lost = NULL; others_active = 0; for (dl = bundle->links; dl; dl = dl->next) { if (fp == &dl->physical->link.lcp.fsm) lost = dl; else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP) others_active++; } if (bundle->ncp.mp.active) { bundle_CalculateBandwidth(bundle); if (lost) mp_LinkLost(&bundle->ncp.mp, lost); else log_Printf(LogALERT, "Oops, lost an unrecognised datalink (%s) !\n", fp->link->name); } if (!others_active) { /* Down the NCPs. We don't expect to get fsm_Close()d ourself ! */ ncp2initial(&bundle->ncp); mp_Down(&bundle->ncp.mp); } } } static void bundle_LayerFinish(void *v, struct fsm *fp) { /* The given fsm is now down (fp cannot be NULL) * * If it's the last NCP, fsm_Close all LCPs * If it's the last NCP, bring any MP layer down */ struct bundle *bundle = (struct bundle *)v; struct datalink *dl; if (isncp(fp->proto) && !ncp_LayersUnfinished(&bundle->ncp)) { if (bundle_Phase(bundle) != PHASE_DEAD) bundle_NewPhase(bundle, PHASE_TERMINATE); for (dl = bundle->links; dl; dl = dl->next) if (dl->state == DATALINK_OPEN) datalink_Close(dl, CLOSE_STAYDOWN); fsm2initial(fp); mp_Down(&bundle->ncp.mp); } } void bundle_Close(struct bundle *bundle, const char *name, int how) { /* * Please close the given datalink. * If name == NULL or name is the last datalink, fsm_Close all NCPs * (except our MP) * If it isn't the last datalink, just Close that datalink. */ struct datalink *dl, *this_dl; int others_active; others_active = 0; this_dl = NULL; for (dl = bundle->links; dl; dl = dl->next) { if (name && !strcasecmp(name, dl->name)) this_dl = dl; if (name == NULL || this_dl == dl) { switch (how) { case CLOSE_LCP: datalink_DontHangup(dl); break; case CLOSE_STAYDOWN: datalink_StayDown(dl); break; } } else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP) others_active++; } if (name && this_dl == NULL) { log_Printf(LogWARN, "%s: Invalid datalink name\n", name); return; } if (!others_active) { #ifndef NORADIUS if (bundle->radius.sessiontime) bundle_StopSessionTimer(bundle); #endif bundle_StopIdleTimer(bundle); if (ncp_LayersUnfinished(&bundle->ncp)) ncp_Close(&bundle->ncp); else { ncp2initial(&bundle->ncp); mp_Down(&bundle->ncp.mp); for (dl = bundle->links; dl; dl = dl->next) datalink_Close(dl, how); } } else if (this_dl && this_dl->state != DATALINK_CLOSED && this_dl->state != DATALINK_HANGUP) datalink_Close(this_dl, how); } void bundle_Down(struct bundle *bundle, int how) { struct datalink *dl; for (dl = bundle->links; dl; dl = dl->next) datalink_Down(dl, how); } static int bundle_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n) { struct bundle *bundle = descriptor2bundle(d); struct datalink *dl; int result, nlinks; u_short ifqueue; size_t queued; result = 0; /* If there are aren't many packets queued, look for some more. */ for (nlinks = 0, dl = bundle->links; dl; dl = dl->next) nlinks++; if (nlinks) { queued = r ? ncp_FillPhysicalQueues(&bundle->ncp, bundle) : ncp_QueueLen(&bundle->ncp); if (r && (bundle->phase == PHASE_NETWORK || bundle->phys_type.all & PHYS_AUTO)) { /* enough surplus so that we can tell if we're getting swamped */ ifqueue = nlinks > bundle->cfg.ifqueue ? nlinks : bundle->cfg.ifqueue; if (queued < ifqueue) { /* Not enough - select() for more */ if (bundle->choked.timer.state == TIMER_RUNNING) timer_Stop(&bundle->choked.timer); /* Not needed any more */ FD_SET(bundle->dev.fd, r); if (*n < bundle->dev.fd + 1) *n = bundle->dev.fd + 1; log_Printf(LogTIMER, "%s: fdset(r) %d\n", TUN_NAME, bundle->dev.fd); result++; } else if (bundle->choked.timer.state == TIMER_STOPPED) { bundle->choked.timer.func = bundle_ClearQueues; bundle->choked.timer.name = "output choke"; bundle->choked.timer.load = bundle->cfg.choked.timeout * SECTICKS; bundle->choked.timer.arg = bundle; timer_Start(&bundle->choked.timer); } } } #ifndef NORADIUS result += descriptor_UpdateSet(&bundle->radius.desc, r, w, e, n); #endif /* Which links need a select() ? */ for (dl = bundle->links; dl; dl = dl->next) result += descriptor_UpdateSet(&dl->desc, r, w, e, n); /* * This *MUST* be called after the datalink UpdateSet()s as it * might be ``holding'' one of the datalinks (death-row) and * wants to be able to de-select() it from the descriptor set. */ result += descriptor_UpdateSet(&bundle->ncp.mp.server.desc, r, w, e, n); return result; } static int bundle_IsSet(struct fdescriptor *d, const fd_set *fdset) { struct bundle *bundle = descriptor2bundle(d); struct datalink *dl; for (dl = bundle->links; dl; dl = dl->next) if (descriptor_IsSet(&dl->desc, fdset)) return 1; #ifndef NORADIUS if (descriptor_IsSet(&bundle->radius.desc, fdset)) return 1; #endif if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset)) return 1; return FD_ISSET(bundle->dev.fd, fdset); } static void bundle_DescriptorRead(struct fdescriptor *d __unused, struct bundle *bundle, const fd_set *fdset) { struct datalink *dl; unsigned secs; u_int32_t af; if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset)) descriptor_Read(&bundle->ncp.mp.server.desc, bundle, fdset); for (dl = bundle->links; dl; dl = dl->next) if (descriptor_IsSet(&dl->desc, fdset)) descriptor_Read(&dl->desc, bundle, fdset); #ifndef NORADIUS if (descriptor_IsSet(&bundle->radius.desc, fdset)) descriptor_Read(&bundle->radius.desc, bundle, fdset); #endif if (FD_ISSET(bundle->dev.fd, fdset)) { struct tun_data tun; int n, pri; u_char *data; size_t sz; if (bundle->dev.header) { data = (u_char *)&tun; sz = sizeof tun; } else { data = tun.data; sz = sizeof tun.data; } /* something to read from tun */ n = read(bundle->dev.fd, data, sz); if (n < 0) { log_Printf(LogWARN, "%s: read: %s\n", bundle->dev.Name, strerror(errno)); return; } if (bundle->dev.header) { n -= sz - sizeof tun.data; if (n <= 0) { log_Printf(LogERROR, "%s: read: Got only %d bytes of data !\n", bundle->dev.Name, n); return; } af = ntohl(tun.header.family); #ifndef NOINET6 if (af != AF_INET && af != AF_INET6) #else if (af != AF_INET) #endif /* XXX: Should be maintaining drop/family counts ! */ return; } else af = AF_INET; if (af == AF_INET && ((struct ip *)tun.data)->ip_dst.s_addr == bundle->ncp.ipcp.my_ip.s_addr) { /* we've been asked to send something addressed *to* us :( */ if (Enabled(bundle, OPT_LOOPBACK)) { pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.in, NULL, NULL); if (pri >= 0) { n += sz - sizeof tun.data; write(bundle->dev.fd, data, n); log_Printf(LogDEBUG, "Looped back packet addressed to myself\n"); } return; } else log_Printf(LogDEBUG, "Oops - forwarding packet addressed to myself\n"); } /* * Process on-demand dialup. Output packets are queued within the tunnel * device until the appropriate NCP is opened. */ if (bundle_Phase(bundle) == PHASE_DEAD) { /* * Note, we must be in AUTO mode :-/ otherwise our interface should * *not* be UP and we can't receive data */ pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.dial, NULL, NULL); if (pri >= 0) bundle_Open(bundle, NULL, PHYS_AUTO, 0); else /* * Drop the packet. If we were to queue it, we'd just end up with * a pile of timed-out data in our output queue by the time we get * around to actually dialing. We'd also prematurely reach the * threshold at which we stop select()ing to read() the tun * device - breaking auto-dial. */ return; } secs = 0; pri = PacketCheck(bundle, af, tun.data, n, &bundle->filter.out, NULL, &secs); if (pri >= 0) { /* Prepend the number of seconds timeout given in the filter */ tun.header.timeout = secs; ncp_Enqueue(&bundle->ncp, af, pri, (char *)&tun, n + sizeof tun.header); } } } static int bundle_DescriptorWrite(struct fdescriptor *d __unused, struct bundle *bundle, const fd_set *fdset) { struct datalink *dl; int result = 0; /* This is not actually necessary as struct mpserver doesn't Write() */ if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset)) if (descriptor_Write(&bundle->ncp.mp.server.desc, bundle, fdset) == 1) result++; for (dl = bundle->links; dl; dl = dl->next) if (descriptor_IsSet(&dl->desc, fdset)) switch (descriptor_Write(&dl->desc, bundle, fdset)) { case -1: datalink_ComeDown(dl, CLOSE_NORMAL); break; case 1: result++; } return result; } void bundle_LockTun(struct bundle *bundle) { FILE *lockfile; char pidfile[PATH_MAX]; snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit); lockfile = ID0fopen(pidfile, "w"); if (lockfile != NULL) { fprintf(lockfile, "%d\n", (int)getpid()); fclose(lockfile); } else log_Printf(LogERROR, "Warning: Can't create %s: %s\n", pidfile, strerror(errno)); } static void bundle_UnlockTun(struct bundle *bundle) { char pidfile[PATH_MAX]; snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit); ID0unlink(pidfile); } struct bundle * bundle_Create(const char *prefix, int type, int unit) { static struct bundle bundle; /* there can be only one */ int enoentcount, err, minunit, maxunit; const char *ifname; #if defined(__FreeBSD__) && !defined(NOKLDLOAD) int kldtried; #endif #if defined(TUNSIFMODE) || defined(TUNSLMODE) || defined(TUNSIFHEAD) int iff; #endif if (bundle.iface != NULL) { /* Already allocated ! */ log_Printf(LogALERT, "bundle_Create: There's only one BUNDLE !\n"); return NULL; } if (unit == -1) { minunit = 0; maxunit = -1; } else { minunit = unit; maxunit = unit + 1; } err = ENOENT; enoentcount = 0; #if defined(__FreeBSD__) && !defined(NOKLDLOAD) kldtried = 0; #endif for (bundle.unit = minunit; bundle.unit != maxunit; bundle.unit++) { snprintf(bundle.dev.Name, sizeof bundle.dev.Name, "%s%d", prefix, bundle.unit); bundle.dev.fd = ID0open(bundle.dev.Name, O_RDWR); if (bundle.dev.fd >= 0) break; else if (errno == ENXIO || errno == ENOENT) { #if defined(__FreeBSD__) && !defined(NOKLDLOAD) if (bundle.unit == minunit && !kldtried++) { /* * Attempt to load the tunnel interface KLD if it isn't loaded * already. */ if (loadmodules(LOAD_VERBOSLY, "if_tun", NULL)) bundle.unit--; continue; } #endif if (errno != ENOENT || ++enoentcount > 2) { err = errno; break; } } else err = errno; } if (bundle.dev.fd < 0) { if (unit == -1) log_Printf(LogWARN, "No available tunnel devices found (%s)\n", strerror(err)); else log_Printf(LogWARN, "%s%d: %s\n", prefix, unit, strerror(err)); return NULL; } log_SetTun(bundle.unit, NULL); ifname = strrchr(bundle.dev.Name, '/'); if (ifname == NULL) ifname = bundle.dev.Name; else ifname++; bundle.iface = iface_Create(ifname); if (bundle.iface == NULL) { close(bundle.dev.fd); return NULL; } #ifdef TUNSIFMODE /* Make sure we're POINTOPOINT & IFF_MULTICAST */ iff = IFF_POINTOPOINT | IFF_MULTICAST; if (ID0ioctl(bundle.dev.fd, TUNSIFMODE, &iff) < 0) log_Printf(LogERROR, "bundle_Create: ioctl(TUNSIFMODE): %s\n", strerror(errno)); #endif #ifdef TUNSLMODE /* Make sure we're not prepending sockaddrs */ iff = 0; if (ID0ioctl(bundle.dev.fd, TUNSLMODE, &iff) < 0) log_Printf(LogERROR, "bundle_Create: ioctl(TUNSLMODE): %s\n", strerror(errno)); #endif #ifdef TUNSIFHEAD /* We want the address family please ! */ iff = 1; if (ID0ioctl(bundle.dev.fd, TUNSIFHEAD, &iff) < 0) { log_Printf(LogERROR, "bundle_Create: ioctl(TUNSIFHEAD): %s\n", strerror(errno)); bundle.dev.header = 0; } else bundle.dev.header = 1; #else #ifdef __OpenBSD__ /* Always present for OpenBSD */ bundle.dev.header = 1; #else /* * If TUNSIFHEAD isn't available and we're not OpenBSD, assume * everything's AF_INET (hopefully the tun device won't pass us * anything else !). */ bundle.dev.header = 0; #endif #endif log_Printf(LogPHASE, "Using interface: %s\n", ifname); bundle.bandwidth = 0; bundle.routing_seq = 0; bundle.phase = PHASE_DEAD; bundle.CleaningUp = 0; bundle.NatEnabled = 0; bundle.fsm.LayerStart = bundle_LayerStart; bundle.fsm.LayerUp = bundle_LayerUp; bundle.fsm.LayerDown = bundle_LayerDown; bundle.fsm.LayerFinish = bundle_LayerFinish; bundle.fsm.object = &bundle; bundle.cfg.idle.timeout = NCP_IDLE_TIMEOUT; bundle.cfg.idle.min_timeout = 0; *bundle.cfg.auth.name = '\0'; *bundle.cfg.auth.key = '\0'; bundle.cfg.optmask = (1ull << OPT_IDCHECK) | (1ull << OPT_LOOPBACK) | (1ull << OPT_SROUTES) | (1ull << OPT_TCPMSSFIXUP) | (1ull << OPT_THROUGHPUT) | (1ull << OPT_UTMP) | (1ull << OPT_NAS_IP_ADDRESS) | (1ull << OPT_NAS_IDENTIFIER); #ifndef NOINET6 opt_enable(&bundle, OPT_IPCP); if (probe.ipv6_available) opt_enable(&bundle, OPT_IPV6CP); #endif *bundle.cfg.label = '\0'; bundle.cfg.ifqueue = DEF_IFQUEUE; bundle.cfg.choked.timeout = CHOKED_TIMEOUT; bundle.phys_type.all = type; bundle.phys_type.open = 0; bundle.upat = 0; bundle.links = datalink_Create("deflink", &bundle, type); if (bundle.links == NULL) { log_Printf(LogALERT, "Cannot create data link: %s\n", strerror(errno)); iface_Free(bundle.iface); bundle.iface = NULL; close(bundle.dev.fd); return NULL; } bundle.desc.type = BUNDLE_DESCRIPTOR; bundle.desc.UpdateSet = bundle_UpdateSet; bundle.desc.IsSet = bundle_IsSet; bundle.desc.Read = bundle_DescriptorRead; bundle.desc.Write = bundle_DescriptorWrite; ncp_Init(&bundle.ncp, &bundle); memset(&bundle.filter, '\0', sizeof bundle.filter); bundle.filter.in.fragok = bundle.filter.in.logok = 1; bundle.filter.in.name = "IN"; bundle.filter.out.fragok = bundle.filter.out.logok = 1; bundle.filter.out.name = "OUT"; bundle.filter.dial.name = "DIAL"; bundle.filter.dial.logok = 1; bundle.filter.alive.name = "ALIVE"; bundle.filter.alive.logok = 1; { int i; for (i = 0; i < MAXFILTERS; i++) { bundle.filter.in.rule[i].f_action = A_NONE; bundle.filter.out.rule[i].f_action = A_NONE; bundle.filter.dial.rule[i].f_action = A_NONE; bundle.filter.alive.rule[i].f_action = A_NONE; } } memset(&bundle.idle.timer, '\0', sizeof bundle.idle.timer); bundle.idle.done = 0; bundle.notify.fd = -1; memset(&bundle.choked.timer, '\0', sizeof bundle.choked.timer); #ifndef NORADIUS radius_Init(&bundle.radius); #endif /* Clean out any leftover crud */ iface_Clear(bundle.iface, &bundle.ncp, 0, IFACE_CLEAR_ALL); bundle_LockTun(&bundle); return &bundle; } static void bundle_DownInterface(struct bundle *bundle) { route_IfDelete(bundle, 1); iface_ClearFlags(bundle->iface->name, IFF_UP); } void bundle_Destroy(struct bundle *bundle) { struct datalink *dl; /* * Clean up the interface. We don't really need to do the timer_Stop()s, * mp_Down(), iface_Clear() and bundle_DownInterface() unless we're getting * out under exceptional conditions such as a descriptor exception. */ timer_Stop(&bundle->idle.timer); timer_Stop(&bundle->choked.timer); mp_Down(&bundle->ncp.mp); iface_Clear(bundle->iface, &bundle->ncp, 0, IFACE_CLEAR_ALL); bundle_DownInterface(bundle); #ifndef NORADIUS /* Tell the radius server the bad news */ radius_Destroy(&bundle->radius); #endif /* Again, these are all DATALINK_CLOSED unless we're abending */ dl = bundle->links; while (dl) dl = datalink_Destroy(dl); ncp_Destroy(&bundle->ncp); close(bundle->dev.fd); bundle_UnlockTun(bundle); /* In case we never made PHASE_NETWORK */ bundle_Notify(bundle, EX_ERRDEAD); iface_Destroy(bundle->iface); bundle->iface = NULL; } void bundle_LinkClosed(struct bundle *bundle, struct datalink *dl) { /* * Our datalink has closed. * CleanDatalinks() (called from DoLoop()) will remove closed * BACKGROUND, FOREGROUND and DIRECT links. * If it's the last data link, enter phase DEAD. * * NOTE: dl may not be in our list (bundle_SendDatalink()) ! */ struct datalink *odl; int other_links; log_SetTtyCommandMode(dl); other_links = 0; for (odl = bundle->links; odl; odl = odl->next) if (odl != dl && odl->state != DATALINK_CLOSED) other_links++; if (!other_links) { if (dl->physical->type != PHYS_AUTO) /* Not in -auto mode */ bundle_DownInterface(bundle); ncp2initial(&bundle->ncp); mp_Down(&bundle->ncp.mp); bundle_NewPhase(bundle, PHASE_DEAD); #ifndef NORADIUS if (bundle->radius.sessiontime) bundle_StopSessionTimer(bundle); #endif bundle_StopIdleTimer(bundle); } } void bundle_Open(struct bundle *bundle, const char *name, int mask, int force) { /* * Please open the given datalink, or all if name == NULL */ struct datalink *dl; for (dl = bundle->links; dl; dl = dl->next) if (name == NULL || !strcasecmp(dl->name, name)) { if ((mask & dl->physical->type) && (dl->state == DATALINK_CLOSED || (force && dl->state == DATALINK_OPENING && dl->dial.timer.state == TIMER_RUNNING) || dl->state == DATALINK_READY)) { timer_Stop(&dl->dial.timer); /* We're finished with this */ datalink_Up(dl, 1, 1); if (mask & PHYS_AUTO) break; /* Only one AUTO link at a time */ } if (name != NULL) break; } } struct datalink * bundle2datalink(struct bundle *bundle, const char *name) { struct datalink *dl; if (name != NULL) { for (dl = bundle->links; dl; dl = dl->next) if (!strcasecmp(dl->name, name)) return dl; } else if (bundle->links && !bundle->links->next) return bundle->links; return NULL; } int bundle_ShowLinks(struct cmdargs const *arg) { struct datalink *dl; struct pppThroughput *t; unsigned long long octets; int secs; for (dl = arg->bundle->links; dl; dl = dl->next) { octets = MAX(dl->physical->link.stats.total.in.OctetsPerSecond, dl->physical->link.stats.total.out.OctetsPerSecond); prompt_Printf(arg->prompt, "Name: %s [%s, %s]", dl->name, mode2Nam(dl->physical->type), datalink_State(dl)); if (dl->physical->link.stats.total.rolling && dl->state == DATALINK_OPEN) prompt_Printf(arg->prompt, " bandwidth %d, %llu bps (%llu bytes/sec)", dl->mp.bandwidth ? dl->mp.bandwidth : physical_GetSpeed(dl->physical), octets * 8, octets); prompt_Printf(arg->prompt, "\n"); } t = &arg->bundle->ncp.mp.link.stats.total; octets = MAX(t->in.OctetsPerSecond, t->out.OctetsPerSecond); secs = t->downtime ? 0 : throughput_uptime(t); if (secs > t->SamplePeriod) secs = t->SamplePeriod; if (secs) prompt_Printf(arg->prompt, "Currently averaging %llu bps (%llu bytes/sec)" " over the last %d secs\n", octets * 8, octets, secs); return 0; } static const char * optval(struct bundle *bundle, int opt) { return Enabled(bundle, opt) ? "enabled" : "disabled"; } int bundle_ShowStatus(struct cmdargs const *arg) { int remaining; prompt_Printf(arg->prompt, "Phase %s\n", bundle_PhaseName(arg->bundle)); prompt_Printf(arg->prompt, " Device: %s\n", arg->bundle->dev.Name); prompt_Printf(arg->prompt, " Interface: %s @ %lubps", arg->bundle->iface->name, arg->bundle->bandwidth); if (arg->bundle->upat) { int secs = bundle_Uptime(arg->bundle); prompt_Printf(arg->prompt, ", up time %d:%02d:%02d", secs / 3600, (secs / 60) % 60, secs % 60); } prompt_Printf(arg->prompt, "\n Queued: %lu of %u\n", (unsigned long)ncp_QueueLen(&arg->bundle->ncp), arg->bundle->cfg.ifqueue); prompt_Printf(arg->prompt, "\nDefaults:\n"); prompt_Printf(arg->prompt, " Label: %s\n", arg->bundle->cfg.label); prompt_Printf(arg->prompt, " Auth name: %s\n", arg->bundle->cfg.auth.name); prompt_Printf(arg->prompt, " Diagnostic socket: "); if (*server.cfg.sockname != '\0') { prompt_Printf(arg->prompt, "%s", server.cfg.sockname); if (server.cfg.mask != (mode_t)-1) prompt_Printf(arg->prompt, ", mask 0%03o", (int)server.cfg.mask); prompt_Printf(arg->prompt, "%s\n", server.fd == -1 ? " (not open)" : ""); } else if (server.cfg.port != 0) prompt_Printf(arg->prompt, "TCP port %d%s\n", server.cfg.port, server.fd == -1 ? " (not open)" : ""); else prompt_Printf(arg->prompt, "none\n"); prompt_Printf(arg->prompt, " Choked Timer: %us\n", arg->bundle->cfg.choked.timeout); #ifndef NORADIUS radius_Show(&arg->bundle->radius, arg->prompt); #endif prompt_Printf(arg->prompt, " Idle Timer: "); if (arg->bundle->cfg.idle.timeout) { prompt_Printf(arg->prompt, "%us", arg->bundle->cfg.idle.timeout); if (arg->bundle->cfg.idle.min_timeout) prompt_Printf(arg->prompt, ", min %us", arg->bundle->cfg.idle.min_timeout); remaining = bundle_RemainingIdleTime(arg->bundle); if (remaining != -1) prompt_Printf(arg->prompt, " (%ds remaining)", remaining); prompt_Printf(arg->prompt, "\n"); } else prompt_Printf(arg->prompt, "disabled\n"); prompt_Printf(arg->prompt, " Filter Decap: %-20.20s", optval(arg->bundle, OPT_FILTERDECAP)); prompt_Printf(arg->prompt, " ID check: %s\n", optval(arg->bundle, OPT_IDCHECK)); prompt_Printf(arg->prompt, " Iface-Alias: %-20.20s", optval(arg->bundle, OPT_IFACEALIAS)); #ifndef NOINET6 prompt_Printf(arg->prompt, " IPCP: %s\n", optval(arg->bundle, OPT_IPCP)); prompt_Printf(arg->prompt, " IPV6CP: %-20.20s", optval(arg->bundle, OPT_IPV6CP)); #endif prompt_Printf(arg->prompt, " Keep-Session: %s\n", optval(arg->bundle, OPT_KEEPSESSION)); prompt_Printf(arg->prompt, " Loopback: %-20.20s", optval(arg->bundle, OPT_LOOPBACK)); prompt_Printf(arg->prompt, " PasswdAuth: %s\n", optval(arg->bundle, OPT_PASSWDAUTH)); prompt_Printf(arg->prompt, " Proxy: %-20.20s", optval(arg->bundle, OPT_PROXY)); prompt_Printf(arg->prompt, " Proxyall: %s\n", optval(arg->bundle, OPT_PROXYALL)); prompt_Printf(arg->prompt, " Sticky Routes: %-20.20s", optval(arg->bundle, OPT_SROUTES)); prompt_Printf(arg->prompt, " TCPMSS Fixup: %s\n", optval(arg->bundle, OPT_TCPMSSFIXUP)); prompt_Printf(arg->prompt, " Throughput: %-20.20s", optval(arg->bundle, OPT_THROUGHPUT)); prompt_Printf(arg->prompt, " Utmp Logging: %s\n", optval(arg->bundle, OPT_UTMP)); prompt_Printf(arg->prompt, " NAS-IP-Address: %-20.20s", optval(arg->bundle, OPT_NAS_IP_ADDRESS)); prompt_Printf(arg->prompt, " NAS-Identifier: %s\n", optval(arg->bundle, OPT_NAS_IDENTIFIER)); return 0; } static void bundle_IdleTimeout(void *v) { struct bundle *bundle = (struct bundle *)v; log_Printf(LogPHASE, "Idle timer expired\n"); bundle_StopIdleTimer(bundle); bundle_Close(bundle, NULL, CLOSE_STAYDOWN); } /* * Start Idle timer. If timeout is reached, we call bundle_Close() to * close LCP and link. */ void bundle_StartIdleTimer(struct bundle *bundle, unsigned secs) { timer_Stop(&bundle->idle.timer); if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) != bundle->phys_type.open && bundle->cfg.idle.timeout) { time_t now = time(NULL); if (secs == 0) secs = bundle->cfg.idle.timeout; /* We want at least `secs' */ if (bundle->cfg.idle.min_timeout > secs && bundle->upat) { unsigned up = now - bundle->upat; if (bundle->cfg.idle.min_timeout > up && bundle->cfg.idle.min_timeout - up > (long long)secs) /* Only increase from the current `remaining' value */ secs = bundle->cfg.idle.min_timeout - up; } bundle->idle.timer.func = bundle_IdleTimeout; bundle->idle.timer.name = "idle"; bundle->idle.timer.load = secs * SECTICKS; bundle->idle.timer.arg = bundle; timer_Start(&bundle->idle.timer); bundle->idle.done = now + secs; } } void bundle_SetIdleTimer(struct bundle *bundle, unsigned timeout, unsigned min_timeout) { bundle->cfg.idle.timeout = timeout; bundle->cfg.idle.min_timeout = min_timeout; if (ncp_LayersOpen(&bundle->ncp)) bundle_StartIdleTimer(bundle, 0); } void bundle_StopIdleTimer(struct bundle *bundle) { timer_Stop(&bundle->idle.timer); bundle->idle.done = 0; } static int bundle_RemainingIdleTime(struct bundle *bundle) { if (bundle->idle.done) return bundle->idle.done - time(NULL); return -1; } #ifndef NORADIUS static void bundle_SessionTimeout(void *v) { struct bundle *bundle = (struct bundle *)v; log_Printf(LogPHASE, "Session-Timeout timer expired\n"); bundle_StopSessionTimer(bundle); bundle_Close(bundle, NULL, CLOSE_STAYDOWN); } void bundle_StartSessionTimer(struct bundle *bundle, unsigned secs) { timer_Stop(&bundle->session.timer); if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) != bundle->phys_type.open && bundle->radius.sessiontime) { time_t now = time(NULL); if (secs == 0) secs = bundle->radius.sessiontime; bundle->session.timer.func = bundle_SessionTimeout; bundle->session.timer.name = "session"; bundle->session.timer.load = secs * SECTICKS; bundle->session.timer.arg = bundle; timer_Start(&bundle->session.timer); bundle->session.done = now + secs; } } void bundle_StopSessionTimer(struct bundle *bundle) { timer_Stop(&bundle->session.timer); bundle->session.done = 0; } #endif int bundle_IsDead(struct bundle *bundle) { return !bundle->links || (bundle->phase == PHASE_DEAD && bundle->CleaningUp); } static struct datalink * bundle_DatalinkLinkout(struct bundle *bundle, struct datalink *dl) { struct datalink **dlp; for (dlp = &bundle->links; *dlp; dlp = &(*dlp)->next) if (*dlp == dl) { *dlp = dl->next; dl->next = NULL; bundle_LinksRemoved(bundle); return dl; } return NULL; } static void bundle_DatalinkLinkin(struct bundle *bundle, struct datalink *dl) { struct datalink **dlp = &bundle->links; while (*dlp) dlp = &(*dlp)->next; *dlp = dl; dl->next = NULL; bundle_LinkAdded(bundle, dl); mp_CheckAutoloadTimer(&bundle->ncp.mp); } void bundle_CleanDatalinks(struct bundle *bundle) { struct datalink **dlp = &bundle->links; int found = 0; while (*dlp) if ((*dlp)->state == DATALINK_CLOSED && (*dlp)->physical->type & (PHYS_DIRECT|PHYS_BACKGROUND|PHYS_FOREGROUND)) { *dlp = datalink_Destroy(*dlp); found++; } else dlp = &(*dlp)->next; if (found) bundle_LinksRemoved(bundle); } int bundle_DatalinkClone(struct bundle *bundle, struct datalink *dl, const char *name) { if (bundle2datalink(bundle, name)) { log_Printf(LogWARN, "Clone: %s: name already exists\n", name); return 0; } bundle_DatalinkLinkin(bundle, datalink_Clone(dl, name)); return 1; } void bundle_DatalinkRemove(struct bundle *bundle, struct datalink *dl) { dl = bundle_DatalinkLinkout(bundle, dl); if (dl) datalink_Destroy(dl); } void bundle_SetLabel(struct bundle *bundle, const char *label) { if (label) strncpy(bundle->cfg.label, label, sizeof bundle->cfg.label - 1); else *bundle->cfg.label = '\0'; } const char * bundle_GetLabel(struct bundle *bundle) { return *bundle->cfg.label ? bundle->cfg.label : NULL; } int -bundle_LinkSize() +bundle_LinkSize(void) { struct iovec iov[SCATTER_SEGMENTS]; int niov, expect, f; iov[0].iov_len = strlen(Version) + 1; iov[0].iov_base = NULL; niov = 1; if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) { log_Printf(LogERROR, "Cannot determine space required for link\n"); return 0; } for (f = expect = 0; f < niov; f++) expect += iov[f].iov_len; return expect; } void bundle_ReceiveDatalink(struct bundle *bundle, int s) { char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int) * SEND_MAXFD]; int niov, expect, f, *fd, nfd, onfd; ssize_t got; struct iovec iov[SCATTER_SEGMENTS]; struct cmsghdr *cmsg; struct msghdr msg; struct datalink *dl; pid_t pid; log_Printf(LogPHASE, "Receiving datalink\n"); /* * Create our scatter/gather array - passing NULL gets the space * allocation requirement rather than actually flattening the * structures. */ iov[0].iov_len = strlen(Version) + 1; iov[0].iov_base = NULL; niov = 1; if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) { log_Printf(LogERROR, "Cannot determine space required for link\n"); return; } /* Allocate the scatter/gather array for recvmsg() */ for (f = expect = 0; f < niov; f++) { if ((iov[f].iov_base = malloc(iov[f].iov_len)) == NULL) { log_Printf(LogERROR, "Cannot allocate space to receive link\n"); return; } if (f) expect += iov[f].iov_len; } /* Set up our message */ cmsg = (struct cmsghdr *)cmsgbuf; cmsg->cmsg_len = sizeof cmsgbuf; cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = 0; memset(&msg, '\0', sizeof msg); msg.msg_name = NULL; msg.msg_namelen = 0; msg.msg_iov = iov; msg.msg_iovlen = 1; /* Only send the version at the first pass */ msg.msg_control = cmsgbuf; msg.msg_controllen = sizeof cmsgbuf; log_Printf(LogDEBUG, "Expecting %u scatter/gather bytes\n", (unsigned)iov[0].iov_len); if ((got = recvmsg(s, &msg, MSG_WAITALL)) != (ssize_t)iov[0].iov_len) { if (got == -1) log_Printf(LogERROR, "Failed recvmsg: %s\n", strerror(errno)); else log_Printf(LogERROR, "Failed recvmsg: Got %zd, not %u\n", got, (unsigned)iov[0].iov_len); while (niov--) free(iov[niov].iov_base); return; } if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) { log_Printf(LogERROR, "Recvmsg: no descriptors received !\n"); while (niov--) free(iov[niov].iov_base); return; } fd = (int *)CMSG_DATA(cmsg); nfd = ((caddr_t)cmsg + cmsg->cmsg_len - (caddr_t)fd) / sizeof(int); if (nfd < 2) { log_Printf(LogERROR, "Recvmsg: %d descriptor%s received (too few) !\n", nfd, nfd == 1 ? "" : "s"); while (nfd--) close(fd[nfd]); while (niov--) free(iov[niov].iov_base); return; } /* * We've successfully received two or more open file descriptors * through our socket, plus a version string. Make sure it's the * correct version, and drop the connection if it's not. */ if (strncmp(Version, iov[0].iov_base, iov[0].iov_len)) { log_Printf(LogWARN, "Cannot receive datalink, incorrect version" " (\"%.*s\", not \"%s\")\n", (int)iov[0].iov_len, (char *)iov[0].iov_base, Version); while (nfd--) close(fd[nfd]); while (niov--) free(iov[niov].iov_base); return; } /* * Everything looks good. Send the other side our process id so that * they can transfer lock ownership, and wait for them to send the * actual link data. */ pid = getpid(); if ((got = write(fd[1], &pid, sizeof pid)) != sizeof pid) { if (got == -1) log_Printf(LogERROR, "Failed write: %s\n", strerror(errno)); else log_Printf(LogERROR, "Failed write: Got %zd, not %d\n", got, (int)(sizeof pid)); while (nfd--) close(fd[nfd]); while (niov--) free(iov[niov].iov_base); return; } if ((got = readv(fd[1], iov + 1, niov - 1)) != expect) { if (got == -1) log_Printf(LogERROR, "Failed write: %s\n", strerror(errno)); else log_Printf(LogERROR, "Failed write: Got %zd, not %d\n", got, expect); while (nfd--) close(fd[nfd]); while (niov--) free(iov[niov].iov_base); return; } close(fd[1]); onfd = nfd; /* We've got this many in our array */ nfd -= 2; /* Don't include p->fd and our reply descriptor */ niov = 1; /* Skip the version id */ dl = iov2datalink(bundle, iov, &niov, sizeof iov / sizeof *iov, fd[0], fd + 2, &nfd); if (dl) { if (nfd) { log_Printf(LogERROR, "bundle_ReceiveDatalink: Failed to handle %d " "auxiliary file descriptors (%d remain)\n", onfd, nfd); datalink_Destroy(dl); while (nfd--) close(fd[onfd--]); close(fd[0]); } else { bundle_DatalinkLinkin(bundle, dl); datalink_AuthOk(dl); bundle_CalculateBandwidth(dl->bundle); } } else { while (nfd--) close(fd[onfd--]); close(fd[0]); close(fd[1]); } free(iov[0].iov_base); } void bundle_SendDatalink(struct datalink *dl, int s, struct sockaddr_un *sun) { char cmsgbuf[CMSG_SPACE(sizeof(int) * SEND_MAXFD)]; const char *constlock; char *lock; struct cmsghdr *cmsg; struct msghdr msg; struct iovec iov[SCATTER_SEGMENTS]; int niov, f, expect, newsid, fd[SEND_MAXFD], nfd, reply[2]; ssize_t got; pid_t newpid; log_Printf(LogPHASE, "Transmitting datalink %s\n", dl->name); /* Record the base device name for a lock transfer later */ constlock = physical_LockedDevice(dl->physical); if (constlock) { lock = alloca(strlen(constlock) + 1); strcpy(lock, constlock); } else lock = NULL; bundle_LinkClosed(dl->bundle, dl); bundle_DatalinkLinkout(dl->bundle, dl); /* Build our scatter/gather array */ iov[0].iov_len = strlen(Version) + 1; iov[0].iov_base = strdup(Version); niov = 1; nfd = 0; fd[0] = datalink2iov(dl, iov, &niov, SCATTER_SEGMENTS, fd + 2, &nfd); if (fd[0] != -1 && socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, reply) != -1) { /* * fd[1] is used to get the peer process id back, then to confirm that * we've transferred any device locks to that process id. */ fd[1] = reply[1]; nfd += 2; /* Include fd[0] and fd[1] */ memset(&msg, '\0', sizeof msg); msg.msg_name = NULL; msg.msg_namelen = 0; /* * Only send the version to start... We used to send the whole lot, but * this caused problems with our RECVBUF size as a single link is about * 22k ! This way, we should bump into no limits. */ msg.msg_iovlen = 1; msg.msg_iov = iov; msg.msg_control = cmsgbuf; msg.msg_controllen = CMSG_SPACE(sizeof(int) * nfd); msg.msg_flags = 0; cmsg = (struct cmsghdr *)cmsgbuf; cmsg->cmsg_len = msg.msg_controllen; cmsg->cmsg_level = SOL_SOCKET; cmsg->cmsg_type = SCM_RIGHTS; for (f = 0; f < nfd; f++) *((int *)CMSG_DATA(cmsg) + f) = fd[f]; for (f = 1, expect = 0; f < niov; f++) expect += iov[f].iov_len; if (setsockopt(reply[0], SOL_SOCKET, SO_SNDBUF, &expect, sizeof(int)) == -1) log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect, strerror(errno)); if (setsockopt(reply[1], SOL_SOCKET, SO_RCVBUF, &expect, sizeof(int)) == -1) log_Printf(LogERROR, "setsockopt(SO_RCVBUF, %d): %s\n", expect, strerror(errno)); log_Printf(LogDEBUG, "Sending %d descriptor%s and %u bytes in scatter" "/gather array\n", nfd, nfd == 1 ? "" : "s", (unsigned)iov[0].iov_len); if ((got = sendmsg(s, &msg, 0)) == -1) log_Printf(LogERROR, "Failed sendmsg: %s: %s\n", sun->sun_path, strerror(errno)); else if (got != (ssize_t)iov[0].iov_len) log_Printf(LogERROR, "%s: Failed initial sendmsg: Only sent %zd of %u\n", sun->sun_path, got, (unsigned)iov[0].iov_len); else { /* We must get the ACK before closing the descriptor ! */ int res; if ((got = read(reply[0], &newpid, sizeof newpid)) == sizeof newpid) { log_Printf(LogDEBUG, "Received confirmation from pid %ld\n", (long)newpid); if (lock && (res = ID0uu_lock_txfr(lock, newpid)) != UU_LOCK_OK) log_Printf(LogERROR, "uu_lock_txfr: %s\n", uu_lockerr(res)); log_Printf(LogDEBUG, "Transmitting link (%d bytes)\n", expect); if ((got = writev(reply[0], iov + 1, niov - 1)) != expect) { if (got == -1) log_Printf(LogERROR, "%s: Failed writev: %s\n", sun->sun_path, strerror(errno)); else log_Printf(LogERROR, "%s: Failed writev: Wrote %zd of %d\n", sun->sun_path, got, expect); } } else if (got == -1) log_Printf(LogERROR, "%s: Failed socketpair read: %s\n", sun->sun_path, strerror(errno)); else log_Printf(LogERROR, "%s: Failed socketpair read: Got %zd of %d\n", sun->sun_path, got, (int)(sizeof newpid)); } close(reply[0]); close(reply[1]); newsid = Enabled(dl->bundle, OPT_KEEPSESSION) || tcgetpgrp(fd[0]) == getpgrp(); while (nfd) close(fd[--nfd]); if (newsid) bundle_setsid(dl->bundle, got != -1); } close(s); while (niov--) free(iov[niov].iov_base); } int bundle_RenameDatalink(struct bundle *bundle, struct datalink *ndl, const char *name) { struct datalink *dl; if (!strcasecmp(ndl->name, name)) return 1; for (dl = bundle->links; dl; dl = dl->next) if (!strcasecmp(dl->name, name)) return 0; datalink_Rename(ndl, name); return 1; } int bundle_SetMode(struct bundle *bundle, struct datalink *dl, int mode) { int omode; omode = dl->physical->type; if (omode == mode) return 1; if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO)) /* First auto link */ if (bundle->ncp.ipcp.peer_ip.s_addr == INADDR_ANY) { log_Printf(LogWARN, "You must `set ifaddr' or `open' before" " changing mode to %s\n", mode2Nam(mode)); return 0; } if (!datalink_SetMode(dl, mode)) return 0; if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO) && bundle->phase != PHASE_NETWORK) /* First auto link, we need an interface */ ipcp_InterfaceUp(&bundle->ncp.ipcp); /* Regenerate phys_type and adjust idle timer */ bundle_LinksRemoved(bundle); return 1; } void bundle_setsid(struct bundle *bundle, int holdsession) { /* * Lose the current session. This means getting rid of our pid * too so that the tty device will really go away, and any getty * etc will be allowed to restart. */ pid_t pid, orig; int fds[2]; char done; struct datalink *dl; if (!holdsession && bundle_IsDead(bundle)) { /* * No need to lose our session after all... we're going away anyway * * We should really stop the timer and pause if holdsession is set and * the bundle's dead, but that leaves other resources lying about :-( */ return; } orig = getpid(); if (pipe(fds) == -1) { log_Printf(LogERROR, "pipe: %s\n", strerror(errno)); return; } switch ((pid = fork())) { case -1: log_Printf(LogERROR, "fork: %s\n", strerror(errno)); close(fds[0]); close(fds[1]); return; case 0: close(fds[1]); read(fds[0], &done, 1); /* uu_locks are mine ! */ close(fds[0]); if (pipe(fds) == -1) { log_Printf(LogERROR, "pipe(2): %s\n", strerror(errno)); return; } switch ((pid = fork())) { case -1: log_Printf(LogERROR, "fork(2): %s\n", strerror(errno)); close(fds[0]); close(fds[1]); return; case 0: close(fds[1]); bundle_LockTun(bundle); /* update pid */ read(fds[0], &done, 1); /* uu_locks are mine ! */ close(fds[0]); setsid(); bundle_ChangedPID(bundle); log_Printf(LogDEBUG, "%ld -> %ld: %s session control\n", (long)orig, (long)getpid(), holdsession ? "Passed" : "Dropped"); timer_InitService(0); /* Start the Timer Service */ break; default: close(fds[0]); /* Give away all our physical locks (to the final process) */ for (dl = bundle->links; dl; dl = dl->next) if (dl->state != DATALINK_CLOSED) physical_ChangedPid(dl->physical, pid); write(fds[1], "!", 1); /* done */ close(fds[1]); _exit(0); break; } break; default: close(fds[0]); /* Give away all our physical locks (to the intermediate process) */ for (dl = bundle->links; dl; dl = dl->next) if (dl->state != DATALINK_CLOSED) physical_ChangedPid(dl->physical, pid); write(fds[1], "!", 1); /* done */ close(fds[1]); if (holdsession) { int fd, status; timer_TermService(); signal(SIGPIPE, SIG_DFL); signal(SIGALRM, SIG_DFL); signal(SIGHUP, SIG_DFL); signal(SIGTERM, SIG_DFL); signal(SIGINT, SIG_DFL); signal(SIGQUIT, SIG_DFL); for (fd = getdtablesize(); fd >= 0; fd--) close(fd); /* * Reap the intermediate process. As we're not exiting but the * intermediate is, we don't want it to become defunct. */ waitpid(pid, &status, 0); /* Tweak our process arguments.... */ SetTitle("session owner"); #ifndef NOSUID setuid(ID0realuid()); #endif /* * Hang around for a HUP. This should happen as soon as the * ppp that we passed our ctty descriptor to closes it. * NOTE: If this process dies, the passed descriptor becomes * invalid and will give a select() error by setting one * of the error fds, aborting the other ppp. We don't * want that to happen ! */ pause(); } _exit(0); break; } } unsigned bundle_HighestState(struct bundle *bundle) { struct datalink *dl; unsigned result = DATALINK_CLOSED; for (dl = bundle->links; dl; dl = dl->next) if (result < dl->state) result = dl->state; return result; } int bundle_Exception(struct bundle *bundle, int fd) { struct datalink *dl; for (dl = bundle->links; dl; dl = dl->next) if (dl->physical->fd == fd) { datalink_Down(dl, CLOSE_NORMAL); return 1; } return 0; } void bundle_AdjustFilters(struct bundle *bundle, struct ncpaddr *local, struct ncpaddr *remote) { filter_AdjustAddr(&bundle->filter.in, local, remote, NULL); filter_AdjustAddr(&bundle->filter.out, local, remote, NULL); filter_AdjustAddr(&bundle->filter.dial, local, remote, NULL); filter_AdjustAddr(&bundle->filter.alive, local, remote, NULL); } void bundle_AdjustDNS(struct bundle *bundle) { struct in_addr *dns = bundle->ncp.ipcp.ns.dns; filter_AdjustAddr(&bundle->filter.in, NULL, NULL, dns); filter_AdjustAddr(&bundle->filter.out, NULL, NULL, dns); filter_AdjustAddr(&bundle->filter.dial, NULL, NULL, dns); filter_AdjustAddr(&bundle->filter.alive, NULL, NULL, dns); } void bundle_CalculateBandwidth(struct bundle *bundle) { struct datalink *dl; int sp, overhead, maxoverhead; bundle->bandwidth = 0; bundle->iface->mtu = 0; maxoverhead = 0; for (dl = bundle->links; dl; dl = dl->next) { overhead = ccp_MTUOverhead(&dl->physical->link.ccp); if (maxoverhead < overhead) maxoverhead = overhead; if (dl->state == DATALINK_OPEN) { if ((sp = dl->mp.bandwidth) == 0 && (sp = physical_GetSpeed(dl->physical)) == 0) log_Printf(LogDEBUG, "%s: %s: Cannot determine bandwidth\n", dl->name, dl->physical->name.full); else bundle->bandwidth += sp; if (!bundle->ncp.mp.active) { bundle->iface->mtu = dl->physical->link.lcp.his_mru; break; } } } if (bundle->bandwidth == 0) bundle->bandwidth = 115200; /* Shrug */ if (bundle->ncp.mp.active) { bundle->iface->mtu = bundle->ncp.mp.peer_mrru; overhead = ccp_MTUOverhead(&bundle->ncp.mp.link.ccp); if (maxoverhead < overhead) maxoverhead = overhead; } else if (!bundle->iface->mtu) bundle->iface->mtu = DEF_MRU; #ifndef NORADIUS if (bundle->radius.valid && bundle->radius.mtu && bundle->radius.mtu < bundle->iface->mtu) { log_Printf(LogLCP, "Reducing MTU to radius value %lu\n", bundle->radius.mtu); bundle->iface->mtu = bundle->radius.mtu; } #endif if (maxoverhead) { log_Printf(LogLCP, "Reducing MTU from %lu to %lu (CCP requirement)\n", bundle->iface->mtu, bundle->iface->mtu - maxoverhead); bundle->iface->mtu -= maxoverhead; } tun_configure(bundle); route_UpdateMTU(bundle); } void bundle_AutoAdjust(struct bundle *bundle, int percent, int what) { struct datalink *dl, *choice, *otherlinkup; choice = otherlinkup = NULL; for (dl = bundle->links; dl; dl = dl->next) if (dl->physical->type == PHYS_AUTO) { if (dl->state == DATALINK_OPEN) { if (what == AUTO_DOWN) { if (choice) otherlinkup = choice; choice = dl; } } else if (dl->state == DATALINK_CLOSED) { if (what == AUTO_UP) { choice = dl; break; } } else { /* An auto link in an intermediate state - forget it for the moment */ choice = NULL; break; } } else if (dl->state == DATALINK_OPEN && what == AUTO_DOWN) otherlinkup = dl; if (choice) { if (what == AUTO_UP) { log_Printf(LogPHASE, "%d%% saturation -> Opening link ``%s''\n", percent, choice->name); datalink_Up(choice, 1, 1); mp_CheckAutoloadTimer(&bundle->ncp.mp); } else if (otherlinkup) { /* Only bring the second-last link down */ log_Printf(LogPHASE, "%d%% saturation -> Closing link ``%s''\n", percent, choice->name); datalink_Close(choice, CLOSE_STAYDOWN); mp_CheckAutoloadTimer(&bundle->ncp.mp); } } } int bundle_WantAutoloadTimer(struct bundle *bundle) { struct datalink *dl; int autolink, opened; if (bundle->phase == PHASE_NETWORK) { for (autolink = opened = 0, dl = bundle->links; dl; dl = dl->next) if (dl->physical->type == PHYS_AUTO) { if (++autolink == 2 || (autolink == 1 && opened)) /* Two auto links or one auto and one open in NETWORK phase */ return 1; } else if (dl->state == DATALINK_OPEN) { opened++; if (autolink) /* One auto and one open link in NETWORK phase */ return 1; } } return 0; } void bundle_ChangedPID(struct bundle *bundle) { #ifdef TUNSIFPID ioctl(bundle->dev.fd, TUNSIFPID, 0); #endif } int bundle_Uptime(struct bundle *bundle) { if (bundle->upat) return time(NULL) - bundle->upat; return 0; } diff --git a/usr.sbin/ppp/defs.c b/usr.sbin/ppp/defs.c index 7f89ef8b9f9e..627715360ee0 100644 --- a/usr.sbin/ppp/defs.c +++ b/usr.sbin/ppp/defs.c @@ -1,443 +1,443 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 1997 Brian Somers * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #include #include #include #include #include #include #include #include #include #include #include #if defined(__FreeBSD__) && !defined(NOKLDLOAD) #include #endif #include #ifndef __FreeBSD__ #include #endif #include #if defined(__FreeBSD__) && !defined(NOKLDLOAD) #include "id.h" #include "log.h" #endif #include "defs.h" #define issep(c) ((c) == '\t' || (c) == ' ') #ifdef __NetBSD__ void randinit() { srandom((time(NULL)^getpid())+random()); } #endif ssize_t fullread(int fd, void *v, size_t n) { size_t got, total; for (total = 0; total < n; total += got) switch ((got = read(fd, (char *)v + total, n - total))) { case 0: return total; case -1: if (errno == EINTR) got = 0; else return -1; } return total; } static struct { int mode; const char *name; } modes[] = { { PHYS_INTERACTIVE, "interactive" }, { PHYS_AUTO, "auto" }, { PHYS_DIRECT, "direct" }, { PHYS_DEDICATED, "dedicated" }, { PHYS_DDIAL, "ddial" }, { PHYS_BACKGROUND, "background" }, { PHYS_FOREGROUND, "foreground" }, { PHYS_ALL, "*" }, { 0, 0 } }; const char * mode2Nam(int mode) { int m; for (m = 0; modes[m].mode; m++) if (modes[m].mode == mode) return modes[m].name; return "unknown"; } int Nam2mode(const char *name) { int m, got, len; len = strlen(name); got = -1; for (m = 0; modes[m].mode; m++) if (!strncasecmp(name, modes[m].name, len)) { if (modes[m].name[len] == '\0') return modes[m].mode; if (got != -1) return 0; got = m; } return got == -1 ? 0 : modes[got].mode; } struct in_addr GetIpAddr(const char *cp) { struct in_addr ipaddr; if (!strcasecmp(cp, "default")) ipaddr.s_addr = INADDR_ANY; else if (inet_aton(cp, &ipaddr) == 0) { const char *ptr; /* Any illegal characters ? */ for (ptr = cp; *ptr != '\0'; ptr++) if (!isalnum(*ptr) && strchr("-.", *ptr) == NULL) break; if (*ptr == '\0') { struct hostent *hp; hp = gethostbyname(cp); if (hp && hp->h_addrtype == AF_INET) memcpy(&ipaddr, hp->h_addr, hp->h_length); else ipaddr.s_addr = INADDR_NONE; } else ipaddr.s_addr = INADDR_NONE; } return ipaddr; } static const struct speeds { unsigned nspeed; speed_t speed; } speeds[] = { #ifdef B50 { 50, B50, }, #endif #ifdef B75 { 75, B75, }, #endif #ifdef B110 { 110, B110, }, #endif #ifdef B134 { 134, B134, }, #endif #ifdef B150 { 150, B150, }, #endif #ifdef B200 { 200, B200, }, #endif #ifdef B300 { 300, B300, }, #endif #ifdef B600 { 600, B600, }, #endif #ifdef B1200 { 1200, B1200, }, #endif #ifdef B1800 { 1800, B1800, }, #endif #ifdef B2400 { 2400, B2400, }, #endif #ifdef B4800 { 4800, B4800, }, #endif #ifdef B9600 { 9600, B9600, }, #endif #ifdef B19200 { 19200, B19200, }, #endif #ifdef B38400 { 38400, B38400, }, #endif #ifndef _POSIX_SOURCE #ifdef B7200 { 7200, B7200, }, #endif #ifdef B14400 { 14400, B14400, }, #endif #ifdef B28800 { 28800, B28800, }, #endif #ifdef B57600 { 57600, B57600, }, #endif #ifdef B76800 { 76800, B76800, }, #endif #ifdef B115200 { 115200, B115200, }, #endif #ifdef B230400 { 230400, B230400, }, #endif #ifdef B460800 { 460800, B460800, }, #endif #ifdef B921600 { 921600, B921600, }, #endif #ifdef EXTA { 19200, EXTA, }, #endif #ifdef EXTB { 38400, EXTB, }, #endif #endif /* _POSIX_SOURCE */ { 0, 0 } }; unsigned SpeedToUnsigned(speed_t speed) { const struct speeds *sp; for (sp = speeds; sp->nspeed; sp++) { if (sp->speed == speed) { return sp->nspeed; } } return 0; } speed_t UnsignedToSpeed(unsigned nspeed) { const struct speeds *sp; for (sp = speeds; sp->nspeed; sp++) { if (sp->nspeed == nspeed) { return sp->speed; } } return B0; } char * findblank(char *p, int flags) { int instring; instring = 0; while (*p) { if (*p == '\\') { if (flags & PARSE_REDUCE) { memmove(p, p + 1, strlen(p)); if (!*p) break; } else p++; } else if (*p == '"') { memmove(p, p + 1, strlen(p)); instring = !instring; continue; } else if (!instring && (issep(*p) || (*p == '#' && !(flags & PARSE_NOHASH)))) return p; p++; } return instring ? NULL : p; } int MakeArgs(char *script, char **pvect, int maxargs, int flags) { int nargs; nargs = 0; while (*script) { script += strspn(script, " \t"); if (*script == '#' && !(flags & PARSE_NOHASH)) { *script = '\0'; break; } if (*script) { if (nargs >= maxargs - 1) break; *pvect++ = script; nargs++; script = findblank(script, flags); if (script == NULL) return -1; else if (!(flags & PARSE_NOHASH) && *script == '#') *script = '\0'; else if (*script) *script++ = '\0'; } } *pvect = NULL; return nargs; } const char * NumStr(long val, char *buf, size_t sz) { static char result[23]; /* handles 64 bit numbers */ if (buf == NULL || sz == 0) { buf = result; sz = sizeof result; } snprintf(buf, sz, "<%ld>", val); return buf; } const char * HexStr(long val, char *buf, size_t sz) { static char result[21]; /* handles 64 bit numbers */ if (buf == NULL || sz == 0) { buf = result; sz = sizeof result; } snprintf(buf, sz, "<0x%lx>", val); return buf; } const char * ex_desc(int ex) { static char num[12]; /* Used immediately if returned */ static const char * const desc[] = { "normal", "start", "sock", "modem", "dial", "dead", "done", "reboot", "errdead", "hangup", "term", "nodial", "nologin", "redial", "reconnect" }; if (ex >= 0 && ex < (int)(sizeof desc / sizeof *desc)) return desc[ex]; snprintf(num, sizeof num, "%d", ex); return num; } void SetTitle(const char *title) { if (title == NULL) setproctitle(NULL); else if (title[0] == '-' && title[1] != '\0') setproctitle("-%s", title + 1); else setproctitle("%s", title); } fd_set * -mkfdset() +mkfdset(void) { return (fd_set *)malloc(howmany(getdtablesize(), NFDBITS) * sizeof (fd_mask)); } void zerofdset(fd_set *s) { memset(s, '\0', howmany(getdtablesize(), NFDBITS) * sizeof (fd_mask)); } void Concatinate(char *buf, size_t sz, int argc, const char *const *argv) { int i, n; unsigned pos; *buf = '\0'; for (pos = i = 0; i < argc; i++) { n = snprintf(buf + pos, sz - pos, "%s%s", i ? " " : "", argv[i]); if (n < 0) { buf[pos] = '\0'; break; } if ((pos += n) >= sz) break; } } #if defined(__FreeBSD__) && !defined(NOKLDLOAD) int loadmodules(int how, const char *module, ...) { int loaded = 0; va_list ap; va_start(ap, module); while (module != NULL) { if (modfind(module) == -1) { if (ID0kldload(module) == -1) { if (how == LOAD_VERBOSLY) log_Printf(LogWARN, "%s: Cannot load module\n", module); } else loaded++; } module = va_arg(ap, const char *); } va_end(ap); return loaded; } #else int loadmodules(int how __unused, const char *module __unused, ...) { return 0; } #endif diff --git a/usr.sbin/ppp/id.c b/usr.sbin/ppp/id.c index 48ea7ce4a7f0..87e70d4eed4d 100644 --- a/usr.sbin/ppp/id.c +++ b/usr.sbin/ppp/id.c @@ -1,294 +1,294 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 1997 Brian Somers * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #include #include #include #include #include #ifndef NONETGRAPH #include #endif #include #include #include #include #include #if defined(__FreeBSD__) && !defined(NOKLDLOAD) #include #endif #include #ifdef __OpenBSD__ #include #else #include #endif #include #include "log.h" #include "main.h" #include "id.h" static int uid; static int euid; void -ID0init() +ID0init(void) { uid = getuid(); euid = geteuid(); } static void ID0setuser(void) { if (seteuid(uid) == -1) { log_Printf(LogERROR, "ID0setuser: Unable to seteuid!\n"); AbortProgram(EX_NOPERM); } } uid_t -ID0realuid() +ID0realuid(void) { return uid; } static void ID0set0(void) { if (seteuid(euid) == -1) { log_Printf(LogERROR, "ID0set0: Unable to seteuid!\n"); AbortProgram(EX_NOPERM); } } int ID0ioctl(int fd, unsigned long req, void *arg) { int ret; ID0set0(); ret = ioctl(fd, req, arg); log_Printf(LogID0, "%d = ioctl(%d, %lu, %p)\n", ret, fd, req, arg); ID0setuser(); return ret; } int ID0unlink(const char *name) { int ret; ID0set0(); ret = unlink(name); log_Printf(LogID0, "%d = unlink(\"%s\")\n", ret, name); ID0setuser(); return ret; } int ID0socket(int domain, int type, int protocol) { int ret; ID0set0(); ret = socket(domain, type, protocol); log_Printf(LogID0, "%d = socket(%d, %d, %d)\n", ret, domain, type, protocol); ID0setuser(); return ret; } FILE * ID0fopen(const char *path, const char *mode) { FILE *ret; ID0set0(); ret = fopen(path, mode); log_Printf(LogID0, "%p = fopen(\"%s\", \"%s\")\n", ret, path, mode); ID0setuser(); return ret; } int ID0open(const char *path, int flags, ...) { int ret; va_list ap; va_start(ap, flags); ID0set0(); ret = open(path, flags, va_arg(ap, int)); log_Printf(LogID0, "%d = open(\"%s\", %d)\n", ret, path, flags); ID0setuser(); va_end(ap); return ret; } int ID0write(int fd, const void *data, size_t len) { int ret; ID0set0(); ret = write(fd, data, len); log_Printf(LogID0, "%d = write(%d, data, %ld)\n", ret, fd, (long)len); ID0setuser(); return ret; } int ID0uu_lock(const char *basettyname) { int ret; ID0set0(); ret = uu_lock(basettyname); log_Printf(LogID0, "%d = uu_lock(\"%s\")\n", ret, basettyname); ID0setuser(); return ret; } int ID0uu_lock_txfr(const char *basettyname, pid_t newpid) { int ret; ID0set0(); ret = uu_lock_txfr(basettyname, newpid); log_Printf(LogID0, "%d = uu_lock_txfr(\"%s\", %ld)\n", ret, basettyname, (long)newpid); ID0setuser(); return ret; } int ID0uu_unlock(const char *basettyname) { int ret; ID0set0(); ret = uu_unlock(basettyname); log_Printf(LogID0, "%d = uu_unlock(\"%s\")\n", ret, basettyname); ID0setuser(); return ret; } void ID0login(const struct utmpx *ut) { ID0set0(); pututxline(ut); log_Printf(LogID0, "pututxline(\"%.*s\", \"%.*s\", \"%.*s\", \"%.*s\")\n", (int)sizeof ut->ut_id, ut->ut_id, (int)sizeof ut->ut_user, ut->ut_user, (int)sizeof ut->ut_line, ut->ut_line, (int)sizeof ut->ut_host, ut->ut_host); ID0setuser(); } void ID0logout(const struct utmpx *ut) { ID0set0(); pututxline(ut); log_Printf(LogID0, "pututxline(\"%.*s\")\n", (int)sizeof ut->ut_id, ut->ut_id); ID0setuser(); } int ID0bind_un(int s, const struct sockaddr_un *name) { int result; ID0set0(); result = bind(s, (const struct sockaddr *)name, sizeof *name); log_Printf(LogID0, "%d = bind(%d, \"%s\", %d)\n", result, s, name->sun_path, (int)sizeof(*name)); ID0setuser(); return result; } int ID0connect_un(int s, const struct sockaddr_un *name) { int result; ID0set0(); result = connect(s, (const struct sockaddr *)name, sizeof *name); log_Printf(LogID0, "%d = connect(%d, \"%s\", %d)\n", result, s, name->sun_path, (int)sizeof(*name)); ID0setuser(); return result; } int ID0kill(pid_t pid, int sig) { int result; ID0set0(); result = kill(pid, sig); log_Printf(LogID0, "%d = kill(%ld, %d)\n", result, (long)pid, sig); ID0setuser(); return result; } #if defined(__FreeBSD__) && !defined(NOKLDLOAD) int ID0kldload(const char *dev) { int result; ID0set0(); result = kldload(dev); log_Printf(LogID0, "%d = kldload(\"%s\")\n", result, dev); ID0setuser(); return result; } #endif #ifndef NONETGRAPH int ID0NgMkSockNode(const char *name, int *cs, int *ds) { int result; ID0set0(); result = NgMkSockNode(name, cs, ds); log_Printf(LogID0, "%d = NgMkSockNode(\"%s\", &cs, &ds)\n", result, name ? name : ""); ID0setuser(); return result; } #endif diff --git a/usr.sbin/ppp/log.c b/usr.sbin/ppp/log.c index 72f1ca9a9a91..ec689ae14ed7 100644 --- a/usr.sbin/ppp/log.c +++ b/usr.sbin/ppp/log.c @@ -1,534 +1,534 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 1997 Brian Somers * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #include #include #include #include #include #include #include #include "defs.h" #include "command.h" #include "mbuf.h" #include "log.h" #include "descriptor.h" #include "prompt.h" static const char *const LogNames[] = { "Async", "CBCP", "CCP", "Chat", "Command", "Connect", "Debug", "DNS", "Filter", /* Log discarded packets */ "HDLC", "ID0", "IPCP", "IPV6CP", "LCP", "LQM", "Phase", "Physical", "Radius", "Sync", "TCP/IP", "Timer", "Tun", "Warning", "Error", "Alert" }; #define MSK(n) (1<<((n)-1)) static u_long LogMask = MSK(LogPHASE); static u_long LogMaskLocal = MSK(LogERROR) | MSK(LogALERT) | MSK(LogWARN); static int LogTunno = -1; static const char *LogIfaceName; static struct prompt *promptlist; /* Where to log local stuff */ struct prompt *log_PromptContext; int log_PromptListChanged; struct prompt * -log_PromptList() +log_PromptList(void) { return promptlist; } void log_RegisterPrompt(struct prompt *prompt) { prompt->next = promptlist; promptlist = prompt; prompt->active = 1; log_DiscardAllLocal(&prompt->logmask); } void log_ActivatePrompt(struct prompt *prompt) { prompt->active = 1; LogMaskLocal |= prompt->logmask; } static void LogSetMaskLocal(void) { struct prompt *p; LogMaskLocal = MSK(LogERROR) | MSK(LogALERT) | MSK(LogWARN); for (p = promptlist; p; p = p->next) LogMaskLocal |= p->logmask; } void log_DeactivatePrompt(struct prompt *prompt) { if (prompt->active) { prompt->active = 0; LogSetMaskLocal(); } } void log_UnRegisterPrompt(struct prompt *prompt) { if (prompt) { struct prompt **p; for (p = &promptlist; *p; p = &(*p)->next) if (*p == prompt) { *p = prompt->next; prompt->next = NULL; break; } LogSetMaskLocal(); log_PromptListChanged++; } } void log_DestroyPrompts(struct server *s) { struct prompt *p, *pn, *pl; p = promptlist; pl = NULL; while (p) { pn = p->next; if (s && p->owner == s) { if (pl) pl->next = p->next; else promptlist = p->next; p->next = NULL; prompt_Destroy(p, 1); } else pl = p; p = pn; } } void -log_DisplayPrompts() +log_DisplayPrompts(void) { struct prompt *p; for (p = promptlist; p; p = p->next) prompt_Required(p); } void log_WritePrompts(struct datalink *dl, const char *fmt,...) { va_list ap; struct prompt *p; va_start(ap, fmt); for (p = promptlist; p; p = p->next) if (prompt_IsTermMode(p, dl)) prompt_vPrintf(p, fmt, ap); va_end(ap); } void log_SetTtyCommandMode(struct datalink *dl) { struct prompt *p; for (p = promptlist; p; p = p->next) if (prompt_IsTermMode(p, dl)) prompt_TtyCommandMode(p); } static int syslogLevel(int lev) { switch (lev) { case LogLOG: return LOG_INFO; case LogDEBUG: case LogTIMER: return LOG_DEBUG; case LogWARN: return LOG_WARNING; case LogERROR: return LOG_ERR; case LogALERT: return LOG_ALERT; } return lev >= LogMIN && lev <= LogMAX ? LOG_INFO : 0; } const char * log_Name(int id) { if (id == LogLOG) return "LOG"; return id < LogMIN || id > LogMAX ? "Unknown" : LogNames[id - 1]; } void log_Keep(int id) { if (id >= LogMIN && id <= LogMAXCONF) LogMask |= MSK(id); } void log_KeepLocal(int id, u_long *mask) { if (id >= LogMIN && id <= LogMAXCONF) { LogMaskLocal |= MSK(id); *mask |= MSK(id); } } void log_Discard(int id) { if (id >= LogMIN && id <= LogMAXCONF) LogMask &= ~MSK(id); } void log_DiscardLocal(int id, u_long *mask) { if (id >= LogMIN && id <= LogMAXCONF) { *mask &= ~MSK(id); LogSetMaskLocal(); } } void -log_DiscardAll() +log_DiscardAll(void) { LogMask = 0; } void log_DiscardAllLocal(u_long *mask) { *mask = MSK(LogERROR) | MSK(LogALERT) | MSK(LogWARN); LogSetMaskLocal(); } int log_IsKept(int id) { if (id == LogLOG) return LOG_KEPT_SYSLOG; if (id < LogMIN || id > LogMAX) return 0; if (id > LogMAXCONF) return LOG_KEPT_LOCAL | LOG_KEPT_SYSLOG; return ((LogMaskLocal & MSK(id)) ? LOG_KEPT_LOCAL : 0) | ((LogMask & MSK(id)) ? LOG_KEPT_SYSLOG : 0); } int log_IsKeptLocal(int id, u_long mask) { if (id < LogMIN || id > LogMAX) return 0; if (id > LogMAXCONF) return LOG_KEPT_LOCAL | LOG_KEPT_SYSLOG; return ((mask & MSK(id)) ? LOG_KEPT_LOCAL : 0) | ((LogMask & MSK(id)) ? LOG_KEPT_SYSLOG : 0); } void log_Open(const char *Name) { openlog(Name, LOG_PID, LOG_DAEMON); } void log_SetTun(int tunno, const char *ifaceName) { LogTunno = tunno; LogIfaceName = ifaceName; } void -log_Close() +log_Close(void) { closelog(); LogTunno = -1; LogIfaceName = NULL; } void log_Printf(int lev, const char *fmt,...) { va_list ap; struct prompt *prompt; if (log_IsKept(lev)) { char nfmt[200]; va_start(ap, fmt); if (promptlist && (log_IsKept(lev) & LOG_KEPT_LOCAL)) { if ((log_IsKept(LogTUN) & LOG_KEPT_LOCAL) && LogTunno != -1) { if (LogIfaceName) snprintf(nfmt, sizeof nfmt, "%s%d(%s): %s: %s", TUN_NAME, LogTunno, LogIfaceName, log_Name(lev), fmt); else snprintf(nfmt, sizeof nfmt, "%s%d: %s: %s", TUN_NAME, LogTunno, log_Name(lev), fmt); } else snprintf(nfmt, sizeof nfmt, "%s: %s", log_Name(lev), fmt); if (log_PromptContext && lev == LogWARN) /* Warnings just go to the current prompt */ prompt_vPrintf(log_PromptContext, nfmt, ap); else for (prompt = promptlist; prompt; prompt = prompt->next) if (lev > LogMAXCONF || (prompt->logmask & MSK(lev))) prompt_vPrintf(prompt, nfmt, ap); } va_end(ap); va_start(ap, fmt); if ((log_IsKept(lev) & LOG_KEPT_SYSLOG) && (lev != LogWARN || !log_PromptContext)) { if ((log_IsKept(LogTUN) & LOG_KEPT_SYSLOG) && LogTunno != -1) { if (LogIfaceName) snprintf(nfmt, sizeof nfmt, "%s%d(%s): %s: %s", TUN_NAME, LogTunno, LogIfaceName, log_Name(lev), fmt); else snprintf(nfmt, sizeof nfmt, "%s%d: %s: %s", TUN_NAME, LogTunno, log_Name(lev), fmt); } else snprintf(nfmt, sizeof nfmt, "%s: %s", log_Name(lev), fmt); vsyslog(syslogLevel(lev), nfmt, ap); } va_end(ap); } } void log_DumpBp(int lev, const char *hdr, const struct mbuf *bp) { if (log_IsKept(lev)) { char buf[68]; char *b, *c; const u_char *ptr; int f; if (hdr && *hdr) log_Printf(lev, "%s\n", hdr); b = buf; c = b + 50; do { f = bp->m_len; ptr = CONST_MBUF_CTOP(bp); while (f--) { sprintf(b, " %02x", (int) *ptr); *c++ = isprint(*ptr) ? *ptr : '.'; ptr++; b += 3; if (b == buf + 48) { memset(b, ' ', 2); *c = '\0'; log_Printf(lev, "%s\n", buf); b = buf; c = b + 50; } } } while ((bp = bp->m_next) != NULL); if (b > buf) { memset(b, ' ', 50 - (b - buf)); *c = '\0'; log_Printf(lev, "%s\n", buf); } } } void log_DumpBuff(int lev, const char *hdr, const u_char *ptr, int n) { if (log_IsKept(lev)) { char buf[68]; char *b, *c; if (hdr && *hdr) log_Printf(lev, "%s\n", hdr); while (n > 0) { b = buf; c = b + 50; for (b = buf; b != buf + 48 && n--; b += 3, ptr++) { sprintf(b, " %02x", (int) *ptr); *c++ = isprint(*ptr) ? *ptr : '.'; } memset(b, ' ', 50 - (b - buf)); *c = '\0'; log_Printf(lev, "%s\n", buf); } } } int log_ShowLevel(struct cmdargs const *arg) { int i; prompt_Printf(arg->prompt, "Log: "); for (i = LogMIN; i <= LogMAX; i++) if (log_IsKept(i) & LOG_KEPT_SYSLOG) prompt_Printf(arg->prompt, " %s", log_Name(i)); prompt_Printf(arg->prompt, "\nLocal:"); for (i = LogMIN; i <= LogMAX; i++) if (log_IsKeptLocal(i, arg->prompt->logmask) & LOG_KEPT_LOCAL) prompt_Printf(arg->prompt, " %s", log_Name(i)); prompt_Printf(arg->prompt, "\n"); return 0; } int log_SetLevel(struct cmdargs const *arg) { int i, res, argc, local; char const *const *argv, *argp; argc = arg->argc - arg->argn; argv = arg->argv + arg->argn; res = 0; if (argc == 0 || strcasecmp(argv[0], "local")) local = 0; else { if (arg->prompt == NULL) { log_Printf(LogWARN, "set log local: Only available on the" " command line\n"); return 1; } argc--; argv++; local = 1; } if (argc == 0 || (argv[0][0] != '+' && argv[0][0] != '-')) { if (local) log_DiscardAllLocal(&arg->prompt->logmask); else log_DiscardAll(); } while (argc--) { argp = **argv == '+' || **argv == '-' ? *argv + 1 : *argv; /* Special case 'all' */ if (strcasecmp(argp, "all") == 0) { if (**argv == '-') { if (local) for (i = LogMIN; i <= LogMAX; i++) log_DiscardLocal(i, &arg->prompt->logmask); else for (i = LogMIN; i <= LogMAX; i++) log_Discard(i); } else if (local) for (i = LogMIN; i <= LogMAX; i++) log_KeepLocal(i, &arg->prompt->logmask); else for (i = LogMIN; i <= LogMAX; i++) log_Keep(i); argv++; continue; } for (i = LogMIN; i <= LogMAX; i++) if (strcasecmp(argp, log_Name(i)) == 0) { if (**argv == '-') { if (local) log_DiscardLocal(i, &arg->prompt->logmask); else log_Discard(i); } else if (local) log_KeepLocal(i, &arg->prompt->logmask); else log_Keep(i); break; } if (i > LogMAX) { log_Printf(LogWARN, "%s: Invalid log value\n", argp); res = -1; } argv++; } return res; } int log_ShowWho(struct cmdargs const *arg) { struct prompt *p; for (p = promptlist; p; p = p->next) { prompt_Printf(arg->prompt, "%s (%s)", p->src.type, p->src.from); if (p == arg->prompt) prompt_Printf(arg->prompt, " *"); if (!p->active) prompt_Printf(arg->prompt, " ^Z"); prompt_Printf(arg->prompt, "\n"); } return 0; } diff --git a/usr.sbin/ppp/main.c b/usr.sbin/ppp/main.c index 3545d4753fcb..6bcb1e443a16 100644 --- a/usr.sbin/ppp/main.c +++ b/usr.sbin/ppp/main.c @@ -1,682 +1,682 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 1996 - 2001 Brian Somers * based on work by Toshiharu OHNO * Internet Initiative Japan, Inc (IIJ) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef NONAT #ifdef LOCALNAT #include "alias.h" #else #include #endif #endif #include "layer.h" #include "probe.h" #include "mbuf.h" #include "log.h" #include "defs.h" #include "id.h" #include "timer.h" #include "fsm.h" #include "lqr.h" #include "hdlc.h" #include "lcp.h" #include "ccp.h" #include "iplist.h" #include "throughput.h" #include "slcompress.h" #include "ncpaddr.h" #include "ipcp.h" #include "filter.h" #include "descriptor.h" #include "link.h" #include "mp.h" #ifndef NORADIUS #include "radius.h" #endif #include "ipv6cp.h" #include "ncp.h" #include "bundle.h" #include "auth.h" #include "systems.h" #include "sig.h" #include "main.h" #include "server.h" #include "prompt.h" #include "chat.h" #include "chap.h" #include "cbcp.h" #include "datalink.h" #include "iface.h" #ifndef O_NONBLOCK #ifdef O_NDELAY #define O_NONBLOCK O_NDELAY #endif #endif static void DoLoop(struct bundle *); static void TerminalStop(int); static struct bundle *SignalBundle; static struct prompt *SignalPrompt; struct libalias *la; void -Cleanup() +Cleanup(void) { SignalBundle->CleaningUp = 1; bundle_Close(SignalBundle, NULL, CLOSE_STAYDOWN); } void AbortProgram(int excode) { if (SignalBundle) server_Close(SignalBundle); log_Printf(LogPHASE, "PPP Terminated (%s).\n", ex_desc(excode)); if (SignalBundle) { bundle_Close(SignalBundle, NULL, CLOSE_STAYDOWN); bundle_Destroy(SignalBundle); } log_Close(); exit(excode); } static void CloseConnection(int signo) { /* NOTE, these are manual, we've done a setsid() */ sig_signal(SIGINT, SIG_IGN); log_Printf(LogPHASE, "Caught signal %d, abort connection(s)\n", signo); bundle_Down(SignalBundle, CLOSE_STAYDOWN); sig_signal(SIGINT, CloseConnection); } static void CloseSession(int signo) { log_Printf(LogPHASE, "Signal %d, terminate.\n", signo); Cleanup(); } static pid_t BGPid = 0; static void KillChild(int signo) { signal(signo, SIG_IGN); log_Printf(LogPHASE, "Parent: Signal %d\n", signo); kill(BGPid, SIGINT); } static void TerminalCont(int signo __unused) { signal(SIGCONT, SIG_DFL); prompt_Continue(SignalPrompt); } static void TerminalStop(int signo __unused) { prompt_Suspend(SignalPrompt); signal(SIGCONT, TerminalCont); raise(SIGSTOP); } static void BringDownServer(int signo __unused) { /* Drops all child prompts too ! */ if (server_Close(SignalBundle)) log_Printf(LogPHASE, "Closed server socket\n"); } static void RestartServer(int signo __unused) { /* Drops all child prompts and re-opens the socket */ server_Reopen(SignalBundle); } static void Usage(void) { fprintf(stderr, "usage: ppp [-auto | -foreground | -background | -direct |" " -dedicated | -ddial | -interactive]" #ifndef NONAT " [-nat]" #endif " [-quiet] [-unit N] [system ...]\n"); exit(EX_START); } struct switches { unsigned nat : 1; unsigned fg : 1; unsigned quiet : 1; int mode; int unit; }; static int ProcessArgs(int argc, char **argv, struct switches *sw) { int optc, newmode, arg; char *cp; optc = 0; memset(sw, '\0', sizeof *sw); sw->mode = PHYS_INTERACTIVE; sw->unit = -1; for (arg = 1; arg < argc && *argv[arg] == '-'; arg++, optc++) { cp = argv[arg] + 1; newmode = Nam2mode(cp); switch (newmode) { case PHYS_NONE: if (strcmp(cp, "nat") == 0) { #ifdef NONAT log_Printf(LogWARN, "%s ignored: NAT is compiled out\n", argv[arg]); #else sw->nat = 1; #endif optc--; /* this option isn't exclusive */ } else if (strcmp(cp, "alias") == 0) { #ifdef NONAT log_Printf(LogWARN, "%s ignored: NAT is compiled out\n", argv[arg]); fprintf(stderr, "%s ignored: NAT is compiled out\n", argv[arg]); #else log_Printf(LogWARN, "%s is deprecated\n", argv[arg]); fprintf(stderr, "%s is deprecated\n", argv[arg]); sw->nat = 1; #endif optc--; /* this option isn't exclusive */ } else if (strncmp(cp, "unit", 4) == 0) { optc--; /* this option isn't exclusive */ if (cp[4] == '\0') { optc--; /* nor is the argument */ if (++arg == argc) { fprintf(stderr, "-unit: Expected unit number\n"); Usage(); } else sw->unit = atoi(argv[arg]); } else sw->unit = atoi(cp + 4); } else if (strcmp(cp, "quiet") == 0) { sw->quiet = 1; optc--; /* this option isn't exclusive */ } else Usage(); break; case PHYS_ALL: Usage(); break; default: sw->mode = newmode; if (newmode == PHYS_FOREGROUND) sw->fg = 1; } } if (optc > 1) { fprintf(stderr, "You may specify only one mode.\n"); exit(EX_START); } if (sw->mode == PHYS_AUTO && arg == argc) { fprintf(stderr, "A system must be specified in auto mode.\n"); exit(EX_START); } return arg; /* Don't SetLabel yet ! */ } static void CheckLabel(const char *label, struct prompt *prompt, int mode) { const char *err; if ((err = system_IsValid(label, prompt, mode)) != NULL) { fprintf(stderr, "%s: %s\n", label, err); if (mode == PHYS_DIRECT) log_Printf(LogWARN, "Label %s rejected -direct connection: %s\n", label, err); log_Close(); exit(1); } } int main(int argc, char **argv) { char *name; const char *lastlabel; int arg, holdfd[3], label; unsigned f; struct bundle *bundle; struct prompt *prompt; struct switches sw; probe_Init(); /* * We open 3 descriptors to ensure that STDIN_FILENO, STDOUT_FILENO and * STDERR_FILENO are always open. These are closed before DoLoop(), * but *after* we've avoided the possibility of erroneously closing * an important descriptor with close(STD{IN,OUT,ERR}_FILENO). */ if ((holdfd[0] = open(_PATH_DEVNULL, O_RDWR)) == -1) { fprintf(stderr, "Cannot open %s !\n", _PATH_DEVNULL); return 2; } for (f = 1; f < sizeof holdfd / sizeof *holdfd; f++) holdfd[f] = dup(holdfd[0]); name = strrchr(argv[0], '/'); log_Open(name ? name + 1 : argv[0]); #ifndef NONAT la = LibAliasInit(NULL); #endif label = ProcessArgs(argc, argv, &sw); /* * A FreeBSD & OpenBSD hack to dodge a bug in the tty driver that drops * output occasionally.... I must find the real reason some time. To * display the dodgy behaviour, comment out this bit, make yourself a large * routing table and then run ppp in interactive mode. The `show route' * command will drop chunks of data !!! */ if (sw.mode == PHYS_INTERACTIVE) { close(STDIN_FILENO); if (open(_PATH_TTY, O_RDONLY) != STDIN_FILENO) { fprintf(stderr, "Cannot open %s for input !\n", _PATH_TTY); return 2; } } /* Allow output for the moment (except in direct mode) */ if (sw.mode == PHYS_DIRECT) prompt = NULL; else SignalPrompt = prompt = prompt_Create(NULL, NULL, PROMPT_STD); ID0init(); if (ID0realuid() != 0) { char conf[200], *ptr; snprintf(conf, sizeof conf, "%s/%s", PPP_CONFDIR, CONFFILE); do { struct stat sb; if (stat(conf, &sb) == 0 && sb.st_mode & S_IWOTH) { log_Printf(LogALERT, "ppp: Access violation: Please protect %s\n", conf); return -1; } ptr = conf + strlen(conf)-2; while (ptr > conf && *ptr != '/') *ptr-- = '\0'; } while (ptr >= conf); } if (label < argc) for (arg = label; arg < argc; arg++) CheckLabel(argv[arg], prompt, sw.mode); else CheckLabel("default", prompt, sw.mode); if (!sw.quiet) prompt_Printf(prompt, "Working in %s mode\n", mode2Nam(sw.mode)); if ((bundle = bundle_Create(TUN_PREFIX, sw.mode, sw.unit)) == NULL) return EX_START; /* NOTE: We may now have changed argv[1] via a ``set proctitle'' */ SignalBundle = bundle; bundle->NatEnabled = sw.nat; if (sw.nat) opt_enable(bundle, OPT_IFACEALIAS); if (system_Select(bundle, "default", CONFFILE, prompt, NULL) < 0) prompt_Printf(prompt, "Warning: No default entry found in config file.\n"); sig_signal(SIGHUP, CloseSession); sig_signal(SIGTERM, CloseSession); sig_signal(SIGINT, CloseConnection); sig_signal(SIGQUIT, CloseSession); sig_signal(SIGALRM, SIG_IGN); signal(SIGPIPE, SIG_IGN); if (sw.mode == PHYS_INTERACTIVE) sig_signal(SIGTSTP, TerminalStop); sig_signal(SIGUSR1, RestartServer); sig_signal(SIGUSR2, BringDownServer); lastlabel = argv[argc - 1]; for (arg = label; arg < argc; arg++) { /* In case we use LABEL or ``set enddisc label'' */ bundle_SetLabel(bundle, lastlabel); system_Select(bundle, argv[arg], CONFFILE, prompt, NULL); } if (label < argc) /* In case the last label did a ``load'' */ bundle_SetLabel(bundle, lastlabel); if (sw.mode == PHYS_AUTO && ncprange_family(&bundle->ncp.ipcp.cfg.peer_range) == AF_UNSPEC) { prompt_Printf(prompt, "You must ``set ifaddr'' with a peer address " "in auto mode.\n"); AbortProgram(EX_START); } if (prompt) { prompt->bundle = bundle; /* couldn't do it earlier */ if (!sw.quiet) prompt_Printf(prompt, "Using interface: %s\n", bundle->iface->name); } if (sw.mode != PHYS_INTERACTIVE) { if (sw.mode != PHYS_DIRECT) { if (!sw.fg) { int bgpipe[2]; pid_t bgpid; if (sw.mode == PHYS_BACKGROUND && pipe(bgpipe)) { log_Printf(LogERROR, "pipe: %s\n", strerror(errno)); AbortProgram(EX_SOCK); } bgpid = fork(); if (bgpid == -1) { log_Printf(LogERROR, "fork: %s\n", strerror(errno)); AbortProgram(EX_SOCK); } if (bgpid) { char c = EX_NORMAL; int ret; if (sw.mode == PHYS_BACKGROUND) { close(bgpipe[1]); BGPid = bgpid; /* If we get a signal, kill the child */ signal(SIGHUP, KillChild); signal(SIGTERM, KillChild); signal(SIGINT, KillChild); signal(SIGQUIT, KillChild); /* Wait for our child to close its pipe before we exit */ while ((ret = read(bgpipe[0], &c, 1)) == 1) { switch (c) { case EX_NORMAL: if (!sw.quiet) { prompt_Printf(prompt, "PPP enabled\n"); log_Printf(LogPHASE, "Parent: PPP enabled\n"); } break; case EX_REDIAL: if (!sw.quiet) prompt_Printf(prompt, "Attempting redial\n"); continue; case EX_RECONNECT: if (!sw.quiet) prompt_Printf(prompt, "Attempting reconnect\n"); continue; default: prompt_Printf(prompt, "Child failed (%s)\n", ex_desc((int)c)); log_Printf(LogPHASE, "Parent: Child failed (%s)\n", ex_desc((int) c)); } break; } if (ret != 1) { prompt_Printf(prompt, "Child exit, no status.\n"); log_Printf(LogPHASE, "Parent: Child exit, no status.\n"); } close(bgpipe[0]); } return c; } else if (sw.mode == PHYS_BACKGROUND) { close(bgpipe[0]); bundle->notify.fd = bgpipe[1]; } bundle_ChangedPID(bundle); bundle_LockTun(bundle); /* we have a new pid */ } /* -auto, -dedicated, -ddial, -foreground & -background */ prompt_Destroy(prompt, 0); close(STDOUT_FILENO); close(STDERR_FILENO); close(STDIN_FILENO); if (!sw.fg) setsid(); } else { /* * -direct - STDIN_FILENO gets used by physical_Open. STDOUT_FILENO * *may* get used in exec/pipe mode. */ prompt_TtyInit(NULL); close(STDERR_FILENO); } } else { /* -interactive */ close(STDERR_FILENO); prompt_TtyInit(prompt); prompt_TtyCommandMode(prompt); prompt_Required(prompt); } /* We can get rid of these now */ for (f = 0; f < sizeof holdfd / sizeof *holdfd; f++) close(holdfd[f]); log_Printf(LogPHASE, "PPP Started (%s mode).\n", mode2Nam(sw.mode)); DoLoop(bundle); AbortProgram(EX_NORMAL); return EX_NORMAL; } static void DoLoop(struct bundle *bundle) { fd_set *rfds, *wfds, *efds; int i, nfds, nothing_done; if ((rfds = mkfdset()) == NULL) { log_Printf(LogERROR, "DoLoop: Cannot create fd_set\n"); return; } if ((wfds = mkfdset()) == NULL) { log_Printf(LogERROR, "DoLoop: Cannot create fd_set\n"); free(rfds); return; } if ((efds = mkfdset()) == NULL) { log_Printf(LogERROR, "DoLoop: Cannot create fd_set\n"); free(rfds); free(wfds); return; } for (; !bundle_IsDead(bundle); bundle_CleanDatalinks(bundle)) { nfds = 0; zerofdset(rfds); zerofdset(wfds); zerofdset(efds); /* All our datalinks, the tun device and the MP socket */ descriptor_UpdateSet(&bundle->desc, rfds, wfds, efds, &nfds); /* All our prompts and the diagnostic socket */ descriptor_UpdateSet(&server.desc, rfds, NULL, NULL, &nfds); bundle_CleanDatalinks(bundle); if (bundle_IsDead(bundle)) /* Don't select - we'll be here forever */ break; /* * It's possible that we've had a signal since we last checked. If * we don't check again before calling select(), we may end up stuck * after having missed the event.... sig_Handle() tries to be as * quick as possible if nothing is likely to have happened. * This is only really likely if we block in open(... O_NONBLOCK) * which will happen with a misconfigured device. */ if (sig_Handle()) continue; i = select(nfds, rfds, wfds, efds, NULL); if (i < 0 && errno != EINTR) { log_Printf(LogERROR, "DoLoop: select(): %s\n", strerror(errno)); if (log_IsKept(LogTIMER)) { struct timeval t; for (i = 0; i <= nfds; i++) { if (FD_ISSET(i, rfds)) { log_Printf(LogTIMER, "Read set contains %d\n", i); FD_CLR(i, rfds); t.tv_sec = t.tv_usec = 0; if (select(nfds, rfds, wfds, efds, &t) != -1) { log_Printf(LogTIMER, "The culprit !\n"); break; } } if (FD_ISSET(i, wfds)) { log_Printf(LogTIMER, "Write set contains %d\n", i); FD_CLR(i, wfds); t.tv_sec = t.tv_usec = 0; if (select(nfds, rfds, wfds, efds, &t) != -1) { log_Printf(LogTIMER, "The culprit !\n"); break; } } if (FD_ISSET(i, efds)) { log_Printf(LogTIMER, "Error set contains %d\n", i); FD_CLR(i, efds); t.tv_sec = t.tv_usec = 0; if (select(nfds, rfds, wfds, efds, &t) != -1) { log_Printf(LogTIMER, "The culprit !\n"); break; } } } } break; } log_Printf(LogTIMER, "Select returns %d\n", i); sig_Handle(); if (i <= 0) continue; for (i = 0; i <= nfds; i++) if (FD_ISSET(i, efds)) { log_Printf(LogPHASE, "Exception detected on descriptor %d\n", i); /* We deal gracefully with link descriptor exceptions */ if (!bundle_Exception(bundle, i)) { log_Printf(LogERROR, "Exception cannot be handled !\n"); break; } } if (i <= nfds) break; nothing_done = 1; if (descriptor_IsSet(&server.desc, rfds)) { descriptor_Read(&server.desc, bundle, rfds); nothing_done = 0; } if (descriptor_IsSet(&bundle->desc, rfds)) { descriptor_Read(&bundle->desc, bundle, rfds); nothing_done = 0; } if (descriptor_IsSet(&bundle->desc, wfds)) if (descriptor_Write(&bundle->desc, bundle, wfds) <= 0 && nothing_done) { /* * This is disastrous. The OS has told us that something is * writable, and all our write()s have failed. Rather than * going back immediately to do our UpdateSet()s and select(), * we sleep for a bit to avoid gobbling up all cpu time. */ struct timeval t; t.tv_sec = 0; t.tv_usec = 100000; select(0, NULL, NULL, NULL, &t); } } log_Printf(LogDEBUG, "DoLoop done.\n"); } diff --git a/usr.sbin/ppp/physical.c b/usr.sbin/ppp/physical.c index 5612c1194e9d..3f7dbc4a7429 100644 --- a/usr.sbin/ppp/physical.c +++ b/usr.sbin/ppp/physical.c @@ -1,1126 +1,1126 @@ /* * Written by Eivind Eklund * for Yes Interactive * * Copyright (C) 1998, Yes Interactive. All rights reserved. * * Redistribution and use in any form is permitted. Redistribution in * source form should include the above copyright and this set of * conditions, because large sections american law seems to have been * created by a bunch of jerks on drugs that are now illegal, forcing * me to include this copyright-stuff instead of placing this in the * public domain. The name of of 'Yes Interactive' or 'Eivind Eklund' * may not be used to endorse or promote products derived from this * software without specific prior written permission. * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE. * * $FreeBSD$ * */ #include #include #include #include #include #include #include #include #include #include #ifdef NOSUID #include #endif #include #include #include #include #include #include #include #include #include #include #if defined(__OpenBSD__) || defined(__NetBSD__) #include #include #else #include #endif #include "layer.h" #ifndef NONAT #include "nat_cmd.h" #endif #include "proto.h" #include "acf.h" #include "vjcomp.h" #include "defs.h" #include "command.h" #include "mbuf.h" #include "log.h" #include "id.h" #include "timer.h" #include "fsm.h" #include "lqr.h" #include "hdlc.h" #include "lcp.h" #include "throughput.h" #include "sync.h" #include "async.h" #include "iplist.h" #include "slcompress.h" #include "ncpaddr.h" #include "ipcp.h" #include "filter.h" #include "descriptor.h" #include "ccp.h" #include "link.h" #include "physical.h" #include "mp.h" #ifndef NORADIUS #include "radius.h" #endif #include "ipv6cp.h" #include "ncp.h" #include "bundle.h" #include "prompt.h" #include "chat.h" #include "auth.h" #include "main.h" #include "chap.h" #include "cbcp.h" #include "datalink.h" #include "tcp.h" #include "udp.h" #include "exec.h" #include "tty.h" #ifndef NONETGRAPH #include "ether.h" #include "netgraph.h" #endif #include "tcpmss.h" static int physical_DescriptorWrite(struct fdescriptor *, struct bundle *, const fd_set *); static unsigned physical_DeviceSize(void) { return sizeof(struct device); } struct { struct device *(*create)(struct physical *); struct device *(*iov2device)(int, struct physical *, struct iovec *, int *, int, int *, int *); unsigned (*DeviceSize)(void); } devices[] = { { tty_Create, tty_iov2device, tty_DeviceSize }, #ifndef NONETGRAPH /* * This must come before ``udp'' so that the probe routine is * able to identify it as a more specific type of SOCK_DGRAM. */ { ether_Create, ether_iov2device, ether_DeviceSize }, #ifdef EXPERIMENTAL_NETGRAPH { ng_Create, ng_iov2device, ng_DeviceSize }, #endif #endif { tcp_Create, tcp_iov2device, tcp_DeviceSize }, { udp_Create, udp_iov2device, udp_DeviceSize }, { exec_Create, exec_iov2device, exec_DeviceSize } }; #define NDEVICES (sizeof devices / sizeof devices[0]) static int physical_UpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n) { return physical_doUpdateSet(d, r, w, e, n, 0); } void physical_SetDescriptor(struct physical *p) { p->desc.type = PHYSICAL_DESCRIPTOR; p->desc.UpdateSet = physical_UpdateSet; p->desc.IsSet = physical_IsSet; p->desc.Read = physical_DescriptorRead; p->desc.Write = physical_DescriptorWrite; } struct physical * physical_Create(struct datalink *dl, int type) { struct physical *p; p = (struct physical *)malloc(sizeof(struct physical)); if (!p) return NULL; p->link.type = PHYSICAL_LINK; p->link.name = dl->name; p->link.len = sizeof *p; /* The sample period is fixed - see physical2iov() & iov2physical() */ throughput_init(&p->link.stats.total, SAMPLE_PERIOD); p->link.stats.parent = dl->bundle->ncp.mp.active ? &dl->bundle->ncp.mp.link.stats.total : NULL; p->link.stats.gather = 1; memset(p->link.Queue, '\0', sizeof p->link.Queue); memset(p->link.proto_in, '\0', sizeof p->link.proto_in); memset(p->link.proto_out, '\0', sizeof p->link.proto_out); link_EmptyStack(&p->link); p->handler = NULL; physical_SetDescriptor(p); p->type = type; hdlc_Init(&p->hdlc, &p->link.lcp); async_Init(&p->async); p->fd = -1; p->out = NULL; p->connect_count = 0; p->dl = dl; p->input.sz = 0; *p->name.full = '\0'; p->name.base = p->name.full; p->Utmp = 0; p->session_owner = (pid_t)-1; p->cfg.rts_cts = MODEM_CTSRTS; p->cfg.speed = MODEM_SPEED; p->cfg.parity = CS8; memcpy(p->cfg.devlist, MODEM_LIST, sizeof MODEM_LIST); p->cfg.ndev = NMODEMS; p->cfg.cd.necessity = CD_DEFAULT; p->cfg.cd.delay = 0; /* reconfigured or device specific default */ lcp_Init(&p->link.lcp, dl->bundle, &p->link, &dl->fsmp); ccp_Init(&p->link.ccp, dl->bundle, &p->link, &dl->fsmp); return p; } static const struct parity { const char *name; const char *name1; int set; } validparity[] = { { "even", "P_EVEN", CS7 | PARENB }, { "odd", "P_ODD", CS7 | PARENB | PARODD }, { "none", "P_ZERO", CS8 }, { NULL, NULL, 0 }, }; static int GetParityValue(const char *str) { const struct parity *pp; for (pp = validparity; pp->name; pp++) { if (strcasecmp(pp->name, str) == 0 || strcasecmp(pp->name1, str) == 0) { return pp->set; } } return (-1); } int physical_SetParity(struct physical *p, const char *str) { struct termios rstio; int val; val = GetParityValue(str); if (val > 0) { p->cfg.parity = val; if (p->fd >= 0) { tcgetattr(p->fd, &rstio); rstio.c_cflag &= ~(CSIZE | PARODD | PARENB); rstio.c_cflag |= val; tcsetattr(p->fd, TCSADRAIN, &rstio); } return 0; } log_Printf(LogWARN, "%s: %s: Invalid parity\n", p->link.name, str); return -1; } unsigned physical_GetSpeed(struct physical *p) { if (p->handler && p->handler->speed) return (*p->handler->speed)(p); return 0; } int physical_SetSpeed(struct physical *p, unsigned speed) { if (UnsignedToSpeed(speed) != B0) { p->cfg.speed = speed; return 1; } return 0; } int physical_Raw(struct physical *p) { if (p->handler && p->handler->raw) return (*p->handler->raw)(p); return 1; } void physical_Offline(struct physical *p) { if (p->handler && p->handler->offline) (*p->handler->offline)(p); log_Printf(LogPHASE, "%s: Disconnected!\n", p->link.name); } static int physical_Lock(struct physical *p) { int res; if (*p->name.full == '/' && p->type != PHYS_DIRECT && (res = ID0uu_lock(p->name.base)) != UU_LOCK_OK) { if (res == UU_LOCK_INUSE) log_Printf(LogPHASE, "%s: %s is in use\n", p->link.name, p->name.full); else log_Printf(LogPHASE, "%s: %s is in use: uu_lock: %s\n", p->link.name, p->name.full, uu_lockerr(res)); return 0; } return 1; } static void physical_Unlock(struct physical *p) { if (*p->name.full == '/' && p->type != PHYS_DIRECT && ID0uu_unlock(p->name.base) == -1) log_Printf(LogALERT, "%s: Can't uu_unlock %s\n", p->link.name, p->name.base); } void physical_Close(struct physical *p) { int newsid; char fn[PATH_MAX]; struct utmpx ut; if (p->fd < 0) return; log_Printf(LogDEBUG, "%s: Close\n", p->link.name); if (p->handler && p->handler->cooked) (*p->handler->cooked)(p); physical_StopDeviceTimer(p); if (p->Utmp) { memset(&ut, 0, sizeof ut); ut.ut_type = DEAD_PROCESS; gettimeofday(&ut.ut_tv, NULL); snprintf(ut.ut_id, sizeof ut.ut_id, "%xppp", (int)getpid()); ID0logout(&ut); p->Utmp = 0; } newsid = tcgetpgrp(p->fd) == getpgrp(); close(p->fd); p->fd = -1; log_SetTtyCommandMode(p->dl); throughput_stop(&p->link.stats.total); throughput_log(&p->link.stats.total, LogPHASE, p->link.name); if (p->session_owner != (pid_t)-1) { log_Printf(LogPHASE, "%s: HUPing %ld\n", p->link.name, (long)p->session_owner); ID0kill(p->session_owner, SIGHUP); p->session_owner = (pid_t)-1; } if (newsid) bundle_setsid(p->dl->bundle, 0); if (*p->name.full == '/') { snprintf(fn, sizeof fn, "%s%s.if", _PATH_VARRUN, p->name.base); if (ID0unlink(fn) == -1) log_Printf(LogALERT, "%s: Can't remove %s: %s\n", p->link.name, fn, strerror(errno)); } physical_Unlock(p); if (p->handler && p->handler->destroy) (*p->handler->destroy)(p); p->handler = NULL; p->name.base = p->name.full; *p->name.full = '\0'; } void physical_Destroy(struct physical *p) { physical_Close(p); throughput_destroy(&p->link.stats.total); free(p); } static int physical_DescriptorWrite(struct fdescriptor *d, struct bundle *bundle __unused, const fd_set *fdset __unused) { struct physical *p = descriptor2physical(d); int nw, result = 0; if (p->out == NULL) p->out = link_Dequeue(&p->link); if (p->out) { nw = physical_Write(p, MBUF_CTOP(p->out), p->out->m_len); log_Printf(LogDEBUG, "%s: DescriptorWrite: wrote %d(%lu) to %d\n", p->link.name, nw, (unsigned long)p->out->m_len, p->fd); if (nw > 0) { p->out->m_len -= nw; p->out->m_offset += nw; if (p->out->m_len == 0) p->out = m_free(p->out); result = 1; } else if (nw < 0) { if (errno == EAGAIN) result = 1; else if (errno != ENOBUFS) { log_Printf(LogPHASE, "%s: write (fd %d, len %zd): %s\n", p->link.name, p->fd, p->out->m_len, strerror(errno)); datalink_Down(p->dl, CLOSE_NORMAL); } } /* else we shouldn't really have been called ! select() is broken ! */ } return result; } int physical_ShowStatus(struct cmdargs const *arg) { struct physical *p = arg->cx->physical; struct cd *cd; const char *dev; int n, slot; prompt_Printf(arg->prompt, "Name: %s\n", p->link.name); prompt_Printf(arg->prompt, " State: "); if (p->fd < 0) prompt_Printf(arg->prompt, "closed\n"); else { slot = physical_Slot(p); if (p->handler && p->handler->openinfo) { if (slot == -1) prompt_Printf(arg->prompt, "open (%s)\n", (*p->handler->openinfo)(p)); else prompt_Printf(arg->prompt, "open (%s, port %d)\n", (*p->handler->openinfo)(p), slot); } else if (slot == -1) prompt_Printf(arg->prompt, "open\n"); else prompt_Printf(arg->prompt, "open (port %d)\n", slot); } prompt_Printf(arg->prompt, " Device: %s", *p->name.full ? p->name.full : p->type == PHYS_DIRECT ? "unknown" : "N/A"); if (p->session_owner != (pid_t)-1) prompt_Printf(arg->prompt, " (session owner: %ld)", (long)p->session_owner); prompt_Printf(arg->prompt, "\n Link Type: %s\n", mode2Nam(p->type)); prompt_Printf(arg->prompt, " Connect Count: %d\n", p->connect_count); #ifdef TIOCOUTQ if (p->fd >= 0 && ioctl(p->fd, TIOCOUTQ, &n) >= 0) prompt_Printf(arg->prompt, " Physical outq: %d\n", n); #endif prompt_Printf(arg->prompt, " Queued Packets: %lu\n", (u_long)link_QueueLen(&p->link)); prompt_Printf(arg->prompt, " Phone Number: %s\n", arg->cx->phone.chosen); prompt_Printf(arg->prompt, "\nDefaults:\n"); prompt_Printf(arg->prompt, " Device List: "); dev = p->cfg.devlist; for (n = 0; n < p->cfg.ndev; n++) { if (n) prompt_Printf(arg->prompt, ", "); prompt_Printf(arg->prompt, "\"%s\"", dev); dev += strlen(dev) + 1; } prompt_Printf(arg->prompt, "\n Characteristics: "); if (physical_IsSync(arg->cx->physical)) prompt_Printf(arg->prompt, "sync"); else prompt_Printf(arg->prompt, "%dbps", p->cfg.speed); switch (p->cfg.parity & CSIZE) { case CS7: prompt_Printf(arg->prompt, ", cs7"); break; case CS8: prompt_Printf(arg->prompt, ", cs8"); break; } if (p->cfg.parity & PARENB) { if (p->cfg.parity & PARODD) prompt_Printf(arg->prompt, ", odd parity"); else prompt_Printf(arg->prompt, ", even parity"); } else prompt_Printf(arg->prompt, ", no parity"); prompt_Printf(arg->prompt, ", CTS/RTS %s\n", (p->cfg.rts_cts ? "on" : "off")); prompt_Printf(arg->prompt, " CD check delay: "); cd = p->handler ? &p->handler->cd : &p->cfg.cd; if (cd->necessity == CD_NOTREQUIRED) prompt_Printf(arg->prompt, "no cd"); else if (p->cfg.cd.necessity == CD_DEFAULT) { prompt_Printf(arg->prompt, "device specific"); } else { prompt_Printf(arg->prompt, "%d second%s", p->cfg.cd.delay, p->cfg.cd.delay == 1 ? "" : "s"); if (p->cfg.cd.necessity == CD_REQUIRED) prompt_Printf(arg->prompt, " (required!)"); } prompt_Printf(arg->prompt, "\n\n"); throughput_disp(&p->link.stats.total, arg->prompt); return 0; } void physical_DescriptorRead(struct fdescriptor *d, struct bundle *bundle, const fd_set *fdset __unused) { struct physical *p = descriptor2physical(d); u_char *rbuff; int n, found; rbuff = p->input.buf + p->input.sz; /* something to read */ n = physical_Read(p, rbuff, sizeof p->input.buf - p->input.sz); log_Printf(LogDEBUG, "%s: DescriptorRead: read %d/%d from %d\n", p->link.name, n, (int)(sizeof p->input.buf - p->input.sz), p->fd); if (n <= 0) { if (n < 0) log_Printf(LogPHASE, "%s: read (%d): %s\n", p->link.name, p->fd, strerror(errno)); else log_Printf(LogPHASE, "%s: read (%d): Got zero bytes\n", p->link.name, p->fd); datalink_Down(p->dl, CLOSE_NORMAL); return; } rbuff -= p->input.sz; n += p->input.sz; if (p->link.lcp.fsm.state <= ST_CLOSED) { if (p->type != PHYS_DEDICATED) { found = hdlc_Detect((u_char const **)&rbuff, n, physical_IsSync(p)); if (rbuff != p->input.buf) log_WritePrompts(p->dl, "%.*s", (int)(rbuff - p->input.buf), p->input.buf); p->input.sz = n - (rbuff - p->input.buf); if (found) { /* LCP packet is detected. Turn ourselves into packet mode */ log_Printf(LogPHASE, "%s: PPP packet detected, coming up\n", p->link.name); log_SetTtyCommandMode(p->dl); datalink_Up(p->dl, 0, 1); link_PullPacket(&p->link, rbuff, p->input.sz, bundle); p->input.sz = 0; } else bcopy(rbuff, p->input.buf, p->input.sz); } else /* In -dedicated mode, we just discard input until LCP is started */ p->input.sz = 0; } else if (n > 0) link_PullPacket(&p->link, rbuff, n, bundle); } struct physical * iov2physical(struct datalink *dl, struct iovec *iov, int *niov, int maxiov, int fd, int *auxfd, int *nauxfd) { struct physical *p; int type; unsigned h; p = (struct physical *)iov[(*niov)++].iov_base; p->link.name = dl->name; memset(p->link.Queue, '\0', sizeof p->link.Queue); p->desc.UpdateSet = physical_UpdateSet; p->desc.IsSet = physical_IsSet; p->desc.Read = physical_DescriptorRead; p->desc.Write = physical_DescriptorWrite; p->type = PHYS_DIRECT; p->dl = dl; p->out = NULL; p->connect_count = 1; physical_SetDevice(p, p->name.full); p->link.lcp.fsm.bundle = dl->bundle; p->link.lcp.fsm.link = &p->link; memset(&p->link.lcp.fsm.FsmTimer, '\0', sizeof p->link.lcp.fsm.FsmTimer); memset(&p->link.lcp.fsm.OpenTimer, '\0', sizeof p->link.lcp.fsm.OpenTimer); memset(&p->link.lcp.fsm.StoppedTimer, '\0', sizeof p->link.lcp.fsm.StoppedTimer); p->link.lcp.fsm.parent = &dl->fsmp; lcp_SetupCallbacks(&p->link.lcp); p->link.ccp.fsm.bundle = dl->bundle; p->link.ccp.fsm.link = &p->link; /* Our in.state & out.state are NULL (no link-level ccp yet) */ memset(&p->link.ccp.fsm.FsmTimer, '\0', sizeof p->link.ccp.fsm.FsmTimer); memset(&p->link.ccp.fsm.OpenTimer, '\0', sizeof p->link.ccp.fsm.OpenTimer); memset(&p->link.ccp.fsm.StoppedTimer, '\0', sizeof p->link.ccp.fsm.StoppedTimer); p->link.ccp.fsm.parent = &dl->fsmp; ccp_SetupCallbacks(&p->link.ccp); p->hdlc.lqm.owner = &p->link.lcp; p->hdlc.ReportTimer.state = TIMER_STOPPED; p->hdlc.lqm.timer.state = TIMER_STOPPED; p->fd = fd; p->link.stats.total.in.SampleOctets = (long long *)iov[(*niov)++].iov_base; p->link.stats.total.out.SampleOctets = (long long *)iov[(*niov)++].iov_base; p->link.stats.parent = dl->bundle->ncp.mp.active ? &dl->bundle->ncp.mp.link.stats.total : NULL; p->link.stats.gather = 1; type = (long)p->handler; p->handler = NULL; for (h = 0; h < NDEVICES && p->handler == NULL; h++) p->handler = (*devices[h].iov2device)(type, p, iov, niov, maxiov, auxfd, nauxfd); if (p->handler == NULL) { log_Printf(LogPHASE, "%s: Unknown link type\n", p->link.name); free(iov[(*niov)++].iov_base); physical_SetupStack(p, "unknown", PHYSICAL_NOFORCE); } else log_Printf(LogPHASE, "%s: Device %s, link type is %s\n", p->link.name, p->name.full, p->handler->name); if (p->hdlc.lqm.method && p->hdlc.lqm.timer.load) lqr_reStart(&p->link.lcp); hdlc_StartTimer(&p->hdlc); throughput_restart(&p->link.stats.total, "physical throughput", Enabled(dl->bundle, OPT_THROUGHPUT)); return p; } unsigned -physical_MaxDeviceSize() +physical_MaxDeviceSize(void) { unsigned biggest, sz, n; biggest = sizeof(struct device); for (n = 0; n < NDEVICES; n++) if (devices[n].DeviceSize) { sz = (*devices[n].DeviceSize)(); if (biggest < sz) biggest = sz; } return biggest; } int physical2iov(struct physical *p, struct iovec *iov, int *niov, int maxiov, int *auxfd, int *nauxfd) { struct device *h; int sz; h = NULL; if (p) { hdlc_StopTimer(&p->hdlc); lqr_StopTimer(p); timer_Stop(&p->link.lcp.fsm.FsmTimer); timer_Stop(&p->link.ccp.fsm.FsmTimer); timer_Stop(&p->link.lcp.fsm.OpenTimer); timer_Stop(&p->link.ccp.fsm.OpenTimer); timer_Stop(&p->link.lcp.fsm.StoppedTimer); timer_Stop(&p->link.ccp.fsm.StoppedTimer); if (p->handler) { h = p->handler; p->handler = (struct device *)(long)p->handler->type; } if (Enabled(p->dl->bundle, OPT_KEEPSESSION) || tcgetpgrp(p->fd) == getpgrp()) p->session_owner = getpid(); /* So I'll eventually get HUP'd */ else p->session_owner = (pid_t)-1; timer_Stop(&p->link.stats.total.Timer); } if (*niov + 2 >= maxiov) { log_Printf(LogERROR, "physical2iov: No room for physical + throughput" " + device !\n"); if (p) free(p); return -1; } iov[*niov].iov_base = (void *)p; iov[*niov].iov_len = sizeof *p; (*niov)++; iov[*niov].iov_base = p ? (void *)p->link.stats.total.in.SampleOctets : NULL; iov[*niov].iov_len = SAMPLE_PERIOD * sizeof(long long); (*niov)++; iov[*niov].iov_base = p ? (void *)p->link.stats.total.out.SampleOctets : NULL; iov[*niov].iov_len = SAMPLE_PERIOD * sizeof(long long); (*niov)++; sz = physical_MaxDeviceSize(); if (p) { if (h && h->device2iov) (*h->device2iov)(h, iov, niov, maxiov, auxfd, nauxfd); else { if ((iov[*niov].iov_base = malloc(sz)) == NULL) { log_Printf(LogALERT, "physical2iov: Out of memory (%d bytes)\n", sz); AbortProgram(EX_OSERR); } if (h) memcpy(iov[*niov].iov_base, h, sizeof *h); iov[*niov].iov_len = sz; (*niov)++; } } else { iov[*niov].iov_base = NULL; iov[*niov].iov_len = sz; (*niov)++; } return p ? p->fd : 0; } const char * physical_LockedDevice(struct physical *p) { if (p->fd >= 0 && *p->name.full == '/' && p->type != PHYS_DIRECT) return p->name.base; return NULL; } void physical_ChangedPid(struct physical *p, pid_t newpid) { if (physical_LockedDevice(p)) { int res; if ((res = ID0uu_lock_txfr(p->name.base, newpid)) != UU_LOCK_OK) log_Printf(LogPHASE, "uu_lock_txfr: %s\n", uu_lockerr(res)); } } int physical_IsSync(struct physical *p) { return p->cfg.speed == 0; } u_short physical_DeviceMTU(struct physical *p) { return p->handler ? p->handler->mtu : 0; } const char *physical_GetDevice(struct physical *p) { return p->name.full; } void physical_SetDeviceList(struct physical *p, int argc, const char *const *argv) { unsigned pos; int f; p->cfg.devlist[sizeof p->cfg.devlist - 1] = '\0'; for (f = 0, pos = 0; f < argc && pos < sizeof p->cfg.devlist - 1; f++) { if (pos) p->cfg.devlist[pos++] = '\0'; strncpy(p->cfg.devlist + pos, argv[f], sizeof p->cfg.devlist - pos - 1); pos += strlen(p->cfg.devlist + pos); } p->cfg.ndev = f; } void physical_SetSync(struct physical *p) { p->cfg.speed = 0; } int physical_SetRtsCts(struct physical *p, int enable) { p->cfg.rts_cts = enable ? 1 : 0; return 1; } ssize_t physical_Read(struct physical *p, void *buf, size_t nbytes) { ssize_t ret; if (p->handler && p->handler->read) ret = (*p->handler->read)(p, buf, nbytes); else ret = read(p->fd, buf, nbytes); log_DumpBuff(LogPHYSICAL, "read", buf, ret); return ret; } ssize_t physical_Write(struct physical *p, const void *buf, size_t nbytes) { log_DumpBuff(LogPHYSICAL, "write", buf, nbytes); if (p->handler && p->handler->write) return (*p->handler->write)(p, buf, nbytes); return write(p->fd, buf, nbytes); } int physical_doUpdateSet(struct fdescriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n, int force) { struct physical *p = descriptor2physical(d); int sets; sets = 0; if (p->fd >= 0) { if (r) { FD_SET(p->fd, r); log_Printf(LogTIMER, "%s: fdset(r) %d\n", p->link.name, p->fd); sets++; } if (e) { FD_SET(p->fd, e); log_Printf(LogTIMER, "%s: fdset(e) %d\n", p->link.name, p->fd); sets++; } if (w && (force || link_QueueLen(&p->link) || p->out)) { FD_SET(p->fd, w); log_Printf(LogTIMER, "%s: fdset(w) %d\n", p->link.name, p->fd); sets++; } if (sets && *n < p->fd + 1) *n = p->fd + 1; } return sets; } int physical_RemoveFromSet(struct physical *p, fd_set *r, fd_set *w, fd_set *e) { if (p->handler && p->handler->removefromset) return (*p->handler->removefromset)(p, r, w, e); else { int sets; sets = 0; if (p->fd >= 0) { if (r && FD_ISSET(p->fd, r)) { FD_CLR(p->fd, r); log_Printf(LogTIMER, "%s: fdunset(r) %d\n", p->link.name, p->fd); sets++; } if (e && FD_ISSET(p->fd, e)) { FD_CLR(p->fd, e); log_Printf(LogTIMER, "%s: fdunset(e) %d\n", p->link.name, p->fd); sets++; } if (w && FD_ISSET(p->fd, w)) { FD_CLR(p->fd, w); log_Printf(LogTIMER, "%s: fdunset(w) %d\n", p->link.name, p->fd); sets++; } } return sets; } } int physical_IsSet(struct fdescriptor *d, const fd_set *fdset) { struct physical *p = descriptor2physical(d); return p->fd >= 0 && FD_ISSET(p->fd, fdset); } void physical_Login(struct physical *p, const char *name) { if (p->type == PHYS_DIRECT && *p->name.base && !p->Utmp) { struct utmpx ut; const char *connstr; char *colon; memset(&ut, 0, sizeof ut); ut.ut_type = USER_PROCESS; gettimeofday(&ut.ut_tv, NULL); snprintf(ut.ut_id, sizeof ut.ut_id, "%xppp", (int)getpid()); strncpy(ut.ut_user, name, sizeof ut.ut_user); if (p->handler && (p->handler->type == TCP_DEVICE || p->handler->type == UDP_DEVICE)) { strncpy(ut.ut_host, p->name.base, sizeof ut.ut_host); colon = memchr(ut.ut_host, ':', sizeof ut.ut_host); if (colon) *colon = '\0'; } else strncpy(ut.ut_line, p->name.base, sizeof ut.ut_line); if ((connstr = getenv("CONNECT"))) /* mgetty sets this to the connection speed */ strncpy(ut.ut_host, connstr, sizeof ut.ut_host); ID0login(&ut); p->Utmp = 1; } } int physical_SetMode(struct physical *p, int mode) { if ((p->type & (PHYS_DIRECT|PHYS_DEDICATED) || mode & (PHYS_DIRECT|PHYS_DEDICATED)) && (!(p->type & PHYS_DIRECT) || !(mode & PHYS_BACKGROUND))) { /* Note: The -direct -> -background is for callback ! */ log_Printf(LogWARN, "%s: Cannot change mode %s to %s\n", p->link.name, mode2Nam(p->type), mode2Nam(mode)); return 0; } p->type = mode; return 1; } void physical_DeleteQueue(struct physical *p) { if (p->out) { m_freem(p->out); p->out = NULL; } link_DeleteQueue(&p->link); } void physical_SetDevice(struct physical *p, const char *name) { int len = strlen(_PATH_DEV); if (name != p->name.full) { strncpy(p->name.full, name, sizeof p->name.full - 1); p->name.full[sizeof p->name.full - 1] = '\0'; } p->name.base = *p->name.full == '!' ? p->name.full + 1 : strncmp(p->name.full, _PATH_DEV, len) ? p->name.full : p->name.full + len; } static void physical_Found(struct physical *p) { FILE *lockfile; char fn[PATH_MAX]; if (*p->name.full == '/') { snprintf(fn, sizeof fn, "%s%s.if", _PATH_VARRUN, p->name.base); lockfile = ID0fopen(fn, "w"); if (lockfile != NULL) { fprintf(lockfile, "%s%d\n", TUN_NAME, p->dl->bundle->unit); fclose(lockfile); } else log_Printf(LogALERT, "%s: Can't create %s: %s\n", p->link.name, fn, strerror(errno)); } throughput_start(&p->link.stats.total, "physical throughput", Enabled(p->dl->bundle, OPT_THROUGHPUT)); p->connect_count++; p->input.sz = 0; log_Printf(LogPHASE, "%s: Connected!\n", p->link.name); } int physical_Open(struct physical *p) { char *dev; int devno, wasfd, err; unsigned h; if (p->fd >= 0) log_Printf(LogDEBUG, "%s: Open: Modem is already open!\n", p->link.name); /* We're going back into "term" mode */ else if (p->type == PHYS_DIRECT) { physical_SetDevice(p, ""); p->fd = STDIN_FILENO; for (h = 0; h < NDEVICES && p->handler == NULL && p->fd >= 0; h++) p->handler = (*devices[h].create)(p); close(STDOUT_FILENO); if (p->fd >= 0) { if (p->handler == NULL) { physical_SetupStack(p, "unknown", PHYSICAL_NOFORCE); log_Printf(LogDEBUG, "%s: stdin is unidentified\n", p->link.name); } physical_Found(p); } } else { dev = p->cfg.devlist; devno = 0; while (devno < p->cfg.ndev && p->fd < 0) { physical_SetDevice(p, dev); if (physical_Lock(p)) { err = 0; if (*p->name.full == '/') { p->fd = ID0open(p->name.full, O_RDWR | O_NONBLOCK); if (p->fd < 0) err = errno; } wasfd = p->fd; for (h = 0; h < NDEVICES && p->handler == NULL; h++) if ((p->handler = (*devices[h].create)(p)) == NULL && wasfd != p->fd) break; if (p->fd < 0) { if (h == NDEVICES) { if (err) log_Printf(LogWARN, "%s: %s: %s\n", p->link.name, p->name.full, strerror(errno)); else log_Printf(LogWARN, "%s: Device (%s) must begin with a '/'," " a '!' or contain at least one ':'\n", p->link.name, p->name.full); } physical_Unlock(p); } else physical_Found(p); } dev += strlen(dev) + 1; devno++; } } return p->fd; } void physical_SetupStack(struct physical *p, const char *who, int how) { link_EmptyStack(&p->link); if (how == PHYSICAL_FORCE_SYNC || how == PHYSICAL_FORCE_SYNCNOACF || (how == PHYSICAL_NOFORCE && physical_IsSync(p))) link_Stack(&p->link, &synclayer); else { link_Stack(&p->link, &asynclayer); link_Stack(&p->link, &hdlclayer); } if (how != PHYSICAL_FORCE_SYNCNOACF) link_Stack(&p->link, &acflayer); link_Stack(&p->link, &protolayer); link_Stack(&p->link, &lqrlayer); link_Stack(&p->link, &ccplayer); link_Stack(&p->link, &vjlayer); link_Stack(&p->link, &tcpmsslayer); #ifndef NONAT link_Stack(&p->link, &natlayer); #endif if (how == PHYSICAL_FORCE_ASYNC && physical_IsSync(p)) { log_Printf(LogWARN, "Sync device setting ignored for ``%s'' device\n", who); p->cfg.speed = MODEM_SPEED; } else if (how == PHYSICAL_FORCE_SYNC && !physical_IsSync(p)) { log_Printf(LogWARN, "Async device setting ignored for ``%s'' device\n", who); physical_SetSync(p); } } void physical_StopDeviceTimer(struct physical *p) { if (p->handler && p->handler->stoptimer) (*p->handler->stoptimer)(p); } int physical_AwaitCarrier(struct physical *p) { if (p->handler && p->handler->awaitcarrier) return (*p->handler->awaitcarrier)(p); return CARRIER_OK; } void physical_SetAsyncParams(struct physical *p, u_int32_t mymap, u_int32_t hismap) { if (p->handler && p->handler->setasyncparams) return (*p->handler->setasyncparams)(p, mymap, hismap); async_SetLinkParams(&p->async, mymap, hismap); } int physical_Slot(struct physical *p) { if (p->handler && p->handler->slot) return (*p->handler->slot)(p); return -1; } int physical_SetPPPoEnonstandard(struct physical *p, int enable) { p->cfg.nonstandard_pppoe = enable ? 1 : 0; p->cfg.pppoe_configured = 1; return 1; } diff --git a/usr.sbin/ppp/probe.c b/usr.sbin/ppp/probe.c index 34e65d03b1ed..74bc4a1cefb2 100644 --- a/usr.sbin/ppp/probe.c +++ b/usr.sbin/ppp/probe.c @@ -1,80 +1,80 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 1998 Brian Somers * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #include #include #include #include #include "probe.h" #include "log.h" #include "id.h" struct probe probe; /* Does select() alter the passed time value ? */ static int select_changes_time(void) { struct timeval t; t.tv_sec = 0; t.tv_usec = 100000; select(0, NULL, NULL, NULL, &t); return t.tv_usec != 100000; } #ifndef NOINET6 static int ipv6_available(void) { int s; if ((s = ID0socket(PF_INET6, SOCK_DGRAM, 0)) == -1) return 0; close(s); return 1; } #endif void -probe_Init() +probe_Init(void) { probe.select_changes_time = select_changes_time() ? 1 : 0; log_Printf(LogDEBUG, "Select changes time: %s\n", probe.select_changes_time ? "yes" : "no"); #ifndef NOINET6 probe.ipv6_available = ipv6_available() ? 1 : 0; log_Printf(LogDEBUG, "IPv6 available: %s\n", probe.ipv6_available ? "yes" : "no"); #endif } diff --git a/usr.sbin/ppp/sig.c b/usr.sbin/ppp/sig.c index c7b2f469826c..c662d48892d7 100644 --- a/usr.sbin/ppp/sig.c +++ b/usr.sbin/ppp/sig.c @@ -1,121 +1,121 @@ /*- * SPDX-License-Identifier: BSD-2-Clause-FreeBSD * * Copyright (c) 1997 - 1999, 2001 Brian Somers * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #include #include #include "log.h" #include "sig.h" static int caused[NSIG]; /* An array of pending signals */ static int necessary; /* Anything set ? */ static sig_type handler[NSIG]; /* all start at SIG_DFL */ /* * Record a signal in the "caused" array * * This function is the only thing actually called in signal context. It * records that a signal has been caused and that sig_Handle() should be * called (in non-signal context) as soon as possible to process that * signal. */ static void signal_recorder(int sig) { caused[sig - 1]++; necessary = 1; } /* * Set up signal_recorder to handle the given sig and record ``fn'' as * the function to ultimately call in sig_Handle(). ``fn'' will not be * called in signal context (as sig_Handle() is not called in signal * context). */ sig_type sig_signal(int sig, sig_type fn) { sig_type Result; if (sig <= 0 || sig > NSIG) { /* Oops - we must be a bit out of date (too many sigs ?) */ log_Printf(LogALERT, "Eeek! %s:%d: I must be out of date!\n", __FILE__, __LINE__); return signal(sig, fn); } Result = handler[sig - 1]; if (fn == SIG_DFL || fn == SIG_IGN) { signal(sig, fn); handler[sig - 1] = (sig_type) 0; } else { handler[sig - 1] = fn; signal(sig, signal_recorder); } caused[sig - 1] = 0; return Result; } /* * Call the handlers for any pending signals * * This function is called from a non-signal context - in fact, it's * called every time select() in DoLoop() returns - just in case * select() returned due to a signal being recorded by signal_recorder(). */ int -sig_Handle() +sig_Handle(void) { int sig; int got; int result; result = 0; if (necessary) { /* We've *probably* got something in `caused' set */ necessary = 0; /* `necessary' might go back to 1 while we're in here.... */ do { got = 0; for (sig = 0; sig < NSIG; sig++) if (caused[sig]) { caused[sig]--; got++; result++; (*handler[sig])(sig + 1); } } while (got); } return result; }