Index: head/libexec/bootpd/rtmsg.c =================================================================== --- head/libexec/bootpd/rtmsg.c (revision 262135) +++ head/libexec/bootpd/rtmsg.c (revision 262136) @@ -1,243 +1,239 @@ /* * Copyright (c) 1984, 1993 * The Regents of the University of California. All rights reserved. * Copyright (c) 1994 * Geoffrey M. Rehmet, All rights reserved. * * This code is derived from software which forms part of the 4.4-Lite * Berkeley software distribution, which was in derived from software * contributed to Berkeley by Sun Microsystems, Inc. * * 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ /* * from arp.c 8.2 (Berkeley) 1/2/94 */ #include __FBSDID("$FreeBSD$"); #include /* * Verify that we are at least 4.4 BSD */ #if defined(BSD) #if BSD >= 199306 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "report.h" static int rtmsg(int); static int s = -1; /* routing socket */ /* * Open the routing socket */ static void getsocket () { if (s < 0) { s = socket(PF_ROUTE, SOCK_RAW, 0); if (s < 0) { report(LOG_ERR, "socket %s", strerror(errno)); exit(1); } } else { /* * Drain the socket of any unwanted routing messages. */ int n; char buf[512]; ioctl(s, FIONREAD, &n); while (n > 0) { read(s, buf, sizeof buf); ioctl(s, FIONREAD, &n); } } } static struct sockaddr_in so_mask = {8, 0, 0, { 0xffffffff}}; static struct sockaddr_in blank_sin = {sizeof(blank_sin), AF_INET }, sin_m; static struct sockaddr_dl blank_sdl = {sizeof(blank_sdl), AF_LINK }, sdl_m; static int expire_time, flags, doing_proxy; static struct { struct rt_msghdr m_rtm; char m_space[512]; } m_rtmsg; /* * Set an individual arp entry */ int bsd_arp_set(ia, eaddr, len) struct in_addr *ia; char *eaddr; int len; { register struct sockaddr_in *sin = &sin_m; register struct sockaddr_dl *sdl; register struct rt_msghdr *rtm = &(m_rtmsg.m_rtm); u_char *ea; struct timespec tp; int op = RTM_ADD; getsocket(); sdl_m = blank_sdl; sin_m = blank_sin; sin->sin_addr = *ia; ea = (u_char *)LLADDR(&sdl_m); bcopy(eaddr, ea, len); sdl_m.sdl_alen = len; doing_proxy = flags = expire_time = 0; /* make arp entry temporary */ clock_gettime(CLOCK_MONOTONIC, &tp); expire_time = tp.tv_sec + 20 * 60; tryagain: if (rtmsg(RTM_GET) < 0) { report(LOG_WARNING, "rtmget: %s", strerror(errno)); return (1); } sin = (struct sockaddr_in *)(rtm + 1); sdl = (struct sockaddr_dl *)(sin->sin_len + (char *)sin); if (sin->sin_addr.s_addr == sin_m.sin_addr.s_addr) { if (sdl->sdl_family == AF_LINK && !(rtm->rtm_flags & RTF_GATEWAY)) switch (sdl->sdl_type) { case IFT_ETHER: case IFT_FDDI: case IFT_ISO88023: case IFT_ISO88024: case IFT_ISO88025: op = RTM_CHANGE; goto overwrite; } if (doing_proxy == 0) { report(LOG_WARNING, "set: can only proxy for %s\n", inet_ntoa(sin->sin_addr)); return (1); } goto tryagain; } overwrite: if (sdl->sdl_family != AF_LINK) { report(LOG_WARNING, "cannot intuit interface index and type for %s\n", inet_ntoa(sin->sin_addr)); return (1); } sdl_m.sdl_type = sdl->sdl_type; sdl_m.sdl_index = sdl->sdl_index; return (rtmsg(op)); } static int rtmsg(cmd) int cmd; { static int seq; int rlen; register struct rt_msghdr *rtm = &m_rtmsg.m_rtm; register char *cp = m_rtmsg.m_space; register int l; errno = 0; bzero((char *)&m_rtmsg, sizeof(m_rtmsg)); rtm->rtm_flags = flags; rtm->rtm_version = RTM_VERSION; switch (cmd) { default: report(LOG_ERR, "set_arp: internal wrong cmd - exiting"); exit(1); case RTM_ADD: case RTM_CHANGE: rtm->rtm_addrs |= RTA_GATEWAY; rtm->rtm_rmx.rmx_expire = expire_time; rtm->rtm_inits = RTV_EXPIRE; rtm->rtm_flags |= (RTF_HOST | RTF_STATIC | RTF_LLDATA); if (doing_proxy) { rtm->rtm_addrs |= RTA_NETMASK; rtm->rtm_flags &= ~RTF_HOST; } /* FALLTHROUGH */ case RTM_GET: rtm->rtm_addrs |= RTA_DST; } #define NEXTADDR(w, s) \ if (rtm->rtm_addrs & (w)) { \ bcopy((char *)&s, cp, sizeof(s)); cp += sizeof(s);} NEXTADDR(RTA_DST, sin_m); NEXTADDR(RTA_GATEWAY, sdl_m); NEXTADDR(RTA_NETMASK, so_mask); rtm->rtm_msglen = cp - (char *)&m_rtmsg; l = rtm->rtm_msglen; rtm->rtm_seq = ++seq; rtm->rtm_type = cmd; if ((rlen = write(s, (char *)&m_rtmsg, l)) < 0) { if ((errno != ESRCH) && !(errno == EEXIST && cmd == RTM_ADD)){ report(LOG_WARNING, "writing to routing socket: %s", strerror(errno)); return (-1); } } do { l = read(s, (char *)&m_rtmsg, sizeof(m_rtmsg)); } while (l > 0 && (rtm->rtm_type != cmd || rtm->rtm_seq != seq || rtm->rtm_pid != getpid())); if (l < 0) report(LOG_WARNING, "arp: read from routing socket: %s\n", strerror(errno)); return (0); } #endif /* BSD */ #endif /* BSD >= 199306 */ Index: head/libexec/comsat/comsat.8 =================================================================== --- head/libexec/comsat/comsat.8 (revision 262135) +++ head/libexec/comsat/comsat.8 (revision 262136) @@ -1,115 +1,111 @@ .\" Copyright (c) 1983, 1991, 1993 .\" The Regents of the University of California. 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. -.\" 3. All advertising materials mentioning features or use of this software -.\" must display the following acknowledgement: -.\" This product includes software developed by the University of -.\" California, Berkeley and its contributors. -.\" 4. Neither the name of the University nor the names of its contributors +.\" 3. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. .\" .\" @(#)comsat.8 8.1 (Berkeley) 6/4/93 .\" $FreeBSD$ .\" .Dd January 21, 2010 .Dt COMSAT 8 .Os .Sh NAME .Nm comsat .Nd biff server .Sh SYNOPSIS .Nm .Sh DESCRIPTION The .Nm utility is the server process which receives reports of incoming mail and notifies users if they have requested this service. The .Nm utility receives messages on a datagram port associated with the .Dq biff service specification (see .Xr services 5 and .Xr inetd 8 ) . The one line messages are of the form: .Pp .D1 Ar user Ns @ Ns Ar mailbox Ns - Ns Ar offset Ns Op : Ns Ar mailbox-name .Pp If the .Ar user specified is logged in to the system and the associated terminal has the owner execute bit turned on (by a .Dq Nm biff Cm y ) , the .Ar offset is used as a seek offset into the appropriate mailbox file and the first 7 lines or 560 characters of the message are printed on the user's terminal. Lines which appear to be part of the message header other than the .Dq Li From , .Dq Li \&To , .Dq Li Date , or .Dq Li Subject lines are not included in the displayed message. .Pp If the .Ar user specified is logged in to the system and the associated terminal has the group execute bit turned on (by a .Dq Nm biff Cm b ) , two bell characters .Tn ( ASCII \\007) are printed on the user's terminal. .Pp If .Ar mailbox-name omitted, standard mailbox assumed. .Sh FILES .Bl -tag -width ".Pa /var/mail/user" -compact .It Pa /var/run/utx.active to find out who is logged on and on what terminals .It Pa /var/mail/user standard mailbox .El .Sh SEE ALSO .Xr biff 1 , .Xr inetd 8 .Sh HISTORY The .Nm utility appeared in .Bx 4.2 . .Sh BUGS The message header filtering is prone to error. The density of the information presented is near the theoretical minimum. .Pp Users should be notified of mail which arrives on other machines than the one to which they are currently logged in. .Pp The notification should appear in a separate window so it does not mess up the screen. Index: head/libexec/comsat/comsat.c =================================================================== --- head/libexec/comsat/comsat.c (revision 262135) +++ head/libexec/comsat/comsat.c (revision 262136) @@ -1,288 +1,284 @@ /* * Copyright (c) 1980, 1993 * The Regents of the University of California. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #ifndef lint static const char copyright[] = "@(#) Copyright (c) 1980, 1993\n\ The Regents of the University of California. All rights reserved.\n"; #endif /* not lint */ #ifndef lint #if 0 static char sccsid[] = "@(#)comsat.c 8.1 (Berkeley) 6/4/93"; #endif static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static int debug = 0; #define dsyslog if (debug) syslog #define MAXIDLE 120 static char hostname[MAXHOSTNAMELEN]; static void jkfprintf(FILE *, char[], char[], off_t); static void mailfor(char *); static void notify(struct utmpx *, char[], off_t, int); static void reapchildren(int); int main(int argc __unused, char *argv[] __unused) { struct sockaddr_in from; socklen_t fromlen; int cc; char msgbuf[256]; /* verify proper invocation */ fromlen = sizeof(from); if (getsockname(0, (struct sockaddr *)&from, &fromlen) < 0) err(1, "getsockname"); openlog("comsat", LOG_PID, LOG_DAEMON); if (chdir(_PATH_MAILDIR)) { syslog(LOG_ERR, "chdir: %s: %m", _PATH_MAILDIR); (void) recv(0, msgbuf, sizeof(msgbuf) - 1, 0); exit(1); } (void)gethostname(hostname, sizeof(hostname)); (void)signal(SIGTTOU, SIG_IGN); (void)signal(SIGCHLD, reapchildren); for (;;) { cc = recv(0, msgbuf, sizeof(msgbuf) - 1, 0); if (cc <= 0) { if (errno != EINTR) sleep(1); errno = 0; continue; } msgbuf[cc] = '\0'; mailfor(msgbuf); sigsetmask(0L); } } static void reapchildren(int signo __unused) { while (wait3(NULL, WNOHANG, NULL) > 0); } static void mailfor(char *name) { struct utmpx *utp; char *cp; char *file; off_t offset; int folder; char buf[sizeof(_PATH_MAILDIR) + sizeof(utp->ut_user) + 1]; char buf2[sizeof(_PATH_MAILDIR) + sizeof(utp->ut_user) + 1]; if (!(cp = strchr(name, '@'))) return; *cp = '\0'; offset = strtoll(cp + 1, NULL, 10); if (!(cp = strchr(cp + 1, ':'))) file = name; else file = cp + 1; sprintf(buf, "%s/%.*s", _PATH_MAILDIR, (int)sizeof(utp->ut_user), name); if (*file != '/') { sprintf(buf2, "%s/%.*s", _PATH_MAILDIR, (int)sizeof(utp->ut_user), file); file = buf2; } folder = strcmp(buf, file); setutxent(); while ((utp = getutxent()) != NULL) if (utp->ut_type == USER_PROCESS && !strcmp(utp->ut_user, name)) notify(utp, file, offset, folder); endutxent(); } static const char *cr; static void notify(struct utmpx *utp, char file[], off_t offset, int folder) { FILE *tp; struct stat stb; struct termios tio; char tty[20]; const char *s = utp->ut_line; if (strncmp(s, "pts/", 4) == 0) s += 4; if (strchr(s, '/')) { /* A slash is an attempt to break security... */ syslog(LOG_AUTH | LOG_NOTICE, "Unexpected `/' in `%s'", utp->ut_line); return; } (void)snprintf(tty, sizeof(tty), "%s%.*s", _PATH_DEV, (int)sizeof(utp->ut_line), utp->ut_line); if (stat(tty, &stb) == -1 || !(stb.st_mode & (S_IXUSR | S_IXGRP))) { dsyslog(LOG_DEBUG, "%s: wrong mode on %s", utp->ut_user, tty); return; } dsyslog(LOG_DEBUG, "notify %s on %s", utp->ut_user, tty); switch (fork()) { case -1: syslog(LOG_NOTICE, "fork failed (%m)"); return; case 0: break; default: return; } if ((tp = fopen(tty, "w")) == NULL) { dsyslog(LOG_ERR, "%s: %s", tty, strerror(errno)); _exit(1); } (void)tcgetattr(fileno(tp), &tio); cr = ((tio.c_oflag & (OPOST|ONLCR)) == (OPOST|ONLCR)) ? "\n" : "\n\r"; switch (stb.st_mode & (S_IXUSR | S_IXGRP)) { case S_IXUSR: case (S_IXUSR | S_IXGRP): (void)fprintf(tp, "%s\007New mail for %s@%.*s\007 has arrived%s%s%s:%s----%s", cr, utp->ut_user, (int)sizeof(hostname), hostname, folder ? cr : "", folder ? "to " : "", folder ? file : "", cr, cr); jkfprintf(tp, utp->ut_user, file, offset); break; case S_IXGRP: (void)fprintf(tp, "\007"); (void)fflush(tp); (void)sleep(1); (void)fprintf(tp, "\007"); break; default: break; } (void)fclose(tp); _exit(0); } static void jkfprintf(FILE *tp, char user[], char file[], off_t offset) { unsigned char *cp, ch; FILE *fi; int linecnt, charcnt, inheader; struct passwd *p; unsigned char line[BUFSIZ]; /* Set effective uid to user in case mail drop is on nfs */ if ((p = getpwnam(user)) != NULL) (void) setuid(p->pw_uid); if ((fi = fopen(file, "r")) == NULL) return; (void)fseeko(fi, offset, SEEK_CUR); /* * Print the first 7 lines or 560 characters of the new mail * (whichever comes first). Skip header crap other than * From, Subject, To, and Date. */ linecnt = 7; charcnt = 560; inheader = 1; while (fgets(line, sizeof(line), fi) != NULL) { if (inheader) { if (line[0] == '\n') { inheader = 0; continue; } if (line[0] == ' ' || line[0] == '\t' || (strncmp(line, "From:", 5) && strncmp(line, "Subject:", 8))) continue; } if (linecnt <= 0 || charcnt <= 0) { (void)fprintf(tp, "...more...%s", cr); (void)fclose(fi); return; } /* strip weird stuff so can't trojan horse stupid terminals */ for (cp = line; (ch = *cp) && ch != '\n'; ++cp, --charcnt) { /* disable upper controls and enable all other 8bit codes due to lack of locale knowledge */ if (((ch & 0x80) && ch < 0xA0) || (!(ch & 0x80) && !isprint(ch) && !isspace(ch) && ch != '\a' && ch != '\b') ) { if (ch & 0x80) { ch &= ~0x80; (void)fputs("M-", tp); } if (iscntrl(ch)) { ch ^= 0x40; (void)fputc('^', tp); } } (void)fputc(ch, tp); } (void)fputs(cr, tp); --linecnt; } (void)fprintf(tp, "----%s\n", cr); (void)fclose(fi); } Index: head/libexec/fingerd/fingerd.8 =================================================================== --- head/libexec/fingerd/fingerd.8 (revision 262135) +++ head/libexec/fingerd/fingerd.8 (revision 262136) @@ -1,181 +1,177 @@ .\" Copyright (c) 1980, 1991, 1993 .\" The Regents of the University of California. 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. -.\" 3. All advertising materials mentioning features or use of this software -.\" must display the following acknowledgement: -.\" This product includes software developed by the University of -.\" California, Berkeley and its contributors. -.\" 4. Neither the name of the University nor the names of its contributors +.\" 3. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. .\" .\" @(#)fingerd.8 8.1 (Berkeley) 6/4/93 .\" $FreeBSD$ .\" .Dd April 1, 2010 .Dt FINGERD 8 .Os .Sh NAME .Nm fingerd .Nd remote user information server .Sh SYNOPSIS .Nm .Op Fl d .Op Fl k .Op Fl s .Op Fl l .Op Fl p Ar filename .Sh DESCRIPTION The .Nm utility uses a simple protocol based on .%T RFC1196 that provides an interface to .Xr finger 1 at several network sites. It is supposed to return a friendly, human-oriented status report on either the system at the moment or a particular person in depth. There is no required format and the protocol consists mostly of specifying a single .Dq "command line" , thus, .Nm can also be used to implement other protocols in conjunction with the .Fl p flag. .Pp The .Nm utility is started by .Xr inetd 8 , which listens for .Tn TCP requests at port 79. Once connected it reads a single command line terminated by a .Aq Tn CRLF which is passed to .Xr finger 1 . The .Nm utility closes its connections as soon as the output is finished. .Pp If the line is null (i.e., just a .Aq Tn CRLF is sent) then .Xr finger 1 returns a .Dq default report that lists all people logged into the system at that moment. .Pp If a user name is specified (e.g.\& .Pf eric Aq Tn CRLF ) then the response lists more extended information for only that particular user, whether logged in or not. Allowable .Dq names in the command line include both .Dq login names and .Dq user names . If a name is ambiguous, all possible derivations are returned. .Pp The following options may be passed to .Nm as server program arguments in .Pa /etc/inetd.conf : .Bl -tag -width indent .It Fl d Enable debugging mode. In debugging mode, .Nm will not attempt any network-related operations on .Va stdin , and it will print the full .Nm finger command line to .Va stderr before executing it. .It Fl k Suppress login information. See the description of the .Fl k option in .Xr finger 1 for details. .It Fl s Enable secure mode. Queries without a user name are rejected and forwarding of queries to other remote hosts is denied. .It Fl l Enable logging. The name of the host originating the query is reported via .Xr syslog 3 at LOG_NOTICE priority. .It Fl p Use an alternate program as the local information provider. The default local program executed by .Nm is .Xr finger 1 . By specifying a customized local server, this option allows a system manager to have more control over what information is provided to remote sites. If .Fl p is specified, .Nm will also set the environment variable .Ev FINGERD_REMOTE_HOST to the name of the host making the request. .El .Sh SEE ALSO .Xr finger 1 , .Xr inetd 8 .Sh HISTORY The .Nm utility appeared in .Bx 4.3 . .Sh BUGS Connecting directly to the server from a .Tn TIP or an equally narrow-minded .Tn TELNET Ns \-protocol user program can result in meaningless attempts at option negotiation being sent to the server, which will foul up the command line interpretation. The .Nm utility should be taught to filter out .Tn IAC Ns \'s and perhaps even respond negatively .Pq Tn IAC WON'T to all option commands received. Index: head/libexec/fingerd/fingerd.c =================================================================== --- head/libexec/fingerd/fingerd.c (revision 262135) +++ head/libexec/fingerd/fingerd.c (revision 262136) @@ -1,235 +1,231 @@ /* * Copyright (c) 1983, 1993 * The Regents of the University of California. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #ifndef lint static const char copyright[] = "@(#) Copyright (c) 1983, 1993\n\ The Regents of the University of California. All rights reserved.\n"; #endif /* not lint */ #ifndef lint #if 0 static char sccsid[] = "@(#)fingerd.c 8.1 (Berkeley) 6/4/93"; #endif static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "pathnames.h" void logerr(const char *, ...) __printflike(1, 2) __dead2; int main(int argc, char *argv[]) { FILE *fp; int ch; char *lp; struct sockaddr_storage ss; socklen_t sval; int p[2], debug, kflag, logging, pflag, secure; #define ENTRIES 50 char **ap, *av[ENTRIES + 1], **comp, line[1024], *prog; char rhost[MAXHOSTNAMELEN]; prog = _PATH_FINGER; debug = logging = kflag = pflag = secure = 0; openlog("fingerd", LOG_PID | LOG_CONS, LOG_DAEMON); opterr = 0; while ((ch = getopt(argc, argv, "dklp:s")) != -1) switch (ch) { case 'd': debug = 1; break; case 'k': kflag = 1; break; case 'l': logging = 1; break; case 'p': prog = optarg; pflag = 1; break; case 's': secure = 1; break; case '?': default: logerr("illegal option -- %c", optopt); } /* * Enable server-side Transaction TCP. */ if (!debug) { int one = 1; if (setsockopt(STDOUT_FILENO, IPPROTO_TCP, TCP_NOPUSH, &one, sizeof one) < 0) { logerr("setsockopt(TCP_NOPUSH) failed: %m"); } } if (!fgets(line, sizeof(line), stdin)) exit(1); if (!debug && (logging || pflag)) { sval = sizeof(ss); if (getpeername(0, (struct sockaddr *)&ss, &sval) < 0) logerr("getpeername: %s", strerror(errno)); realhostname_sa(rhost, sizeof rhost - 1, (struct sockaddr *)&ss, sval); rhost[sizeof(rhost) - 1] = '\0'; if (pflag) setenv("FINGERD_REMOTE_HOST", rhost, 1); } if (logging) { char *t; char *end; end = memchr(line, 0, sizeof(line)); if (end == NULL) { if ((t = malloc(sizeof(line) + 1)) == NULL) logerr("malloc: %s", strerror(errno)); memcpy(t, line, sizeof(line)); t[sizeof(line)] = 0; } else { if ((t = strdup(line)) == NULL) logerr("strdup: %s", strerror(errno)); } for (end = t; *end; end++) if (*end == '\n' || *end == '\r') *end = ' '; syslog(LOG_NOTICE, "query from %s: `%s'", rhost, t); } comp = &av[2]; av[3] = "--"; if (kflag) *comp-- = "-k"; for (lp = line, ap = &av[4];;) { *ap = strtok(lp, " \t\r\n"); if (!*ap) { if (secure && ap == &av[4]) { puts("must provide username\r\n"); exit(1); } break; } if (secure && strchr(*ap, '@')) { puts("forwarding service denied\r\n"); exit(1); } /* RFC742: "/[Ww]" == "-l" */ if ((*ap)[0] == '/' && ((*ap)[1] == 'W' || (*ap)[1] == 'w')) { *comp-- = "-l"; } else if (++ap == av + ENTRIES) { *ap = NULL; break; } lp = NULL; } if ((lp = strrchr(prog, '/')) != NULL) *comp = ++lp; else *comp = prog; if (pipe(p) < 0) logerr("pipe: %s", strerror(errno)); if (debug) { fprintf(stderr, "%s", prog); for (ap = comp; *ap != NULL; ++ap) fprintf(stderr, " %s", *ap); fprintf(stderr, "\n"); } switch(vfork()) { case 0: (void)close(p[0]); if (p[1] != STDOUT_FILENO) { (void)dup2(p[1], STDOUT_FILENO); (void)close(p[1]); } dup2(STDOUT_FILENO, STDERR_FILENO); execv(prog, comp); write(STDERR_FILENO, prog, strlen(prog)); #define MSG ": cannot execute\n" write(STDERR_FILENO, MSG, strlen(MSG)); #undef MSG _exit(1); case -1: logerr("fork: %s", strerror(errno)); } (void)close(p[1]); if (!(fp = fdopen(p[0], "r"))) logerr("fdopen: %s", strerror(errno)); while ((ch = getc(fp)) != EOF) { if (ch == '\n') putchar('\r'); putchar(ch); } exit(0); } #include void logerr(const char *fmt, ...) { va_list ap; va_start(ap, fmt); (void)vsyslog(LOG_ERR, fmt, ap); va_end(ap); exit(1); /* NOTREACHED */ } Index: head/libexec/fingerd/pathnames.h =================================================================== --- head/libexec/fingerd/pathnames.h (revision 262135) +++ head/libexec/fingerd/pathnames.h (revision 262136) @@ -1,38 +1,34 @@ /* * Copyright (c) 1989, 1993 * The Regents of the University of California. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. * * @(#)pathnames.h 8.1 (Berkeley) 6/4/93 * * $FreeBSD$ */ #define _PATH_FINGER "/usr/bin/finger" Index: head/libexec/ftpd/extern.h =================================================================== --- head/libexec/ftpd/extern.h (revision 262135) +++ head/libexec/ftpd/extern.h (revision 262136) @@ -1,118 +1,114 @@ /*- * Copyright (c) 1992, 1993 * The Regents of the University of California. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. * * @(#)extern.h 8.2 (Berkeley) 4/4/94 * $FreeBSD$ */ #include #include void blkfree(char **); char **copyblk(char **); void cwd(char *); void delete(char *); void dologout(int); void fatalerror(char *); void ftpd_logwtmp(char *, char *, struct sockaddr *addr); int ftpd_pclose(FILE *); FILE *ftpd_popen(char *, char *); int getline(char *, int, FILE *); void lreply(int, const char *, ...) __printflike(2, 3); void makedir(char *); void nack(char *); void pass(char *); void passive(void); void long_passive(char *, int); void perror_reply(int, char *); void pwd(void); void removedir(char *); void renamecmd(char *, char *); char *renamefrom(char *); void reply(int, const char *, ...) __printflike(2, 3); void retrieve(char *, char *); void send_file_list(char *); #ifdef OLD_SETPROCTITLE void setproctitle(const char *, ...); #endif void statcmd(void); void statfilecmd(char *); void store(char *, char *, int); void upper(char *); void user(char *); void yyerror(char *); int yyparse(void); int ls_main(int, char **); extern int assumeutf8; extern char cbuf[]; extern union sockunion data_dest; extern int epsvall; extern int form; extern int ftpdebug; extern int guest; extern union sockunion his_addr; extern char *homedir; extern int hostinfo; extern char *hostname; extern int maxtimeout; extern int logged_in; extern int logging; extern int noepsv; extern int noguestretr; extern int noretr; extern int paranoid; extern struct passwd *pw; extern int pdata; extern char proctitle[]; extern int readonly; extern off_t restart_point; extern int timeout; extern char tmpline[]; extern int type; extern char *typenames[]; /* defined in included from ftpd.c */ extern int usedefault; struct sockaddr_in; struct sockaddr_in6; union sockunion { struct sockinet { u_char si_len; u_char si_family; u_short si_port; } su_si; struct sockaddr_in su_sin; struct sockaddr_in6 su_sin6; }; #define su_len su_si.si_len #define su_family su_si.si_family #define su_port su_si.si_port Index: head/libexec/ftpd/ftpcmd.y =================================================================== --- head/libexec/ftpd/ftpcmd.y (revision 262135) +++ head/libexec/ftpd/ftpcmd.y (revision 262136) @@ -1,1817 +1,1813 @@ /* * Copyright (c) 1985, 1988, 1993, 1994 * The Regents of the University of California. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. * * @(#)ftpcmd.y 8.3 (Berkeley) 4/6/94 */ /* * Grammar for FTP commands. * See RFC 959. */ %{ #ifndef lint #if 0 static char sccsid[] = "@(#)ftpcmd.y 8.3 (Berkeley) 4/6/94"; #endif #endif /* not lint */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "extern.h" #include "pathnames.h" off_t restart_point; static int cmd_type; static int cmd_form; static int cmd_bytesz; static int state; char cbuf[512]; char *fromname = NULL; %} %union { struct { off_t o; int i; } u; char *s; } %token A B C E F I L N P R S T ALL SP CRLF COMMA USER PASS ACCT REIN QUIT PORT PASV TYPE STRU MODE RETR STOR APPE MLFL MAIL MSND MSOM MSAM MRSQ MRCP ALLO REST RNFR RNTO ABOR DELE CWD LIST NLST SITE STAT HELP NOOP MKD RMD PWD CDUP STOU SMNT SYST SIZE MDTM LPRT LPSV EPRT EPSV FEAT UMASK IDLE CHMOD MDFIVE LEXERR NOTIMPL %token STRING %token NUMBER %type check_login octal_number byte_size %type check_login_ro check_login_epsv %type struct_code mode_code type_code form_code %type pathstring pathname password username %type ALL NOTIMPL %start cmd_list %% cmd_list : /* empty */ | cmd_list cmd { if (fromname) free(fromname); fromname = NULL; restart_point = 0; } | cmd_list rcmd ; cmd : USER SP username CRLF { user($3); free($3); } | PASS SP password CRLF { pass($3); free($3); } | PASS CRLF { pass(""); } | PORT check_login SP host_port CRLF { if (epsvall) { reply(501, "No PORT allowed after EPSV ALL."); goto port_done; } if (!$2) goto port_done; if (port_check("PORT") == 1) goto port_done; #ifdef INET6 if ((his_addr.su_family != AF_INET6 || !IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr))) { /* shoud never happen */ usedefault = 1; reply(500, "Invalid address rejected."); goto port_done; } port_check_v6("pcmd"); #endif port_done: ; } | LPRT check_login SP host_long_port CRLF { if (epsvall) { reply(501, "No LPRT allowed after EPSV ALL."); goto lprt_done; } if (!$2) goto lprt_done; if (port_check("LPRT") == 1) goto lprt_done; #ifdef INET6 if (his_addr.su_family != AF_INET6) { usedefault = 1; reply(500, "Invalid address rejected."); goto lprt_done; } if (port_check_v6("LPRT") == 1) goto lprt_done; #endif lprt_done: ; } | EPRT check_login SP STRING CRLF { char delim; char *tmp = NULL; char *p, *q; char *result[3]; struct addrinfo hints; struct addrinfo *res; int i; if (epsvall) { reply(501, "No EPRT allowed after EPSV ALL."); goto eprt_done; } if (!$2) goto eprt_done; memset(&data_dest, 0, sizeof(data_dest)); tmp = strdup($4); if (ftpdebug) syslog(LOG_DEBUG, "%s", tmp); if (!tmp) { fatalerror("not enough core"); /*NOTREACHED*/ } p = tmp; delim = p[0]; p++; memset(result, 0, sizeof(result)); for (i = 0; i < 3; i++) { q = strchr(p, delim); if (!q || *q != delim) { parsefail: reply(500, "Invalid argument, rejected."); if (tmp) free(tmp); usedefault = 1; goto eprt_done; } *q++ = '\0'; result[i] = p; if (ftpdebug) syslog(LOG_DEBUG, "%d: %s", i, p); p = q; } /* some more sanity check */ p = result[0]; while (*p) { if (!isdigit(*p)) goto parsefail; p++; } p = result[2]; while (*p) { if (!isdigit(*p)) goto parsefail; p++; } /* grab address */ memset(&hints, 0, sizeof(hints)); if (atoi(result[0]) == 1) hints.ai_family = PF_INET; #ifdef INET6 else if (atoi(result[0]) == 2) hints.ai_family = PF_INET6; #endif else hints.ai_family = PF_UNSPEC; /*XXX*/ hints.ai_socktype = SOCK_STREAM; i = getaddrinfo(result[1], result[2], &hints, &res); if (i) goto parsefail; memcpy(&data_dest, res->ai_addr, res->ai_addrlen); #ifdef INET6 if (his_addr.su_family == AF_INET6 && data_dest.su_family == AF_INET6) { /* XXX more sanity checks! */ data_dest.su_sin6.sin6_scope_id = his_addr.su_sin6.sin6_scope_id; } #endif free(tmp); tmp = NULL; if (port_check("EPRT") == 1) goto eprt_done; #ifdef INET6 if (his_addr.su_family != AF_INET6) { usedefault = 1; reply(500, "Invalid address rejected."); goto eprt_done; } if (port_check_v6("EPRT") == 1) goto eprt_done; #endif eprt_done: free($4); } | PASV check_login CRLF { if (epsvall) reply(501, "No PASV allowed after EPSV ALL."); else if ($2) passive(); } | LPSV check_login CRLF { if (epsvall) reply(501, "No LPSV allowed after EPSV ALL."); else if ($2) long_passive("LPSV", PF_UNSPEC); } | EPSV check_login_epsv SP NUMBER CRLF { if ($2) { int pf; switch ($4.i) { case 1: pf = PF_INET; break; #ifdef INET6 case 2: pf = PF_INET6; break; #endif default: pf = -1; /*junk value*/ break; } long_passive("EPSV", pf); } } | EPSV check_login_epsv SP ALL CRLF { if ($2) { reply(200, "EPSV ALL command successful."); epsvall++; } } | EPSV check_login_epsv CRLF { if ($2) long_passive("EPSV", PF_UNSPEC); } | TYPE check_login SP type_code CRLF { if ($2) { switch (cmd_type) { case TYPE_A: if (cmd_form == FORM_N) { reply(200, "Type set to A."); type = cmd_type; form = cmd_form; } else reply(504, "Form must be N."); break; case TYPE_E: reply(504, "Type E not implemented."); break; case TYPE_I: reply(200, "Type set to I."); type = cmd_type; break; case TYPE_L: #if CHAR_BIT == 8 if (cmd_bytesz == 8) { reply(200, "Type set to L (byte size 8)."); type = cmd_type; } else reply(504, "Byte size must be 8."); #else /* CHAR_BIT == 8 */ UNIMPLEMENTED for CHAR_BIT != 8 #endif /* CHAR_BIT == 8 */ } } } | STRU check_login SP struct_code CRLF { if ($2) { switch ($4) { case STRU_F: reply(200, "STRU F accepted."); break; default: reply(504, "Unimplemented STRU type."); } } } | MODE check_login SP mode_code CRLF { if ($2) { switch ($4) { case MODE_S: reply(200, "MODE S accepted."); break; default: reply(502, "Unimplemented MODE type."); } } } | ALLO check_login SP NUMBER CRLF { if ($2) { reply(202, "ALLO command ignored."); } } | ALLO check_login SP NUMBER SP R SP NUMBER CRLF { if ($2) { reply(202, "ALLO command ignored."); } } | RETR check_login SP pathname CRLF { if (noretr || (guest && noguestretr)) reply(500, "RETR command disabled."); else if ($2 && $4 != NULL) retrieve(NULL, $4); if ($4 != NULL) free($4); } | STOR check_login_ro SP pathname CRLF { if ($2 && $4 != NULL) store($4, "w", 0); if ($4 != NULL) free($4); } | APPE check_login_ro SP pathname CRLF { if ($2 && $4 != NULL) store($4, "a", 0); if ($4 != NULL) free($4); } | NLST check_login CRLF { if ($2) send_file_list("."); } | NLST check_login SP pathstring CRLF { if ($2) send_file_list($4); free($4); } | LIST check_login CRLF { if ($2) retrieve(_PATH_LS " -lgA", ""); } | LIST check_login SP pathstring CRLF { if ($2) retrieve(_PATH_LS " -lgA %s", $4); free($4); } | STAT check_login SP pathname CRLF { if ($2 && $4 != NULL) statfilecmd($4); if ($4 != NULL) free($4); } | STAT check_login CRLF { if ($2) { statcmd(); } } | DELE check_login_ro SP pathname CRLF { if ($2 && $4 != NULL) delete($4); if ($4 != NULL) free($4); } | RNTO check_login_ro SP pathname CRLF { if ($2 && $4 != NULL) { if (fromname) { renamecmd(fromname, $4); free(fromname); fromname = NULL; } else { reply(503, "Bad sequence of commands."); } } if ($4 != NULL) free($4); } | ABOR check_login CRLF { if ($2) reply(225, "ABOR command successful."); } | CWD check_login CRLF { if ($2) { cwd(homedir); } } | CWD check_login SP pathname CRLF { if ($2 && $4 != NULL) cwd($4); if ($4 != NULL) free($4); } | HELP CRLF { help(cmdtab, NULL); } | HELP SP STRING CRLF { char *cp = $3; if (strncasecmp(cp, "SITE", 4) == 0) { cp = $3 + 4; if (*cp == ' ') cp++; if (*cp) help(sitetab, cp); else help(sitetab, NULL); } else help(cmdtab, $3); free($3); } | NOOP CRLF { reply(200, "NOOP command successful."); } | MKD check_login_ro SP pathname CRLF { if ($2 && $4 != NULL) makedir($4); if ($4 != NULL) free($4); } | RMD check_login_ro SP pathname CRLF { if ($2 && $4 != NULL) removedir($4); if ($4 != NULL) free($4); } | PWD check_login CRLF { if ($2) pwd(); } | CDUP check_login CRLF { if ($2) cwd(".."); } | SITE SP HELP CRLF { help(sitetab, NULL); } | SITE SP HELP SP STRING CRLF { help(sitetab, $5); free($5); } | SITE SP MDFIVE check_login SP pathname CRLF { char p[64], *q; if ($4 && $6) { q = MD5File($6, p); if (q != NULL) reply(200, "MD5(%s) = %s", $6, p); else perror_reply(550, $6); } if ($6) free($6); } | SITE SP UMASK check_login CRLF { int oldmask; if ($4) { oldmask = umask(0); (void) umask(oldmask); reply(200, "Current UMASK is %03o.", oldmask); } } | SITE SP UMASK check_login SP octal_number CRLF { int oldmask; if ($4) { if (($6 == -1) || ($6 > 0777)) { reply(501, "Bad UMASK value."); } else { oldmask = umask($6); reply(200, "UMASK set to %03o (was %03o).", $6, oldmask); } } } | SITE SP CHMOD check_login_ro SP octal_number SP pathname CRLF { if ($4 && ($8 != NULL)) { if (($6 == -1 ) || ($6 > 0777)) reply(501, "Bad mode value."); else if (chmod($8, $6) < 0) perror_reply(550, $8); else reply(200, "CHMOD command successful."); } if ($8 != NULL) free($8); } | SITE SP check_login IDLE CRLF { if ($3) reply(200, "Current IDLE time limit is %d seconds; max %d.", timeout, maxtimeout); } | SITE SP check_login IDLE SP NUMBER CRLF { if ($3) { if ($6.i < 30 || $6.i > maxtimeout) { reply(501, "Maximum IDLE time must be between 30 and %d seconds.", maxtimeout); } else { timeout = $6.i; (void) alarm(timeout); reply(200, "Maximum IDLE time set to %d seconds.", timeout); } } } | STOU check_login_ro SP pathname CRLF { if ($2 && $4 != NULL) store($4, "w", 1); if ($4 != NULL) free($4); } | FEAT CRLF { lreply(211, "Extensions supported:"); #if 0 /* XXX these two keywords are non-standard */ printf(" EPRT\r\n"); if (!noepsv) printf(" EPSV\r\n"); #endif printf(" MDTM\r\n"); printf(" REST STREAM\r\n"); printf(" SIZE\r\n"); if (assumeutf8) { /* TVFS requires UTF8, see RFC 3659 */ printf(" TVFS\r\n"); printf(" UTF8\r\n"); } reply(211, "End."); } | SYST check_login CRLF { if ($2) { if (hostinfo) #ifdef BSD reply(215, "UNIX Type: L%d Version: BSD-%d", CHAR_BIT, BSD); #else /* BSD */ reply(215, "UNIX Type: L%d", CHAR_BIT); #endif /* BSD */ else reply(215, "UNKNOWN Type: L%d", CHAR_BIT); } } /* * SIZE is not in RFC959, but Postel has blessed it and * it will be in the updated RFC. * * Return size of file in a format suitable for * using with RESTART (we just count bytes). */ | SIZE check_login SP pathname CRLF { if ($2 && $4 != NULL) sizecmd($4); if ($4 != NULL) free($4); } /* * MDTM is not in RFC959, but Postel has blessed it and * it will be in the updated RFC. * * Return modification time of file as an ISO 3307 * style time. E.g. YYYYMMDDHHMMSS or YYYYMMDDHHMMSS.xxx * where xxx is the fractional second (of any precision, * not necessarily 3 digits) */ | MDTM check_login SP pathname CRLF { if ($2 && $4 != NULL) { struct stat stbuf; if (stat($4, &stbuf) < 0) perror_reply(550, $4); else if (!S_ISREG(stbuf.st_mode)) { reply(550, "%s: not a plain file.", $4); } else { struct tm *t; t = gmtime(&stbuf.st_mtime); reply(213, "%04d%02d%02d%02d%02d%02d", 1900 + t->tm_year, t->tm_mon+1, t->tm_mday, t->tm_hour, t->tm_min, t->tm_sec); } } if ($4 != NULL) free($4); } | QUIT CRLF { reply(221, "Goodbye."); dologout(0); } | NOTIMPL { nack($1); } | error { yyclearin; /* discard lookahead data */ yyerrok; /* clear error condition */ state = CMD; /* reset lexer state */ } ; rcmd : RNFR check_login_ro SP pathname CRLF { restart_point = 0; if ($2 && $4) { if (fromname) free(fromname); fromname = NULL; if (renamefrom($4)) fromname = $4; else free($4); } else if ($4) { free($4); } } | REST check_login SP NUMBER CRLF { if ($2) { if (fromname) free(fromname); fromname = NULL; restart_point = $4.o; reply(350, "Restarting at %jd. %s", (intmax_t)restart_point, "Send STORE or RETRIEVE to initiate transfer."); } } ; username : STRING ; password : /* empty */ { $$ = (char *)calloc(1, sizeof(char)); } | STRING ; byte_size : NUMBER { $$ = $1.i; } ; host_port : NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER { char *a, *p; data_dest.su_len = sizeof(struct sockaddr_in); data_dest.su_family = AF_INET; p = (char *)&data_dest.su_sin.sin_port; p[0] = $9.i; p[1] = $11.i; a = (char *)&data_dest.su_sin.sin_addr; a[0] = $1.i; a[1] = $3.i; a[2] = $5.i; a[3] = $7.i; } ; host_long_port : NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER { char *a, *p; memset(&data_dest, 0, sizeof(data_dest)); data_dest.su_len = sizeof(struct sockaddr_in6); data_dest.su_family = AF_INET6; p = (char *)&data_dest.su_port; p[0] = $39.i; p[1] = $41.i; a = (char *)&data_dest.su_sin6.sin6_addr; a[0] = $5.i; a[1] = $7.i; a[2] = $9.i; a[3] = $11.i; a[4] = $13.i; a[5] = $15.i; a[6] = $17.i; a[7] = $19.i; a[8] = $21.i; a[9] = $23.i; a[10] = $25.i; a[11] = $27.i; a[12] = $29.i; a[13] = $31.i; a[14] = $33.i; a[15] = $35.i; if (his_addr.su_family == AF_INET6) { /* XXX more sanity checks! */ data_dest.su_sin6.sin6_scope_id = his_addr.su_sin6.sin6_scope_id; } if ($1.i != 6 || $3.i != 16 || $37.i != 2) memset(&data_dest, 0, sizeof(data_dest)); } | NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER COMMA NUMBER { char *a, *p; memset(&data_dest, 0, sizeof(data_dest)); data_dest.su_sin.sin_len = sizeof(struct sockaddr_in); data_dest.su_family = AF_INET; p = (char *)&data_dest.su_port; p[0] = $15.i; p[1] = $17.i; a = (char *)&data_dest.su_sin.sin_addr; a[0] = $5.i; a[1] = $7.i; a[2] = $9.i; a[3] = $11.i; if ($1.i != 4 || $3.i != 4 || $13.i != 2) memset(&data_dest, 0, sizeof(data_dest)); } ; form_code : N { $$ = FORM_N; } | T { $$ = FORM_T; } | C { $$ = FORM_C; } ; type_code : A { cmd_type = TYPE_A; cmd_form = FORM_N; } | A SP form_code { cmd_type = TYPE_A; cmd_form = $3; } | E { cmd_type = TYPE_E; cmd_form = FORM_N; } | E SP form_code { cmd_type = TYPE_E; cmd_form = $3; } | I { cmd_type = TYPE_I; } | L { cmd_type = TYPE_L; cmd_bytesz = CHAR_BIT; } | L SP byte_size { cmd_type = TYPE_L; cmd_bytesz = $3; } /* this is for a bug in the BBN ftp */ | L byte_size { cmd_type = TYPE_L; cmd_bytesz = $2; } ; struct_code : F { $$ = STRU_F; } | R { $$ = STRU_R; } | P { $$ = STRU_P; } ; mode_code : S { $$ = MODE_S; } | B { $$ = MODE_B; } | C { $$ = MODE_C; } ; pathname : pathstring { if (logged_in && $1) { char *p; /* * Expand ~user manually since glob(3) * will return the unexpanded pathname * if the corresponding file/directory * doesn't exist yet. Using sole glob(3) * would break natural commands like * MKD ~user/newdir * or * RNTO ~/newfile */ if ((p = exptilde($1)) != NULL) { $$ = expglob(p); free(p); } else $$ = NULL; free($1); } else $$ = $1; } ; pathstring : STRING ; octal_number : NUMBER { int ret, dec, multby, digit; /* * Convert a number that was read as decimal number * to what it would be if it had been read as octal. */ dec = $1.i; multby = 1; ret = 0; while (dec) { digit = dec%10; if (digit > 7) { ret = -1; break; } ret += digit * multby; multby *= 8; dec /= 10; } $$ = ret; } ; check_login : /* empty */ { $$ = check_login1(); } ; check_login_epsv : /* empty */ { if (noepsv) { reply(500, "EPSV command disabled."); $$ = 0; } else $$ = check_login1(); } ; check_login_ro : /* empty */ { if (readonly) { reply(550, "Permission denied."); $$ = 0; } else $$ = check_login1(); } ; %% #define CMD 0 /* beginning of command */ #define ARGS 1 /* expect miscellaneous arguments */ #define STR1 2 /* expect SP followed by STRING */ #define STR2 3 /* expect STRING */ #define OSTR 4 /* optional SP then STRING */ #define ZSTR1 5 /* optional SP then optional STRING */ #define ZSTR2 6 /* optional STRING after SP */ #define SITECMD 7 /* SITE command */ #define NSTR 8 /* Number followed by a string */ #define MAXGLOBARGS 1000 #define MAXASIZE 10240 /* Deny ASCII SIZE on files larger than that */ struct tab { char *name; short token; short state; short implemented; /* 1 if command is implemented */ char *help; }; struct tab cmdtab[] = { /* In order defined in RFC 765 */ { "USER", USER, STR1, 1, " username" }, { "PASS", PASS, ZSTR1, 1, "[ [password]]" }, { "ACCT", ACCT, STR1, 0, "(specify account)" }, { "SMNT", SMNT, ARGS, 0, "(structure mount)" }, { "REIN", REIN, ARGS, 0, "(reinitialize server state)" }, { "QUIT", QUIT, ARGS, 1, "(terminate service)", }, { "PORT", PORT, ARGS, 1, " b0, b1, b2, b3, b4, b5" }, { "LPRT", LPRT, ARGS, 1, " af, hal, h1, h2, h3,..., pal, p1, p2..." }, { "EPRT", EPRT, STR1, 1, " |af|addr|port|" }, { "PASV", PASV, ARGS, 1, "(set server in passive mode)" }, { "LPSV", LPSV, ARGS, 1, "(set server in passive mode)" }, { "EPSV", EPSV, ARGS, 1, "[ af|ALL]" }, { "TYPE", TYPE, ARGS, 1, " { A | E | I | L }" }, { "STRU", STRU, ARGS, 1, "(specify file structure)" }, { "MODE", MODE, ARGS, 1, "(specify transfer mode)" }, { "RETR", RETR, STR1, 1, " file-name" }, { "STOR", STOR, STR1, 1, " file-name" }, { "APPE", APPE, STR1, 1, " file-name" }, { "MLFL", MLFL, OSTR, 0, "(mail file)" }, { "MAIL", MAIL, OSTR, 0, "(mail to user)" }, { "MSND", MSND, OSTR, 0, "(mail send to terminal)" }, { "MSOM", MSOM, OSTR, 0, "(mail send to terminal or mailbox)" }, { "MSAM", MSAM, OSTR, 0, "(mail send to terminal and mailbox)" }, { "MRSQ", MRSQ, OSTR, 0, "(mail recipient scheme question)" }, { "MRCP", MRCP, STR1, 0, "(mail recipient)" }, { "ALLO", ALLO, ARGS, 1, "allocate storage (vacuously)" }, { "REST", REST, ARGS, 1, " offset (restart command)" }, { "RNFR", RNFR, STR1, 1, " file-name" }, { "RNTO", RNTO, STR1, 1, " file-name" }, { "ABOR", ABOR, ARGS, 1, "(abort operation)" }, { "DELE", DELE, STR1, 1, " file-name" }, { "CWD", CWD, OSTR, 1, "[ directory-name ]" }, { "XCWD", CWD, OSTR, 1, "[ directory-name ]" }, { "LIST", LIST, OSTR, 1, "[ path-name ]" }, { "NLST", NLST, OSTR, 1, "[ path-name ]" }, { "SITE", SITE, SITECMD, 1, "site-cmd [ arguments ]" }, { "SYST", SYST, ARGS, 1, "(get type of operating system)" }, { "FEAT", FEAT, ARGS, 1, "(get extended features)" }, { "STAT", STAT, OSTR, 1, "[ path-name ]" }, { "HELP", HELP, OSTR, 1, "[ ]" }, { "NOOP", NOOP, ARGS, 1, "" }, { "MKD", MKD, STR1, 1, " path-name" }, { "XMKD", MKD, STR1, 1, " path-name" }, { "RMD", RMD, STR1, 1, " path-name" }, { "XRMD", RMD, STR1, 1, " path-name" }, { "PWD", PWD, ARGS, 1, "(return current directory)" }, { "XPWD", PWD, ARGS, 1, "(return current directory)" }, { "CDUP", CDUP, ARGS, 1, "(change to parent directory)" }, { "XCUP", CDUP, ARGS, 1, "(change to parent directory)" }, { "STOU", STOU, STR1, 1, " file-name" }, { "SIZE", SIZE, OSTR, 1, " path-name" }, { "MDTM", MDTM, OSTR, 1, " path-name" }, { NULL, 0, 0, 0, 0 } }; struct tab sitetab[] = { { "MD5", MDFIVE, STR1, 1, "[ file-name ]" }, { "UMASK", UMASK, ARGS, 1, "[ umask ]" }, { "IDLE", IDLE, ARGS, 1, "[ maximum-idle-time ]" }, { "CHMOD", CHMOD, NSTR, 1, " mode file-name" }, { "HELP", HELP, OSTR, 1, "[ ]" }, { NULL, 0, 0, 0, 0 } }; static char *copy(char *); static char *expglob(char *); static char *exptilde(char *); static void help(struct tab *, char *); static struct tab * lookup(struct tab *, char *); static int port_check(const char *); #ifdef INET6 static int port_check_v6(const char *); #endif static void sizecmd(char *); static void toolong(int); #ifdef INET6 static void v4map_data_dest(void); #endif static int yylex(void); static struct tab * lookup(struct tab *p, char *cmd) { for (; p->name != NULL; p++) if (strcmp(cmd, p->name) == 0) return (p); return (0); } #include /* * getline - a hacked up version of fgets to ignore TELNET escape codes. */ int getline(char *s, int n, FILE *iop) { int c; register char *cs; sigset_t sset, osset; cs = s; /* tmpline may contain saved command from urgent mode interruption */ for (c = 0; tmpline[c] != '\0' && --n > 0; ++c) { *cs++ = tmpline[c]; if (tmpline[c] == '\n') { *cs++ = '\0'; if (ftpdebug) syslog(LOG_DEBUG, "command: %s", s); tmpline[0] = '\0'; return(0); } if (c == 0) tmpline[0] = '\0'; } /* SIGURG would interrupt stdio if not blocked during the read loop */ sigemptyset(&sset); sigaddset(&sset, SIGURG); sigprocmask(SIG_BLOCK, &sset, &osset); while ((c = getc(iop)) != EOF) { c &= 0377; if (c == IAC) { if ((c = getc(iop)) == EOF) goto got_eof; c &= 0377; switch (c) { case WILL: case WONT: if ((c = getc(iop)) == EOF) goto got_eof; printf("%c%c%c", IAC, DONT, 0377&c); (void) fflush(stdout); continue; case DO: case DONT: if ((c = getc(iop)) == EOF) goto got_eof; printf("%c%c%c", IAC, WONT, 0377&c); (void) fflush(stdout); continue; case IAC: break; default: continue; /* ignore command */ } } *cs++ = c; if (--n <= 0) { /* * If command doesn't fit into buffer, discard the * rest of the command and indicate truncation. * This prevents the command to be split up into * multiple commands. */ while (c != '\n' && (c = getc(iop)) != EOF) ; return (-2); } if (c == '\n') break; } got_eof: sigprocmask(SIG_SETMASK, &osset, NULL); if (c == EOF && cs == s) return (-1); *cs++ = '\0'; if (ftpdebug) { if (!guest && strncasecmp("pass ", s, 5) == 0) { /* Don't syslog passwords */ syslog(LOG_DEBUG, "command: %.5s ???", s); } else { register char *cp; register int len; /* Don't syslog trailing CR-LF */ len = strlen(s); cp = s + len - 1; while (cp >= s && (*cp == '\n' || *cp == '\r')) { --cp; --len; } syslog(LOG_DEBUG, "command: %.*s", len, s); } } return (0); } static void toolong(int signo) { reply(421, "Timeout (%d seconds): closing control connection.", timeout); if (logging) syslog(LOG_INFO, "User %s timed out after %d seconds", (pw ? pw -> pw_name : "unknown"), timeout); dologout(1); } static int yylex(void) { static int cpos; char *cp, *cp2; struct tab *p; int n; char c; for (;;) { switch (state) { case CMD: (void) signal(SIGALRM, toolong); (void) alarm(timeout); n = getline(cbuf, sizeof(cbuf)-1, stdin); if (n == -1) { reply(221, "You could at least say goodbye."); dologout(0); } else if (n == -2) { reply(500, "Command too long."); (void) alarm(0); continue; } (void) alarm(0); #ifdef SETPROCTITLE if (strncasecmp(cbuf, "PASS", 4) != 0) setproctitle("%s: %s", proctitle, cbuf); #endif /* SETPROCTITLE */ if ((cp = strchr(cbuf, '\r'))) { *cp++ = '\n'; *cp = '\0'; } if ((cp = strpbrk(cbuf, " \n"))) cpos = cp - cbuf; if (cpos == 0) cpos = 4; c = cbuf[cpos]; cbuf[cpos] = '\0'; upper(cbuf); p = lookup(cmdtab, cbuf); cbuf[cpos] = c; if (p != 0) { yylval.s = p->name; if (!p->implemented) return (NOTIMPL); /* state remains CMD */ state = p->state; return (p->token); } break; case SITECMD: if (cbuf[cpos] == ' ') { cpos++; return (SP); } cp = &cbuf[cpos]; if ((cp2 = strpbrk(cp, " \n"))) cpos = cp2 - cbuf; c = cbuf[cpos]; cbuf[cpos] = '\0'; upper(cp); p = lookup(sitetab, cp); cbuf[cpos] = c; if (guest == 0 && p != 0) { yylval.s = p->name; if (!p->implemented) { state = CMD; return (NOTIMPL); } state = p->state; return (p->token); } state = CMD; break; case ZSTR1: case OSTR: if (cbuf[cpos] == '\n') { state = CMD; return (CRLF); } /* FALLTHROUGH */ case STR1: dostr1: if (cbuf[cpos] == ' ') { cpos++; state = state == OSTR ? STR2 : state+1; return (SP); } break; case ZSTR2: if (cbuf[cpos] == '\n') { state = CMD; return (CRLF); } /* FALLTHROUGH */ case STR2: cp = &cbuf[cpos]; n = strlen(cp); cpos += n - 1; /* * Make sure the string is nonempty and \n terminated. */ if (n > 1 && cbuf[cpos] == '\n') { cbuf[cpos] = '\0'; yylval.s = copy(cp); cbuf[cpos] = '\n'; state = ARGS; return (STRING); } break; case NSTR: if (cbuf[cpos] == ' ') { cpos++; return (SP); } if (isdigit(cbuf[cpos])) { cp = &cbuf[cpos]; while (isdigit(cbuf[++cpos])) ; c = cbuf[cpos]; cbuf[cpos] = '\0'; yylval.u.i = atoi(cp); cbuf[cpos] = c; state = STR1; return (NUMBER); } state = STR1; goto dostr1; case ARGS: if (isdigit(cbuf[cpos])) { cp = &cbuf[cpos]; while (isdigit(cbuf[++cpos])) ; c = cbuf[cpos]; cbuf[cpos] = '\0'; yylval.u.i = atoi(cp); yylval.u.o = strtoull(cp, NULL, 10); cbuf[cpos] = c; return (NUMBER); } if (strncasecmp(&cbuf[cpos], "ALL", 3) == 0 && !isalnum(cbuf[cpos + 3])) { cpos += 3; return ALL; } switch (cbuf[cpos++]) { case '\n': state = CMD; return (CRLF); case ' ': return (SP); case ',': return (COMMA); case 'A': case 'a': return (A); case 'B': case 'b': return (B); case 'C': case 'c': return (C); case 'E': case 'e': return (E); case 'F': case 'f': return (F); case 'I': case 'i': return (I); case 'L': case 'l': return (L); case 'N': case 'n': return (N); case 'P': case 'p': return (P); case 'R': case 'r': return (R); case 'S': case 's': return (S); case 'T': case 't': return (T); } break; default: fatalerror("Unknown state in scanner."); } state = CMD; return (LEXERR); } } void upper(char *s) { while (*s != '\0') { if (islower(*s)) *s = toupper(*s); s++; } } static char * copy(char *s) { char *p; p = malloc(strlen(s) + 1); if (p == NULL) fatalerror("Ran out of memory."); (void) strcpy(p, s); return (p); } static void help(struct tab *ctab, char *s) { struct tab *c; int width, NCMDS; char *type; if (ctab == sitetab) type = "SITE "; else type = ""; width = 0, NCMDS = 0; for (c = ctab; c->name != NULL; c++) { int len = strlen(c->name); if (len > width) width = len; NCMDS++; } width = (width + 8) &~ 7; if (s == 0) { int i, j, w; int columns, lines; lreply(214, "The following %scommands are recognized %s.", type, "(* =>'s unimplemented)"); columns = 76 / width; if (columns == 0) columns = 1; lines = (NCMDS + columns - 1) / columns; for (i = 0; i < lines; i++) { printf(" "); for (j = 0; j < columns; j++) { c = ctab + j * lines + i; printf("%s%c", c->name, c->implemented ? ' ' : '*'); if (c + lines >= &ctab[NCMDS]) break; w = strlen(c->name) + 1; while (w < width) { putchar(' '); w++; } } printf("\r\n"); } (void) fflush(stdout); if (hostinfo) reply(214, "Direct comments to ftp-bugs@%s.", hostname); else reply(214, "End."); return; } upper(s); c = lookup(ctab, s); if (c == NULL) { reply(502, "Unknown command %s.", s); return; } if (c->implemented) reply(214, "Syntax: %s%s %s", type, c->name, c->help); else reply(214, "%s%-*s\t%s; unimplemented.", type, width, c->name, c->help); } static void sizecmd(char *filename) { switch (type) { case TYPE_L: case TYPE_I: { struct stat stbuf; if (stat(filename, &stbuf) < 0) perror_reply(550, filename); else if (!S_ISREG(stbuf.st_mode)) reply(550, "%s: not a plain file.", filename); else reply(213, "%jd", (intmax_t)stbuf.st_size); break; } case TYPE_A: { FILE *fin; int c; off_t count; struct stat stbuf; fin = fopen(filename, "r"); if (fin == NULL) { perror_reply(550, filename); return; } if (fstat(fileno(fin), &stbuf) < 0) { perror_reply(550, filename); (void) fclose(fin); return; } else if (!S_ISREG(stbuf.st_mode)) { reply(550, "%s: not a plain file.", filename); (void) fclose(fin); return; } else if (stbuf.st_size > MAXASIZE) { reply(550, "%s: too large for type A SIZE.", filename); (void) fclose(fin); return; } count = 0; while((c=getc(fin)) != EOF) { if (c == '\n') /* will get expanded to \r\n */ count++; count++; } (void) fclose(fin); reply(213, "%jd", (intmax_t)count); break; } default: reply(504, "SIZE not implemented for type %s.", typenames[type]); } } /* Return 1, if port check is done. Return 0, if not yet. */ static int port_check(const char *pcmd) { if (his_addr.su_family == AF_INET) { if (data_dest.su_family != AF_INET) { usedefault = 1; reply(500, "Invalid address rejected."); return 1; } if (paranoid && ((ntohs(data_dest.su_port) < IPPORT_RESERVED) || memcmp(&data_dest.su_sin.sin_addr, &his_addr.su_sin.sin_addr, sizeof(data_dest.su_sin.sin_addr)))) { usedefault = 1; reply(500, "Illegal PORT range rejected."); } else { usedefault = 0; if (pdata >= 0) { (void) close(pdata); pdata = -1; } reply(200, "%s command successful.", pcmd); } return 1; } return 0; } static int check_login1(void) { if (logged_in) return 1; else { reply(530, "Please login with USER and PASS."); return 0; } } /* * Replace leading "~user" in a pathname by the user's login directory. * Returned string will be in a freshly malloced buffer unless it's NULL. */ static char * exptilde(char *s) { char *p, *q; char *path, *user; struct passwd *ppw; if ((p = strdup(s)) == NULL) return (NULL); if (*p != '~') return (p); user = p + 1; /* skip tilde */ if ((path = strchr(p, '/')) != NULL) *(path++) = '\0'; /* separate ~user from the rest of path */ if (*user == '\0') /* no user specified, use the current user */ user = pw->pw_name; /* read passwd even for the current user since we may be chrooted */ if ((ppw = getpwnam(user)) != NULL) { /* user found, substitute login directory for ~user */ if (path) asprintf(&q, "%s/%s", ppw->pw_dir, path); else q = strdup(ppw->pw_dir); free(p); p = q; } else { /* user not found, undo the damage */ if (path) path[-1] = '/'; } return (p); } /* * Expand glob(3) patterns possibly present in a pathname. * Avoid expanding to a pathname including '\r' or '\n' in order to * not disrupt the FTP protocol. * The expansion found must be unique. * Return the result as a malloced string, or NULL if an error occurred. * * Problem: this production is used for all pathname * processing, but only gives a 550 error reply. * This is a valid reply in some cases but not in others. */ static char * expglob(char *s) { char *p, **pp, *rval; int flags = GLOB_BRACE | GLOB_NOCHECK; int n; glob_t gl; memset(&gl, 0, sizeof(gl)); flags |= GLOB_LIMIT; gl.gl_matchc = MAXGLOBARGS; if (glob(s, flags, NULL, &gl) == 0 && gl.gl_pathc != 0) { for (pp = gl.gl_pathv, p = NULL, n = 0; *pp; pp++) if (*(*pp + strcspn(*pp, "\r\n")) == '\0') { p = *pp; n++; } if (n == 0) rval = strdup(s); else if (n == 1) rval = strdup(p); else { reply(550, "Wildcard is ambiguous."); rval = NULL; } } else { reply(550, "Wildcard expansion error."); rval = NULL; } globfree(&gl); return (rval); } #ifdef INET6 /* Return 1, if port check is done. Return 0, if not yet. */ static int port_check_v6(const char *pcmd) { if (his_addr.su_family == AF_INET6) { if (IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr)) /* Convert data_dest into v4 mapped sockaddr.*/ v4map_data_dest(); if (data_dest.su_family != AF_INET6) { usedefault = 1; reply(500, "Invalid address rejected."); return 1; } if (paranoid && ((ntohs(data_dest.su_port) < IPPORT_RESERVED) || memcmp(&data_dest.su_sin6.sin6_addr, &his_addr.su_sin6.sin6_addr, sizeof(data_dest.su_sin6.sin6_addr)))) { usedefault = 1; reply(500, "Illegal PORT range rejected."); } else { usedefault = 0; if (pdata >= 0) { (void) close(pdata); pdata = -1; } reply(200, "%s command successful.", pcmd); } return 1; } return 0; } static void v4map_data_dest(void) { struct in_addr savedaddr; int savedport; if (data_dest.su_family != AF_INET) { usedefault = 1; reply(500, "Invalid address rejected."); return; } savedaddr = data_dest.su_sin.sin_addr; savedport = data_dest.su_port; memset(&data_dest, 0, sizeof(data_dest)); data_dest.su_sin6.sin6_len = sizeof(struct sockaddr_in6); data_dest.su_sin6.sin6_family = AF_INET6; data_dest.su_sin6.sin6_port = savedport; memset((caddr_t)&data_dest.su_sin6.sin6_addr.s6_addr[10], 0xff, 2); memcpy((caddr_t)&data_dest.su_sin6.sin6_addr.s6_addr[12], (caddr_t)&savedaddr, sizeof(savedaddr)); } #endif Index: head/libexec/ftpd/ftpd.8 =================================================================== --- head/libexec/ftpd/ftpd.8 (revision 262135) +++ head/libexec/ftpd/ftpd.8 (revision 262136) @@ -1,578 +1,574 @@ .\" Copyright (c) 1985, 1988, 1991, 1993 .\" The Regents of the University of California. 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. -.\" 3. All advertising materials mentioning features or use of this software -.\" must display the following acknowledgement: -.\" This product includes software developed by the University of -.\" California, Berkeley and its contributors. -.\" 4. Neither the name of the University nor the names of its contributors +.\" 3. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. .\" .\" @(#)ftpd.8 8.2 (Berkeley) 4/19/94 .\" $FreeBSD$ .\" .Dd January 21, 2010 .Dt FTPD 8 .Os .Sh NAME .Nm ftpd .Nd Internet File Transfer Protocol server .Sh SYNOPSIS .Nm .Op Fl 468ADdEhMmOoRrSUvW .Op Fl l Op Fl l .Op Fl a Ar address .Op Fl P Ar port .Op Fl p Ar file .Op Fl T Ar maxtimeout .Op Fl t Ar timeout .Op Fl u Ar umask .Sh DESCRIPTION The .Nm utility is the Internet File Transfer Protocol server process. The server uses the .Tn TCP protocol and listens at the port specified with the .Fl P option or in the .Dq ftp service specification; see .Xr services 5 . .Pp Available options: .Bl -tag -width indent .It Fl 4 When .Fl D is specified, accept connections via .Dv AF_INET socket. .It Fl 6 When .Fl D is specified, accept connections via .Dv AF_INET6 socket. .It Fl 8 Enable transparent UTF-8 mode. RFC\ 2640 compliant clients will be told that the character encoding used by the server is UTF-8, which is the only effect of the option. .Pp This option does not enable any encoding conversion for server file names; it implies instead that the names of files on the server are encoded in UTF-8. As for files uploaded via FTP, it is the duty of the RFC\ 2640 compliant client to convert their names from the client's local encoding to UTF-8. FTP command names and own .Nm messages are always encoded in ASCII, which is a subset of UTF-8. Hence no need for server-side conversion at all. .It Fl A Allow only anonymous ftp access. .It Fl a When .Fl D is specified, accept connections only on the specified .Ar address . .It Fl D With this option set, .Nm will detach and become a daemon, accepting connections on the FTP port and forking children processes to handle them. This is lower overhead than starting .Nm from .Xr inetd 8 and is thus useful on busy servers to reduce load. .It Fl d Debugging information is written to the syslog using .Dv LOG_FTP . .It Fl E Disable the EPSV command. This is useful for servers behind older firewalls. .It Fl h Disable printing host-specific information, such as the server software version or hostname, in server messages. .It Fl l Each successful and failed .Xr ftp 1 session is logged using syslog with a facility of .Dv LOG_FTP . If this option is specified twice, the retrieve (get), store (put), append, delete, make directory, remove directory and rename operations and their filename arguments are also logged. By default, .Xr syslogd 8 logs these to .Pa /var/log/xferlog . .It Fl M Prevent anonymous users from creating directories. .It Fl m Permit anonymous users to overwrite or modify existing files if allowed by file system permissions. By default, anonymous users cannot modify existing files; in particular, files to upload will be created under a unique name. .It Fl O Put server in write-only mode for anonymous users only. RETR is disabled for anonymous users, preventing anonymous downloads. This has no effect if .Fl o is also specified. .It Fl o Put server in write-only mode. RETR is disabled, preventing downloads. .It Fl P When .Fl D is specified, accept connections at .Ar port , specified as a numeric value or service name, instead of at the default .Dq ftp port. .It Fl p When .Fl D is specified, write the daemon's process ID to .Ar file instead of the default pid file, .Pa /var/run/ftpd.pid . .It Fl R With this option set, .Nm will revert to historical behavior with regard to security checks on user operations and restrictions on PORT requests. Currently, .Nm will only honor PORT commands directed to unprivileged ports on the remote user's host (which violates the FTP protocol specification but closes some security holes). .It Fl r Put server in read-only mode. All commands which may modify the local file system are disabled. .It Fl S With this option set, .Nm logs all anonymous file downloads to the file .Pa /var/log/ftpd when this file exists. .It Fl T A client may also request a different timeout period; the maximum period allowed may be set to .Ar timeout seconds with the .Fl T option. The default limit is 2 hours. .It Fl t The inactivity timeout period is set to .Ar timeout seconds (the default is 15 minutes). .It Fl U This option instructs ftpd to use data ports in the range of .Dv IP_PORTRANGE_DEFAULT instead of in the range of .Dv IP_PORTRANGE_HIGH . Such a change may be useful for some specific firewall configurations; see .Xr ip 4 for more information. .Pp Note that option is a virtual no-op in .Fx 5.0 and above; both port ranges are identical by default. .It Fl u The default file creation mode mask is set to .Ar umask , which is expected to be an octal numeric value. Refer to .Xr umask 2 for details. This option may be overridden by .Xr login.conf 5 . .It Fl v A synonym for .Fl d . .It Fl W Do not log FTP sessions to the user accounting database. .El .Pp The file .Pa /var/run/nologin can be used to disable ftp access. If the file exists, .Nm displays it and exits. If the file .Pa /etc/ftpwelcome exists, .Nm prints it before issuing the .Dq ready message. If the file .Pa /etc/ftpmotd exists, .Nm prints it after a successful login. Note the motd file used is the one relative to the login environment. This means the one in .Pa ~ftp/etc in the anonymous user's case. .Pp The ftp server currently supports the following ftp requests. The case of the requests is ignored. Requests marked [RW] are disabled if .Fl r is specified. .Bl -column "Request" -offset indent .It Sy Request Ta Sy "Description" .It ABOR Ta "abort previous command" .It ACCT Ta "specify account (ignored)" .It ALLO Ta "allocate storage (vacuously)" .It APPE Ta "append to a file [RW]" .It CDUP Ta "change to parent of current working directory" .It CWD Ta "change working directory" .It DELE Ta "delete a file [RW]" .It EPRT Ta "specify data connection port, multiprotocol" .It EPSV Ta "prepare for server-to-server transfer, multiprotocol" .It FEAT Ta "give information on extended features of server" .It HELP Ta "give help information" .It LIST Ta "give list files in a directory" Pq Dq Li "ls -lgA" .It LPRT Ta "specify data connection port, multiprotocol" .It LPSV Ta "prepare for server-to-server transfer, multiprotocol" .It MDTM Ta "show last modification time of file" .It MKD Ta "make a directory [RW]" .It MODE Ta "specify data transfer" Em mode .It NLST Ta "give name list of files in directory" .It NOOP Ta "do nothing" .It PASS Ta "specify password" .It PASV Ta "prepare for server-to-server transfer" .It PORT Ta "specify data connection port" .It PWD Ta "print the current working directory" .It QUIT Ta "terminate session" .It REST Ta "restart incomplete transfer" .It RETR Ta "retrieve a file" .It RMD Ta "remove a directory [RW]" .It RNFR Ta "specify rename-from file name [RW]" .It RNTO Ta "specify rename-to file name [RW]" .It SITE Ta "non-standard commands (see next section)" .It SIZE Ta "return size of file" .It STAT Ta "return status of server" .It STOR Ta "store a file [RW]" .It STOU Ta "store a file with a unique name [RW]" .It STRU Ta "specify data transfer" Em structure .It SYST Ta "show operating system type of server system" .It TYPE Ta "specify data transfer" Em type .It USER Ta "specify user name" .It XCUP Ta "change to parent of current working directory (deprecated)" .It XCWD Ta "change working directory (deprecated)" .It XMKD Ta "make a directory (deprecated) [RW]" .It XPWD Ta "print the current working directory (deprecated)" .It XRMD Ta "remove a directory (deprecated) [RW]" .El .Pp The following non-standard or .Ux specific commands are supported by the SITE request. .Bl -column Request -offset indent .It Sy Request Ta Sy Description .It UMASK Ta change umask, e.g. ``SITE UMASK 002'' .It IDLE Ta set idle-timer, e.g. ``SITE IDLE 60'' .It CHMOD Ta "change mode of a file [RW], e.g. ``SITE CHMOD 755 filename''" .It MD5 Ta "report the files MD5 checksum, e.g. ``SITE MD5 filename''" .It HELP Ta give help information .El .Pp Note: SITE requests are disabled in case of anonymous logins. .Pp The remaining ftp requests specified in Internet RFC 959 are recognized, but not implemented. MDTM and SIZE are not specified in RFC 959, but will appear in the next updated FTP RFC. To avoid possible denial-of-service attacks, SIZE requests against files larger than 10240 bytes will be denied if the current transfer type is ASCII. .Pp The ftp server will abort an active file transfer only when the ABOR command is preceded by a Telnet "Interrupt Process" (IP) signal and a Telnet "Synch" signal in the command Telnet stream, as described in Internet RFC 959. If a STAT command is received during a data transfer, preceded by a Telnet IP and Synch, transfer status will be returned. .Pp The .Nm utility interprets file names according to the .Dq globbing conventions used by .Xr csh 1 . This allows users to utilize the metacharacters .Dq Li \&*?[]{}~ . .Pp The .Nm utility authenticates users according to six rules. .Bl -enum -offset indent .It The login name must be in the password data base and not have a null password. In this case a password must be provided by the client before any file operations may be performed. If the user has an OPIE key, the response from a successful USER command will include an OPIE challenge. The client may choose to respond with a PASS command giving either a standard password or an OPIE one-time password. The server will automatically determine which type of password it has been given and attempt to authenticate accordingly. See .Xr opie 4 for more information on OPIE authentication. .It The login name must not appear in the file .Pa /etc/ftpusers . .It The login name must not be a member of a group specified in the file .Pa /etc/ftpusers . Entries in this file interpreted as group names are prefixed by an "at" .Ql \&@ sign. .It The user must have a standard shell returned by .Xr getusershell 3 . .It If the user name appears in the file .Pa /etc/ftpchroot , or the user is a member of a group with a group entry in this file, i.e., one prefixed with .Ql \&@ , the session's root will be changed to the directory specified in this file or to the user's login directory by .Xr chroot 2 as for an .Dq anonymous or .Dq ftp account (see next item). See .Xr ftpchroot 5 for a detailed description of the format of this file. This facility may also be triggered by enabling the boolean "ftp-chroot" capability in .Xr login.conf 5 . However, the user must still supply a password. This feature is intended as a compromise between a fully anonymous account and a fully privileged account. The account should also be set up as for an anonymous account. .It If the user name is .Dq anonymous or .Dq ftp , an anonymous ftp account must be present in the password file (user .Dq ftp ) . In this case the user is allowed to log in by specifying any password (by convention an email address for the user should be used as the password). When the .Fl S option is set, all transfers are logged as well. .El .Pp In the last case, .Nm takes special measures to restrict the client's access privileges. The server performs a .Xr chroot 2 to the home directory of the .Dq ftp user. As a special case if the .Dq ftp user's home directory pathname contains the .Pa /./ separator, .Nm uses its left-hand side as the name of the directory to do .Xr chroot 2 to, and its right-hand side to change the current directory to afterwards. A typical example for this case would be .Pa /usr/local/ftp/./pub . In order that system security is not breached, it is recommended that the .Dq ftp subtree be constructed with care, following these rules: .Bl -tag -width "~ftp/pub" -offset indent .It Pa ~ftp Make the home directory owned by .Dq root and unwritable by anyone. .It Pa ~ftp/etc Make this directory owned by .Dq root and unwritable by anyone (mode 555). The files pwd.db (see .Xr passwd 5 ) and .Xr group 5 must be present for the .Xr ls 1 command to be able to produce owner names rather than numbers. The password field in .Xr passwd 5 is not used, and should not contain real passwords. The file .Pa ftpmotd , if present, will be printed after a successful login. These files should be mode 444. .It Pa ~ftp/pub This directory and the subdirectories beneath it should be owned by the users and groups responsible for placing files in them, and be writable only by them (mode 755 or 775). They should .Em not be owned or writable by .Dq ftp or its group, otherwise guest users can fill the drive with unwanted files. .El .Pp If the system has multiple IP addresses, .Nm supports the idea of virtual hosts, which provides the ability to define multiple anonymous ftp areas, each one allocated to a different internet address. The file .Pa /etc/ftphosts contains information pertaining to each of the virtual hosts. Each host is defined on its own line which contains a number of fields separated by whitespace: .Bl -tag -offset indent -width hostname .It hostname Contains the hostname or IP address of the virtual host. .It user Contains a user record in the system password file. As with normal anonymous ftp, this user's access uid, gid and group memberships determine file access to the anonymous ftp area. The anonymous ftp area (to which any user is chrooted on login) is determined by the home directory defined for the account. User id and group for any ftp account may be the same as for the standard ftp user. .It statfile File to which all file transfers are logged, which defaults to .Pa /var/log/ftpd . .It welcome This file is the welcome message displayed before the server ready prompt. It defaults to .Pa /etc/ftpwelcome . .It motd This file is displayed after the user logs in. It defaults to .Pa /etc/ftpmotd . .El .Pp Lines beginning with a '#' are ignored and can be used to include comments. .Pp Defining a virtual host for the primary IP address or hostname changes the default for ftp logins to that address. The 'user', 'statfile', 'welcome' and 'motd' fields may be left blank, or a single hyphen '-' used to indicate that the default value is to be used. .Pp As with any anonymous login configuration, due care must be given to setup and maintenance to guard against security related problems. .Pp The .Nm utility has internal support for handling remote requests to list files, and will not execute .Pa /bin/ls in either a chrooted or non-chrooted environment. The .Pa ~/bin/ls executable need not be placed into the chrooted tree, nor need the .Pa ~/bin directory exist. .Sh FILES .Bl -tag -width ".Pa /var/run/ftpd.pid" -compact .It Pa /etc/ftpusers List of unwelcome/restricted users. .It Pa /etc/ftpchroot List of normal users who should be chroot'd. .It Pa /etc/ftphosts Virtual hosting configuration file. .It Pa /etc/ftpwelcome Welcome notice. .It Pa /etc/ftpmotd Welcome notice after login. .It Pa /var/run/ftpd.pid Default pid file for daemon mode. .It Pa /var/run/nologin Displayed and access refused. .It Pa /var/log/ftpd Log file for anonymous transfers. .It Pa /var/log/xferlog Default place for session logs. .El .Sh SEE ALSO .Xr ftp 1 , .Xr umask 2 , .Xr getusershell 3 , .Xr opie 4 , .Xr ftpchroot 5 , .Xr login.conf 5 , .Xr inetd 8 , .Xr syslogd 8 .Sh HISTORY The .Nm utility appeared in .Bx 4.2 . IPv6 support was added in WIDE Hydrangea IPv6 stack kit. .Sh BUGS The server must run as the super-user to create sockets with privileged port numbers. It maintains an effective user id of the logged in user, reverting to the super-user only when binding addresses to sockets. The possible security holes have been extensively scrutinized, but are possibly incomplete. Index: head/libexec/ftpd/ftpd.c =================================================================== --- head/libexec/ftpd/ftpd.c (revision 262135) +++ head/libexec/ftpd/ftpd.c (revision 262136) @@ -1,3494 +1,3490 @@ /* * Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994 * The Regents of the University of California. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #if 0 #ifndef lint static char copyright[] = "@(#) Copyright (c) 1985, 1988, 1990, 1992, 1993, 1994\n\ The Regents of the University of California. All rights reserved.\n"; #endif /* not lint */ #endif #ifndef lint #if 0 static char sccsid[] = "@(#)ftpd.c 8.4 (Berkeley) 4/16/94"; #endif #endif /* not lint */ #include __FBSDID("$FreeBSD$"); /* * FTP server. */ #include #include #include #include #include #include #include #include #include #include #include #define FTP_NAMES #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifdef LOGIN_CAP #include #endif #ifdef USE_PAM #include #endif #include "pathnames.h" #include "extern.h" #include static char version[] = "Version 6.00LS"; #undef main union sockunion ctrl_addr; union sockunion data_source; union sockunion data_dest; union sockunion his_addr; union sockunion pasv_addr; int daemon_mode; int data; int dataport; int hostinfo = 1; /* print host-specific info in messages */ int logged_in; struct passwd *pw; char *homedir; int ftpdebug; int timeout = 900; /* timeout after 15 minutes of inactivity */ int maxtimeout = 7200;/* don't allow idle time to be set beyond 2 hours */ int logging; int restricted_data_ports = 1; int paranoid = 1; /* be extra careful about security */ int anon_only = 0; /* Only anonymous ftp allowed */ int assumeutf8 = 0; /* Assume that server file names are in UTF-8 */ int guest; int dochroot; char *chrootdir; int dowtmp = 1; int stats; int statfd = -1; int type; int form; int stru; /* avoid C keyword */ int mode; int usedefault = 1; /* for data transfers */ int pdata = -1; /* for passive mode */ int readonly = 0; /* Server is in readonly mode. */ int noepsv = 0; /* EPSV command is disabled. */ int noretr = 0; /* RETR command is disabled. */ int noguestretr = 0; /* RETR command is disabled for anon users. */ int noguestmkd = 0; /* MKD command is disabled for anon users. */ int noguestmod = 1; /* anon users may not modify existing files. */ off_t file_size; off_t byte_count; #if !defined(CMASK) || CMASK == 0 #undef CMASK #define CMASK 027 #endif int defumask = CMASK; /* default umask value */ char tmpline[7]; char *hostname; int epsvall = 0; #ifdef VIRTUAL_HOSTING char *ftpuser; static struct ftphost { struct ftphost *next; struct addrinfo *hostinfo; char *hostname; char *anonuser; char *statfile; char *welcome; char *loginmsg; } *thishost, *firsthost; #endif char remotehost[NI_MAXHOST]; char *ident = NULL; static char wtmpid[20]; #ifdef USE_PAM static int auth_pam(struct passwd**, const char*); pam_handle_t *pamh = NULL; #endif static struct opie opiedata; static char opieprompt[OPIE_CHALLENGE_MAX+1]; static int pwok; char *pid_file = NULL; /* means default location to pidfile(3) */ /* * Limit number of pathnames that glob can return. * A limit of 0 indicates the number of pathnames is unlimited. */ #define MAXGLOBARGS 16384 # /* * Timeout intervals for retrying connections * to hosts that don't accept PORT cmds. This * is a kludge, but given the problems with TCP... */ #define SWAITMAX 90 /* wait at most 90 seconds */ #define SWAITINT 5 /* interval between retries */ int swaitmax = SWAITMAX; int swaitint = SWAITINT; #ifdef SETPROCTITLE #ifdef OLD_SETPROCTITLE char **Argv = NULL; /* pointer to argument vector */ char *LastArgv = NULL; /* end of argv */ #endif /* OLD_SETPROCTITLE */ char proctitle[LINE_MAX]; /* initial part of title */ #endif /* SETPROCTITLE */ #define LOGCMD(cmd, file) logcmd((cmd), (file), NULL, -1) #define LOGCMD2(cmd, file1, file2) logcmd((cmd), (file1), (file2), -1) #define LOGBYTES(cmd, file, cnt) logcmd((cmd), (file), NULL, (cnt)) static volatile sig_atomic_t recvurg; static int transflag; /* NB: for debugging only */ #define STARTXFER flagxfer(1) #define ENDXFER flagxfer(0) #define START_UNSAFE maskurg(1) #define END_UNSAFE maskurg(0) /* It's OK to put an `else' clause after this macro. */ #define CHECKOOB(action) \ if (recvurg) { \ recvurg = 0; \ if (myoob()) { \ ENDXFER; \ action; \ } \ } #ifdef VIRTUAL_HOSTING static void inithosts(int); static void selecthost(union sockunion *); #endif static void ack(char *); static void sigurg(int); static void maskurg(int); static void flagxfer(int); static int myoob(void); static int checkuser(char *, char *, int, char **, int *); static FILE *dataconn(char *, off_t, char *); static void dolog(struct sockaddr *); static void end_login(void); static FILE *getdatasock(char *); static int guniquefd(char *, char **); static void lostconn(int); static void sigquit(int); static int receive_data(FILE *, FILE *); static int send_data(FILE *, FILE *, size_t, off_t, int); static struct passwd * sgetpwnam(char *); static char *sgetsave(char *); static void reapchild(int); static void appendf(char **, char *, ...) __printflike(2, 3); static void logcmd(char *, char *, char *, off_t); static void logxfer(char *, off_t, time_t); static char *doublequote(char *); static int *socksetup(int, char *, const char *); int main(int argc, char *argv[], char **envp) { socklen_t addrlen; int ch, on = 1, tos; char *cp, line[LINE_MAX]; FILE *fd; char *bindname = NULL; const char *bindport = "ftp"; int family = AF_UNSPEC; struct sigaction sa; tzset(); /* in case no timezone database in ~ftp */ sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART; #ifdef OLD_SETPROCTITLE /* * Save start and extent of argv for setproctitle. */ Argv = argv; while (*envp) envp++; LastArgv = envp[-1] + strlen(envp[-1]); #endif /* OLD_SETPROCTITLE */ /* * Prevent diagnostic messages from appearing on stderr. * We run as a daemon or from inetd; in both cases, there's * more reason in logging to syslog. */ (void) freopen(_PATH_DEVNULL, "w", stderr); opterr = 0; /* * LOG_NDELAY sets up the logging connection immediately, * necessary for anonymous ftp's that chroot and can't do it later. */ openlog("ftpd", LOG_PID | LOG_NDELAY, LOG_FTP); while ((ch = getopt(argc, argv, "468a:AdDEhlmMoOp:P:rRSt:T:u:UvW")) != -1) { switch (ch) { case '4': family = (family == AF_INET6) ? AF_UNSPEC : AF_INET; break; case '6': family = (family == AF_INET) ? AF_UNSPEC : AF_INET6; break; case '8': assumeutf8 = 1; break; case 'a': bindname = optarg; break; case 'A': anon_only = 1; break; case 'd': ftpdebug++; break; case 'D': daemon_mode++; break; case 'E': noepsv = 1; break; case 'h': hostinfo = 0; break; case 'l': logging++; /* > 1 == extra logging */ break; case 'm': noguestmod = 0; break; case 'M': noguestmkd = 1; break; case 'o': noretr = 1; break; case 'O': noguestretr = 1; break; case 'p': pid_file = optarg; break; case 'P': bindport = optarg; break; case 'r': readonly = 1; break; case 'R': paranoid = 0; break; case 'S': stats++; break; case 't': timeout = atoi(optarg); if (maxtimeout < timeout) maxtimeout = timeout; break; case 'T': maxtimeout = atoi(optarg); if (timeout > maxtimeout) timeout = maxtimeout; break; case 'u': { long val = 0; val = strtol(optarg, &optarg, 8); if (*optarg != '\0' || val < 0) syslog(LOG_WARNING, "bad value for -u"); else defumask = val; break; } case 'U': restricted_data_ports = 0; break; case 'v': ftpdebug++; break; case 'W': dowtmp = 0; break; default: syslog(LOG_WARNING, "unknown flag -%c ignored", optopt); break; } } if (daemon_mode) { int *ctl_sock, fd, maxfd = -1, nfds, i; fd_set defreadfds, readfds; pid_t pid; struct pidfh *pfh; if ((pfh = pidfile_open(pid_file, 0600, &pid)) == NULL) { if (errno == EEXIST) { syslog(LOG_ERR, "%s already running, pid %d", getprogname(), (int)pid); exit(1); } syslog(LOG_WARNING, "pidfile_open: %m"); } /* * Detach from parent. */ if (daemon(1, 1) < 0) { syslog(LOG_ERR, "failed to become a daemon"); exit(1); } if (pfh != NULL && pidfile_write(pfh) == -1) syslog(LOG_WARNING, "pidfile_write: %m"); sa.sa_handler = reapchild; (void)sigaction(SIGCHLD, &sa, NULL); #ifdef VIRTUAL_HOSTING inithosts(family); #endif /* * Open a socket, bind it to the FTP port, and start * listening. */ ctl_sock = socksetup(family, bindname, bindport); if (ctl_sock == NULL) exit(1); FD_ZERO(&defreadfds); for (i = 1; i <= *ctl_sock; i++) { FD_SET(ctl_sock[i], &defreadfds); if (listen(ctl_sock[i], 32) < 0) { syslog(LOG_ERR, "control listen: %m"); exit(1); } if (maxfd < ctl_sock[i]) maxfd = ctl_sock[i]; } /* * Loop forever accepting connection requests and forking off * children to handle them. */ while (1) { FD_COPY(&defreadfds, &readfds); nfds = select(maxfd + 1, &readfds, NULL, NULL, 0); if (nfds <= 0) { if (nfds < 0 && errno != EINTR) syslog(LOG_WARNING, "select: %m"); continue; } pid = -1; for (i = 1; i <= *ctl_sock; i++) if (FD_ISSET(ctl_sock[i], &readfds)) { addrlen = sizeof(his_addr); fd = accept(ctl_sock[i], (struct sockaddr *)&his_addr, &addrlen); if (fd == -1) { syslog(LOG_WARNING, "accept: %m"); continue; } switch (pid = fork()) { case 0: /* child */ (void) dup2(fd, 0); (void) dup2(fd, 1); (void) close(fd); for (i = 1; i <= *ctl_sock; i++) close(ctl_sock[i]); if (pfh != NULL) pidfile_close(pfh); goto gotchild; case -1: syslog(LOG_WARNING, "fork: %m"); /* FALLTHROUGH */ default: close(fd); } } } } else { addrlen = sizeof(his_addr); if (getpeername(0, (struct sockaddr *)&his_addr, &addrlen) < 0) { syslog(LOG_ERR, "getpeername (%s): %m",argv[0]); exit(1); } #ifdef VIRTUAL_HOSTING if (his_addr.su_family == AF_INET6 && IN6_IS_ADDR_V4MAPPED(&his_addr.su_sin6.sin6_addr)) family = AF_INET; else family = his_addr.su_family; inithosts(family); #endif } gotchild: sa.sa_handler = SIG_DFL; (void)sigaction(SIGCHLD, &sa, NULL); sa.sa_handler = sigurg; sa.sa_flags = 0; /* don't restart syscalls for SIGURG */ (void)sigaction(SIGURG, &sa, NULL); sigfillset(&sa.sa_mask); /* block all signals in handler */ sa.sa_flags = SA_RESTART; sa.sa_handler = sigquit; (void)sigaction(SIGHUP, &sa, NULL); (void)sigaction(SIGINT, &sa, NULL); (void)sigaction(SIGQUIT, &sa, NULL); (void)sigaction(SIGTERM, &sa, NULL); sa.sa_handler = lostconn; (void)sigaction(SIGPIPE, &sa, NULL); addrlen = sizeof(ctrl_addr); if (getsockname(0, (struct sockaddr *)&ctrl_addr, &addrlen) < 0) { syslog(LOG_ERR, "getsockname (%s): %m",argv[0]); exit(1); } dataport = ntohs(ctrl_addr.su_port) - 1; /* as per RFC 959 */ #ifdef VIRTUAL_HOSTING /* select our identity from virtual host table */ selecthost(&ctrl_addr); #endif #ifdef IP_TOS if (ctrl_addr.su_family == AF_INET) { tos = IPTOS_LOWDELAY; if (setsockopt(0, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0) syslog(LOG_WARNING, "control setsockopt (IP_TOS): %m"); } #endif /* * Disable Nagle on the control channel so that we don't have to wait * for peer's ACK before issuing our next reply. */ if (setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0) syslog(LOG_WARNING, "control setsockopt (TCP_NODELAY): %m"); data_source.su_port = htons(ntohs(ctrl_addr.su_port) - 1); (void)snprintf(wtmpid, sizeof(wtmpid), "%xftpd", getpid()); /* Try to handle urgent data inline */ #ifdef SO_OOBINLINE if (setsockopt(0, SOL_SOCKET, SO_OOBINLINE, &on, sizeof(on)) < 0) syslog(LOG_WARNING, "control setsockopt (SO_OOBINLINE): %m"); #endif #ifdef F_SETOWN if (fcntl(fileno(stdin), F_SETOWN, getpid()) == -1) syslog(LOG_ERR, "fcntl F_SETOWN: %m"); #endif dolog((struct sockaddr *)&his_addr); /* * Set up default state */ data = -1; type = TYPE_A; form = FORM_N; stru = STRU_F; mode = MODE_S; tmpline[0] = '\0'; /* If logins are disabled, print out the message. */ if ((fd = fopen(_PATH_NOLOGIN,"r")) != NULL) { while (fgets(line, sizeof(line), fd) != NULL) { if ((cp = strchr(line, '\n')) != NULL) *cp = '\0'; lreply(530, "%s", line); } (void) fflush(stdout); (void) fclose(fd); reply(530, "System not available."); exit(0); } #ifdef VIRTUAL_HOSTING fd = fopen(thishost->welcome, "r"); #else fd = fopen(_PATH_FTPWELCOME, "r"); #endif if (fd != NULL) { while (fgets(line, sizeof(line), fd) != NULL) { if ((cp = strchr(line, '\n')) != NULL) *cp = '\0'; lreply(220, "%s", line); } (void) fflush(stdout); (void) fclose(fd); /* reply(220,) must follow */ } #ifndef VIRTUAL_HOSTING if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL) fatalerror("Ran out of memory."); if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0) hostname[0] = '\0'; hostname[MAXHOSTNAMELEN - 1] = '\0'; #endif if (hostinfo) reply(220, "%s FTP server (%s) ready.", hostname, version); else reply(220, "FTP server ready."); for (;;) (void) yyparse(); /* NOTREACHED */ } static void lostconn(int signo) { if (ftpdebug) syslog(LOG_DEBUG, "lost connection"); dologout(1); } static void sigquit(int signo) { syslog(LOG_ERR, "got signal %d", signo); dologout(1); } #ifdef VIRTUAL_HOSTING /* * read in virtual host tables (if they exist) */ static void inithosts(int family) { int insert; size_t len; FILE *fp; char *cp, *mp, *line; char *hostname; char *vhost, *anonuser, *statfile, *welcome, *loginmsg; struct ftphost *hrp, *lhrp; struct addrinfo hints, *res, *ai; /* * Fill in the default host information */ if ((hostname = malloc(MAXHOSTNAMELEN)) == NULL) fatalerror("Ran out of memory."); if (gethostname(hostname, MAXHOSTNAMELEN - 1) < 0) hostname[0] = '\0'; hostname[MAXHOSTNAMELEN - 1] = '\0'; if ((hrp = malloc(sizeof(struct ftphost))) == NULL) fatalerror("Ran out of memory."); hrp->hostname = hostname; hrp->hostinfo = NULL; memset(&hints, 0, sizeof(hints)); hints.ai_flags = AI_PASSIVE; hints.ai_family = family; hints.ai_socktype = SOCK_STREAM; if (getaddrinfo(hrp->hostname, NULL, &hints, &res) == 0) hrp->hostinfo = res; hrp->statfile = _PATH_FTPDSTATFILE; hrp->welcome = _PATH_FTPWELCOME; hrp->loginmsg = _PATH_FTPLOGINMESG; hrp->anonuser = "ftp"; hrp->next = NULL; thishost = firsthost = lhrp = hrp; if ((fp = fopen(_PATH_FTPHOSTS, "r")) != NULL) { int addrsize, gothost; void *addr; struct hostent *hp; while ((line = fgetln(fp, &len)) != NULL) { int i, hp_error; /* skip comments */ if (line[0] == '#') continue; if (line[len - 1] == '\n') { line[len - 1] = '\0'; mp = NULL; } else { if ((mp = malloc(len + 1)) == NULL) fatalerror("Ran out of memory."); memcpy(mp, line, len); mp[len] = '\0'; line = mp; } cp = strtok(line, " \t"); /* skip empty lines */ if (cp == NULL) goto nextline; vhost = cp; /* set defaults */ anonuser = "ftp"; statfile = _PATH_FTPDSTATFILE; welcome = _PATH_FTPWELCOME; loginmsg = _PATH_FTPLOGINMESG; /* * Preparse the line so we can use its info * for all the addresses associated with * the virtual host name. * Field 0, the virtual host name, is special: * it's already parsed off and will be strdup'ed * later, after we know its canonical form. */ for (i = 1; i < 5 && (cp = strtok(NULL, " \t")); i++) if (*cp != '-' && (cp = strdup(cp))) switch (i) { case 1: /* anon user permissions */ anonuser = cp; break; case 2: /* statistics file */ statfile = cp; break; case 3: /* welcome message */ welcome = cp; break; case 4: /* login message */ loginmsg = cp; break; default: /* programming error */ abort(); /* NOTREACHED */ } hints.ai_flags = AI_PASSIVE; hints.ai_family = family; hints.ai_socktype = SOCK_STREAM; if (getaddrinfo(vhost, NULL, &hints, &res) != 0) goto nextline; for (ai = res; ai != NULL && ai->ai_addr != NULL; ai = ai->ai_next) { gothost = 0; for (hrp = firsthost; hrp != NULL; hrp = hrp->next) { struct addrinfo *hi; for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) if (hi->ai_addrlen == ai->ai_addrlen && memcmp(hi->ai_addr, ai->ai_addr, ai->ai_addr->sa_len) == 0) { gothost++; break; } if (gothost) break; } if (hrp == NULL) { if ((hrp = malloc(sizeof(struct ftphost))) == NULL) goto nextline; hrp->hostname = NULL; insert = 1; } else { if (hrp->hostinfo && hrp->hostinfo != res) freeaddrinfo(hrp->hostinfo); insert = 0; /* host already in the chain */ } hrp->hostinfo = res; /* * determine hostname to use. * force defined name if there is a valid alias * otherwise fallback to primary hostname */ /* XXX: getaddrinfo() can't do alias check */ switch(hrp->hostinfo->ai_family) { case AF_INET: addr = &((struct sockaddr_in *)hrp->hostinfo->ai_addr)->sin_addr; addrsize = sizeof(struct in_addr); break; case AF_INET6: addr = &((struct sockaddr_in6 *)hrp->hostinfo->ai_addr)->sin6_addr; addrsize = sizeof(struct in6_addr); break; default: /* should not reach here */ freeaddrinfo(hrp->hostinfo); if (insert) free(hrp); /*not in chain, can free*/ else hrp->hostinfo = NULL; /*mark as blank*/ goto nextline; /* NOTREACHED */ } if ((hp = getipnodebyaddr(addr, addrsize, hrp->hostinfo->ai_family, &hp_error)) != NULL) { if (strcmp(vhost, hp->h_name) != 0) { if (hp->h_aliases == NULL) vhost = hp->h_name; else { i = 0; while (hp->h_aliases[i] && strcmp(vhost, hp->h_aliases[i]) != 0) ++i; if (hp->h_aliases[i] == NULL) vhost = hp->h_name; } } } if (hrp->hostname && strcmp(hrp->hostname, vhost) != 0) { free(hrp->hostname); hrp->hostname = NULL; } if (hrp->hostname == NULL && (hrp->hostname = strdup(vhost)) == NULL) { freeaddrinfo(hrp->hostinfo); hrp->hostinfo = NULL; /* mark as blank */ if (hp) freehostent(hp); goto nextline; } hrp->anonuser = anonuser; hrp->statfile = statfile; hrp->welcome = welcome; hrp->loginmsg = loginmsg; if (insert) { hrp->next = NULL; lhrp->next = hrp; lhrp = hrp; } if (hp) freehostent(hp); } nextline: if (mp) free(mp); } (void) fclose(fp); } } static void selecthost(union sockunion *su) { struct ftphost *hrp; u_int16_t port; #ifdef INET6 struct in6_addr *mapped_in6 = NULL; #endif struct addrinfo *hi; #ifdef INET6 /* * XXX IPv4 mapped IPv6 addr consideraton, * specified in rfc2373. */ if (su->su_family == AF_INET6 && IN6_IS_ADDR_V4MAPPED(&su->su_sin6.sin6_addr)) mapped_in6 = &su->su_sin6.sin6_addr; #endif hrp = thishost = firsthost; /* default */ port = su->su_port; su->su_port = 0; while (hrp != NULL) { for (hi = hrp->hostinfo; hi != NULL; hi = hi->ai_next) { if (memcmp(su, hi->ai_addr, hi->ai_addrlen) == 0) { thishost = hrp; goto found; } #ifdef INET6 /* XXX IPv4 mapped IPv6 addr consideraton */ if (hi->ai_addr->sa_family == AF_INET && mapped_in6 != NULL && (memcmp(&mapped_in6->s6_addr[12], &((struct sockaddr_in *)hi->ai_addr)->sin_addr, sizeof(struct in_addr)) == 0)) { thishost = hrp; goto found; } #endif } hrp = hrp->next; } found: su->su_port = port; /* setup static variables as appropriate */ hostname = thishost->hostname; ftpuser = thishost->anonuser; } #endif /* * Helper function for sgetpwnam(). */ static char * sgetsave(char *s) { char *new = malloc(strlen(s) + 1); if (new == NULL) { reply(421, "Ran out of memory."); dologout(1); /* NOTREACHED */ } (void) strcpy(new, s); return (new); } /* * Save the result of a getpwnam. Used for USER command, since * the data returned must not be clobbered by any other command * (e.g., globbing). * NB: The data returned by sgetpwnam() will remain valid until * the next call to this function. Its difference from getpwnam() * is that sgetpwnam() is known to be called from ftpd code only. */ static struct passwd * sgetpwnam(char *name) { static struct passwd save; struct passwd *p; if ((p = getpwnam(name)) == NULL) return (p); if (save.pw_name) { free(save.pw_name); free(save.pw_passwd); free(save.pw_class); free(save.pw_gecos); free(save.pw_dir); free(save.pw_shell); } save = *p; save.pw_name = sgetsave(p->pw_name); save.pw_passwd = sgetsave(p->pw_passwd); save.pw_class = sgetsave(p->pw_class); save.pw_gecos = sgetsave(p->pw_gecos); save.pw_dir = sgetsave(p->pw_dir); save.pw_shell = sgetsave(p->pw_shell); return (&save); } static int login_attempts; /* number of failed login attempts */ static int askpasswd; /* had user command, ask for passwd */ static char curname[MAXLOGNAME]; /* current USER name */ /* * USER command. * Sets global passwd pointer pw if named account exists and is acceptable; * sets askpasswd if a PASS command is expected. If logged in previously, * need to reset state. If name is "ftp" or "anonymous", the name is not in * _PATH_FTPUSERS, and ftp account exists, set guest and pw, then just return. * If account doesn't exist, ask for passwd anyway. Otherwise, check user * requesting login privileges. Disallow anyone who does not have a standard * shell as returned by getusershell(). Disallow anyone mentioned in the file * _PATH_FTPUSERS to allow people such as root and uucp to be avoided. */ void user(char *name) { int ecode; char *cp, *shell; if (logged_in) { if (guest) { reply(530, "Can't change user from guest login."); return; } else if (dochroot) { reply(530, "Can't change user from chroot user."); return; } end_login(); } guest = 0; #ifdef VIRTUAL_HOSTING pw = sgetpwnam(thishost->anonuser); #else pw = sgetpwnam("ftp"); #endif if (strcmp(name, "ftp") == 0 || strcmp(name, "anonymous") == 0) { if (checkuser(_PATH_FTPUSERS, "ftp", 0, NULL, &ecode) || (ecode != 0 && ecode != ENOENT)) reply(530, "User %s access denied.", name); else if (checkuser(_PATH_FTPUSERS, "anonymous", 0, NULL, &ecode) || (ecode != 0 && ecode != ENOENT)) reply(530, "User %s access denied.", name); else if (pw != NULL) { guest = 1; askpasswd = 1; reply(331, "Guest login ok, send your email address as password."); } else reply(530, "User %s unknown.", name); if (!askpasswd && logging) syslog(LOG_NOTICE, "ANONYMOUS FTP LOGIN REFUSED FROM %s", remotehost); return; } if (anon_only != 0) { reply(530, "Sorry, only anonymous ftp allowed."); return; } if ((pw = sgetpwnam(name))) { if ((shell = pw->pw_shell) == NULL || *shell == 0) shell = _PATH_BSHELL; setusershell(); while ((cp = getusershell()) != NULL) if (strcmp(cp, shell) == 0) break; endusershell(); if (cp == NULL || (checkuser(_PATH_FTPUSERS, name, 1, NULL, &ecode) || (ecode != 0 && ecode != ENOENT))) { reply(530, "User %s access denied.", name); if (logging) syslog(LOG_NOTICE, "FTP LOGIN REFUSED FROM %s, %s", remotehost, name); pw = NULL; return; } } if (logging) strncpy(curname, name, sizeof(curname)-1); pwok = 0; #ifdef USE_PAM /* XXX Kluge! The conversation mechanism needs to be fixed. */ #endif if (opiechallenge(&opiedata, name, opieprompt) == 0) { pwok = (pw != NULL) && opieaccessfile(remotehost) && opiealways(pw->pw_dir); reply(331, "Response to %s %s for %s.", opieprompt, pwok ? "requested" : "required", name); } else { pwok = 1; reply(331, "Password required for %s.", name); } askpasswd = 1; /* * Delay before reading passwd after first failed * attempt to slow down passwd-guessing programs. */ if (login_attempts) sleep(login_attempts); } /* * Check if a user is in the file "fname", * return a pointer to a malloc'd string with the rest * of the matching line in "residue" if not NULL. */ static int checkuser(char *fname, char *name, int pwset, char **residue, int *ecode) { FILE *fd; int found = 0; size_t len; char *line, *mp, *p; if (ecode != NULL) *ecode = 0; if ((fd = fopen(fname, "r")) != NULL) { while (!found && (line = fgetln(fd, &len)) != NULL) { /* skip comments */ if (line[0] == '#') continue; if (line[len - 1] == '\n') { line[len - 1] = '\0'; mp = NULL; } else { if ((mp = malloc(len + 1)) == NULL) fatalerror("Ran out of memory."); memcpy(mp, line, len); mp[len] = '\0'; line = mp; } /* avoid possible leading and trailing whitespace */ p = strtok(line, " \t"); /* skip empty lines */ if (p == NULL) goto nextline; /* * if first chr is '@', check group membership */ if (p[0] == '@') { int i = 0; struct group *grp; if (p[1] == '\0') /* single @ matches anyone */ found = 1; else { if ((grp = getgrnam(p+1)) == NULL) goto nextline; /* * Check user's default group */ if (pwset && grp->gr_gid == pw->pw_gid) found = 1; /* * Check supplementary groups */ while (!found && grp->gr_mem[i]) found = strcmp(name, grp->gr_mem[i++]) == 0; } } /* * Otherwise, just check for username match */ else found = strcmp(p, name) == 0; /* * Save the rest of line to "residue" if matched */ if (found && residue) { if ((p = strtok(NULL, "")) != NULL) p += strspn(p, " \t"); if (p && *p) { if ((*residue = strdup(p)) == NULL) fatalerror("Ran out of memory."); } else *residue = NULL; } nextline: if (mp) free(mp); } (void) fclose(fd); } else if (ecode != NULL) *ecode = errno; return (found); } /* * Terminate login as previous user, if any, resetting state; * used when USER command is given or login fails. */ static void end_login(void) { #ifdef USE_PAM int e; #endif (void) seteuid(0); if (logged_in && dowtmp) ftpd_logwtmp(wtmpid, NULL, NULL); pw = NULL; #ifdef LOGIN_CAP setusercontext(NULL, getpwuid(0), 0, LOGIN_SETALL & ~(LOGIN_SETLOGIN | LOGIN_SETUSER | LOGIN_SETGROUP | LOGIN_SETPATH | LOGIN_SETENV)); #endif #ifdef USE_PAM if (pamh) { if ((e = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS) syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e)); if ((e = pam_close_session(pamh,0)) != PAM_SUCCESS) syslog(LOG_ERR, "pam_close_session: %s", pam_strerror(pamh, e)); if ((e = pam_end(pamh, e)) != PAM_SUCCESS) syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e)); pamh = NULL; } #endif logged_in = 0; guest = 0; dochroot = 0; } #ifdef USE_PAM /* * the following code is stolen from imap-uw PAM authentication module and * login.c */ #define COPY_STRING(s) (s ? strdup(s) : NULL) struct cred_t { const char *uname; /* user name */ const char *pass; /* password */ }; typedef struct cred_t cred_t; static int auth_conv(int num_msg, const struct pam_message **msg, struct pam_response **resp, void *appdata) { int i; cred_t *cred = (cred_t *) appdata; struct pam_response *reply; reply = calloc(num_msg, sizeof *reply); if (reply == NULL) return PAM_BUF_ERR; for (i = 0; i < num_msg; i++) { switch (msg[i]->msg_style) { case PAM_PROMPT_ECHO_ON: /* assume want user name */ reply[i].resp_retcode = PAM_SUCCESS; reply[i].resp = COPY_STRING(cred->uname); /* PAM frees resp. */ break; case PAM_PROMPT_ECHO_OFF: /* assume want password */ reply[i].resp_retcode = PAM_SUCCESS; reply[i].resp = COPY_STRING(cred->pass); /* PAM frees resp. */ break; case PAM_TEXT_INFO: case PAM_ERROR_MSG: reply[i].resp_retcode = PAM_SUCCESS; reply[i].resp = NULL; break; default: /* unknown message style */ free(reply); return PAM_CONV_ERR; } } *resp = reply; return PAM_SUCCESS; } /* * Attempt to authenticate the user using PAM. Returns 0 if the user is * authenticated, or 1 if not authenticated. If some sort of PAM system * error occurs (e.g., the "/etc/pam.conf" file is missing) then this * function returns -1. This can be used as an indication that we should * fall back to a different authentication mechanism. */ static int auth_pam(struct passwd **ppw, const char *pass) { const char *tmpl_user; const void *item; int rval; int e; cred_t auth_cred = { (*ppw)->pw_name, pass }; struct pam_conv conv = { &auth_conv, &auth_cred }; e = pam_start("ftpd", (*ppw)->pw_name, &conv, &pamh); if (e != PAM_SUCCESS) { /* * In OpenPAM, it's OK to pass NULL to pam_strerror() * if context creation has failed in the first place. */ syslog(LOG_ERR, "pam_start: %s", pam_strerror(NULL, e)); return -1; } e = pam_set_item(pamh, PAM_RHOST, remotehost); if (e != PAM_SUCCESS) { syslog(LOG_ERR, "pam_set_item(PAM_RHOST): %s", pam_strerror(pamh, e)); if ((e = pam_end(pamh, e)) != PAM_SUCCESS) { syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e)); } pamh = NULL; return -1; } e = pam_authenticate(pamh, 0); switch (e) { case PAM_SUCCESS: /* * With PAM we support the concept of a "template" * user. The user enters a login name which is * authenticated by PAM, usually via a remote service * such as RADIUS or TACACS+. If authentication * succeeds, a different but related "template" name * is used for setting the credentials, shell, and * home directory. The name the user enters need only * exist on the remote authentication server, but the * template name must be present in the local password * database. * * This is supported by two various mechanisms in the * individual modules. However, from the application's * point of view, the template user is always passed * back as a changed value of the PAM_USER item. */ if ((e = pam_get_item(pamh, PAM_USER, &item)) == PAM_SUCCESS) { tmpl_user = (const char *) item; if (strcmp((*ppw)->pw_name, tmpl_user) != 0) *ppw = getpwnam(tmpl_user); } else syslog(LOG_ERR, "Couldn't get PAM_USER: %s", pam_strerror(pamh, e)); rval = 0; break; case PAM_AUTH_ERR: case PAM_USER_UNKNOWN: case PAM_MAXTRIES: rval = 1; break; default: syslog(LOG_ERR, "pam_authenticate: %s", pam_strerror(pamh, e)); rval = -1; break; } if (rval == 0) { e = pam_acct_mgmt(pamh, 0); if (e != PAM_SUCCESS) { syslog(LOG_ERR, "pam_acct_mgmt: %s", pam_strerror(pamh, e)); rval = 1; } } if (rval != 0) { if ((e = pam_end(pamh, e)) != PAM_SUCCESS) { syslog(LOG_ERR, "pam_end: %s", pam_strerror(pamh, e)); } pamh = NULL; } return rval; } #endif /* USE_PAM */ void pass(char *passwd) { int rval, ecode; FILE *fd; #ifdef LOGIN_CAP login_cap_t *lc = NULL; #endif #ifdef USE_PAM int e; #endif char *residue = NULL; char *xpasswd; if (logged_in || askpasswd == 0) { reply(503, "Login with USER first."); return; } askpasswd = 0; if (!guest) { /* "ftp" is only account allowed no password */ if (pw == NULL) { rval = 1; /* failure below */ goto skip; } #ifdef USE_PAM rval = auth_pam(&pw, passwd); if (rval >= 0) { opieunlock(); goto skip; } #endif if (opieverify(&opiedata, passwd) == 0) xpasswd = pw->pw_passwd; else if (pwok) { xpasswd = crypt(passwd, pw->pw_passwd); if (passwd[0] == '\0' && pw->pw_passwd[0] != '\0') xpasswd = ":"; } else { rval = 1; goto skip; } rval = strcmp(pw->pw_passwd, xpasswd); if (pw->pw_expire && time(NULL) >= pw->pw_expire) rval = 1; /* failure */ skip: /* * If rval == 1, the user failed the authentication check * above. If rval == 0, either PAM or local authentication * succeeded. */ if (rval) { reply(530, "Login incorrect."); if (logging) { syslog(LOG_NOTICE, "FTP LOGIN FAILED FROM %s", remotehost); syslog(LOG_AUTHPRIV | LOG_NOTICE, "FTP LOGIN FAILED FROM %s, %s", remotehost, curname); } pw = NULL; if (login_attempts++ >= 5) { syslog(LOG_NOTICE, "repeated login failures from %s", remotehost); exit(0); } return; } } login_attempts = 0; /* this time successful */ if (setegid(pw->pw_gid) < 0) { reply(550, "Can't set gid."); return; } /* May be overridden by login.conf */ (void) umask(defumask); #ifdef LOGIN_CAP if ((lc = login_getpwclass(pw)) != NULL) { char remote_ip[NI_MAXHOST]; if (getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len, remote_ip, sizeof(remote_ip) - 1, NULL, 0, NI_NUMERICHOST)) *remote_ip = 0; remote_ip[sizeof(remote_ip) - 1] = 0; if (!auth_hostok(lc, remotehost, remote_ip)) { syslog(LOG_INFO|LOG_AUTH, "FTP LOGIN FAILED (HOST) as %s: permission denied.", pw->pw_name); reply(530, "Permission denied."); pw = NULL; return; } if (!auth_timeok(lc, time(NULL))) { reply(530, "Login not available right now."); pw = NULL; return; } } setusercontext(lc, pw, 0, LOGIN_SETALL & ~(LOGIN_SETUSER | LOGIN_SETPATH | LOGIN_SETENV)); #else setlogin(pw->pw_name); (void) initgroups(pw->pw_name, pw->pw_gid); #endif #ifdef USE_PAM if (pamh) { if ((e = pam_open_session(pamh, 0)) != PAM_SUCCESS) { syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, e)); } else if ((e = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) { syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, e)); } } #endif dochroot = checkuser(_PATH_FTPCHROOT, pw->pw_name, 1, &residue, &ecode) #ifdef LOGIN_CAP /* Allow login.conf configuration as well */ || login_getcapbool(lc, "ftp-chroot", 0) #endif ; /* * It is possible that checkuser() failed to open the chroot file. * If this is the case, report that logins are un-available, since we * have no way of checking whether or not the user should be chrooted. * We ignore ENOENT since it is not required that this file be present. */ if (ecode != 0 && ecode != ENOENT) { reply(530, "Login not available right now."); return; } chrootdir = NULL; /* Disable wtmp logging when chrooting. */ if (dochroot || guest) dowtmp = 0; if (dowtmp) ftpd_logwtmp(wtmpid, pw->pw_name, (struct sockaddr *)&his_addr); logged_in = 1; if (guest && stats && statfd < 0) #ifdef VIRTUAL_HOSTING statfd = open(thishost->statfile, O_WRONLY|O_APPEND); #else statfd = open(_PATH_FTPDSTATFILE, O_WRONLY|O_APPEND); #endif if (statfd < 0) stats = 0; /* * For a chrooted local user, * a) see whether ftpchroot(5) specifies a chroot directory, * b) extract the directory pathname from the line, * c) expand it to the absolute pathname if necessary. */ if (dochroot && residue && (chrootdir = strtok(residue, " \t")) != NULL) { if (chrootdir[0] != '/') asprintf(&chrootdir, "%s/%s", pw->pw_dir, chrootdir); else chrootdir = strdup(chrootdir); /* make it permanent */ if (chrootdir == NULL) fatalerror("Ran out of memory."); } if (guest || dochroot) { /* * If no chroot directory set yet, use the login directory. * Copy it so it can be modified while pw->pw_dir stays intact. */ if (chrootdir == NULL && (chrootdir = strdup(pw->pw_dir)) == NULL) fatalerror("Ran out of memory."); /* * Check for the "/chroot/./home" syntax, * separate the chroot and home directory pathnames. */ if ((homedir = strstr(chrootdir, "/./")) != NULL) { *(homedir++) = '\0'; /* wipe '/' */ homedir++; /* skip '.' */ } else { /* * We MUST do a chdir() after the chroot. Otherwise * the old current directory will be accessible as "." * outside the new root! */ homedir = "/"; } /* * Finally, do chroot() */ if (chroot(chrootdir) < 0) { reply(550, "Can't change root."); goto bad; } __FreeBSD_libc_enter_restricted_mode(); } else /* real user w/o chroot */ homedir = pw->pw_dir; /* * Set euid *before* doing chdir() so * a) the user won't be carried to a directory that he couldn't reach * on his own due to no permission to upper path components, * b) NFS mounted homedirs w/restrictive permissions will be accessible * (uid 0 has no root power over NFS if not mapped explicitly.) */ if (seteuid(pw->pw_uid) < 0) { reply(550, "Can't set uid."); goto bad; } if (chdir(homedir) < 0) { if (guest || dochroot) { reply(550, "Can't change to base directory."); goto bad; } else { if (chdir("/") < 0) { reply(550, "Root is inaccessible."); goto bad; } lreply(230, "No directory! Logging in with home=/."); } } /* * Display a login message, if it exists. * N.B. reply(230,) must follow the message. */ #ifdef VIRTUAL_HOSTING fd = fopen(thishost->loginmsg, "r"); #else fd = fopen(_PATH_FTPLOGINMESG, "r"); #endif if (fd != NULL) { char *cp, line[LINE_MAX]; while (fgets(line, sizeof(line), fd) != NULL) { if ((cp = strchr(line, '\n')) != NULL) *cp = '\0'; lreply(230, "%s", line); } (void) fflush(stdout); (void) fclose(fd); } if (guest) { if (ident != NULL) free(ident); ident = strdup(passwd); if (ident == NULL) fatalerror("Ran out of memory."); reply(230, "Guest login ok, access restrictions apply."); #ifdef SETPROCTITLE #ifdef VIRTUAL_HOSTING if (thishost != firsthost) snprintf(proctitle, sizeof(proctitle), "%s: anonymous(%s)/%s", remotehost, hostname, passwd); else #endif snprintf(proctitle, sizeof(proctitle), "%s: anonymous/%s", remotehost, passwd); setproctitle("%s", proctitle); #endif /* SETPROCTITLE */ if (logging) syslog(LOG_INFO, "ANONYMOUS FTP LOGIN FROM %s, %s", remotehost, passwd); } else { if (dochroot) reply(230, "User %s logged in, " "access restrictions apply.", pw->pw_name); else reply(230, "User %s logged in.", pw->pw_name); #ifdef SETPROCTITLE snprintf(proctitle, sizeof(proctitle), "%s: user/%s", remotehost, pw->pw_name); setproctitle("%s", proctitle); #endif /* SETPROCTITLE */ if (logging) syslog(LOG_INFO, "FTP LOGIN FROM %s as %s", remotehost, pw->pw_name); } if (logging && (guest || dochroot)) syslog(LOG_INFO, "session root changed to %s", chrootdir); #ifdef LOGIN_CAP login_close(lc); #endif if (residue) free(residue); return; bad: /* Forget all about it... */ #ifdef LOGIN_CAP login_close(lc); #endif if (residue) free(residue); end_login(); } void retrieve(char *cmd, char *name) { FILE *fin, *dout; struct stat st; int (*closefunc)(FILE *); time_t start; if (cmd == 0) { fin = fopen(name, "r"), closefunc = fclose; st.st_size = 0; } else { char line[BUFSIZ]; (void) snprintf(line, sizeof(line), cmd, name), name = line; fin = ftpd_popen(line, "r"), closefunc = ftpd_pclose; st.st_size = -1; st.st_blksize = BUFSIZ; } if (fin == NULL) { if (errno != 0) { perror_reply(550, name); if (cmd == 0) { LOGCMD("get", name); } } return; } byte_count = -1; if (cmd == 0) { if (fstat(fileno(fin), &st) < 0) { perror_reply(550, name); goto done; } if (!S_ISREG(st.st_mode)) { /* * Never sending a raw directory is a workaround * for buggy clients that will attempt to RETR * a directory before listing it, e.g., Mozilla. * Preventing a guest from getting irregular files * is a simple security measure. */ if (S_ISDIR(st.st_mode) || guest) { reply(550, "%s: not a plain file.", name); goto done; } st.st_size = -1; /* st.st_blksize is set for all descriptor types */ } } if (restart_point) { if (type == TYPE_A) { off_t i, n; int c; n = restart_point; i = 0; while (i++ < n) { if ((c=getc(fin)) == EOF) { perror_reply(550, name); goto done; } if (c == '\n') i++; } } else if (lseek(fileno(fin), restart_point, L_SET) < 0) { perror_reply(550, name); goto done; } } dout = dataconn(name, st.st_size, "w"); if (dout == NULL) goto done; time(&start); send_data(fin, dout, st.st_blksize, st.st_size, restart_point == 0 && cmd == 0 && S_ISREG(st.st_mode)); if (cmd == 0 && guest && stats && byte_count > 0) logxfer(name, byte_count, start); (void) fclose(dout); data = -1; pdata = -1; done: if (cmd == 0) LOGBYTES("get", name, byte_count); (*closefunc)(fin); } void store(char *name, char *mode, int unique) { int fd; FILE *fout, *din; int (*closefunc)(FILE *); if (*mode == 'a') { /* APPE */ if (unique) { /* Programming error */ syslog(LOG_ERR, "Internal: unique flag to APPE"); unique = 0; } if (guest && noguestmod) { reply(550, "Appending to existing file denied."); goto err; } restart_point = 0; /* not affected by preceding REST */ } if (unique) /* STOU overrides REST */ restart_point = 0; if (guest && noguestmod) { if (restart_point) { /* guest STOR w/REST */ reply(550, "Modifying existing file denied."); goto err; } else /* treat guest STOR as STOU */ unique = 1; } if (restart_point) mode = "r+"; /* so ASCII manual seek can work */ if (unique) { if ((fd = guniquefd(name, &name)) < 0) goto err; fout = fdopen(fd, mode); } else fout = fopen(name, mode); closefunc = fclose; if (fout == NULL) { perror_reply(553, name); goto err; } byte_count = -1; if (restart_point) { if (type == TYPE_A) { off_t i, n; int c; n = restart_point; i = 0; while (i++ < n) { if ((c=getc(fout)) == EOF) { perror_reply(550, name); goto done; } if (c == '\n') i++; } /* * We must do this seek to "current" position * because we are changing from reading to * writing. */ if (fseeko(fout, 0, SEEK_CUR) < 0) { perror_reply(550, name); goto done; } } else if (lseek(fileno(fout), restart_point, L_SET) < 0) { perror_reply(550, name); goto done; } } din = dataconn(name, -1, "r"); if (din == NULL) goto done; if (receive_data(din, fout) == 0) { if (unique) reply(226, "Transfer complete (unique file name:%s).", name); else reply(226, "Transfer complete."); } (void) fclose(din); data = -1; pdata = -1; done: LOGBYTES(*mode == 'a' ? "append" : "put", name, byte_count); (*closefunc)(fout); return; err: LOGCMD(*mode == 'a' ? "append" : "put" , name); return; } static FILE * getdatasock(char *mode) { int on = 1, s, t, tries; if (data >= 0) return (fdopen(data, mode)); s = socket(data_dest.su_family, SOCK_STREAM, 0); if (s < 0) goto bad; if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) syslog(LOG_WARNING, "data setsockopt (SO_REUSEADDR): %m"); /* anchor socket to avoid multi-homing problems */ data_source = ctrl_addr; data_source.su_port = htons(dataport); (void) seteuid(0); for (tries = 1; ; tries++) { /* * We should loop here since it's possible that * another ftpd instance has passed this point and is * trying to open a data connection in active mode now. * Until the other connection is opened, we'll be getting * EADDRINUSE because no SOCK_STREAM sockets in the system * can share both local and remote addresses, localIP:20 * and *:* in this case. */ if (bind(s, (struct sockaddr *)&data_source, data_source.su_len) >= 0) break; if (errno != EADDRINUSE || tries > 10) goto bad; sleep(tries); } (void) seteuid(pw->pw_uid); #ifdef IP_TOS if (data_source.su_family == AF_INET) { on = IPTOS_THROUGHPUT; if (setsockopt(s, IPPROTO_IP, IP_TOS, &on, sizeof(int)) < 0) syslog(LOG_WARNING, "data setsockopt (IP_TOS): %m"); } #endif #ifdef TCP_NOPUSH /* * Turn off push flag to keep sender TCP from sending short packets * at the boundaries of each write(). */ on = 1; if (setsockopt(s, IPPROTO_TCP, TCP_NOPUSH, &on, sizeof on) < 0) syslog(LOG_WARNING, "data setsockopt (TCP_NOPUSH): %m"); #endif return (fdopen(s, mode)); bad: /* Return the real value of errno (close may change it) */ t = errno; (void) seteuid(pw->pw_uid); (void) close(s); errno = t; return (NULL); } static FILE * dataconn(char *name, off_t size, char *mode) { char sizebuf[32]; FILE *file; int retry = 0, tos, conerrno; file_size = size; byte_count = 0; if (size != -1) (void) snprintf(sizebuf, sizeof(sizebuf), " (%jd bytes)", (intmax_t)size); else *sizebuf = '\0'; if (pdata >= 0) { union sockunion from; socklen_t fromlen = ctrl_addr.su_len; int flags, s; struct timeval timeout; fd_set set; FD_ZERO(&set); FD_SET(pdata, &set); timeout.tv_usec = 0; timeout.tv_sec = 120; /* * Granted a socket is in the blocking I/O mode, * accept() will block after a successful select() * if the selected connection dies in between. * Therefore set the non-blocking I/O flag here. */ if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 || fcntl(pdata, F_SETFL, flags | O_NONBLOCK) == -1) goto pdata_err; if (select(pdata+1, &set, NULL, NULL, &timeout) <= 0 || (s = accept(pdata, (struct sockaddr *) &from, &fromlen)) < 0) goto pdata_err; (void) close(pdata); pdata = s; /* * Unset the inherited non-blocking I/O flag * on the child socket so stdio can work on it. */ if ((flags = fcntl(pdata, F_GETFL, 0)) == -1 || fcntl(pdata, F_SETFL, flags & ~O_NONBLOCK) == -1) goto pdata_err; #ifdef IP_TOS if (from.su_family == AF_INET) { tos = IPTOS_THROUGHPUT; if (setsockopt(s, IPPROTO_IP, IP_TOS, &tos, sizeof(int)) < 0) syslog(LOG_WARNING, "pdata setsockopt (IP_TOS): %m"); } #endif reply(150, "Opening %s mode data connection for '%s'%s.", type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf); return (fdopen(pdata, mode)); pdata_err: reply(425, "Can't open data connection."); (void) close(pdata); pdata = -1; return (NULL); } if (data >= 0) { reply(125, "Using existing data connection for '%s'%s.", name, sizebuf); usedefault = 1; return (fdopen(data, mode)); } if (usedefault) data_dest = his_addr; usedefault = 1; do { file = getdatasock(mode); if (file == NULL) { char hostbuf[NI_MAXHOST], portbuf[NI_MAXSERV]; if (getnameinfo((struct sockaddr *)&data_source, data_source.su_len, hostbuf, sizeof(hostbuf) - 1, portbuf, sizeof(portbuf) - 1, NI_NUMERICHOST|NI_NUMERICSERV)) *hostbuf = *portbuf = 0; hostbuf[sizeof(hostbuf) - 1] = 0; portbuf[sizeof(portbuf) - 1] = 0; reply(425, "Can't create data socket (%s,%s): %s.", hostbuf, portbuf, strerror(errno)); return (NULL); } data = fileno(file); conerrno = 0; if (connect(data, (struct sockaddr *)&data_dest, data_dest.su_len) == 0) break; conerrno = errno; (void) fclose(file); data = -1; if (conerrno == EADDRINUSE) { sleep(swaitint); retry += swaitint; } else { break; } } while (retry <= swaitmax); if (conerrno != 0) { reply(425, "Can't build data connection: %s.", strerror(conerrno)); return (NULL); } reply(150, "Opening %s mode data connection for '%s'%s.", type == TYPE_A ? "ASCII" : "BINARY", name, sizebuf); return (file); } /* * A helper macro to avoid code duplication * in send_data() and receive_data(). * * XXX We have to block SIGURG during putc() because BSD stdio * is unable to restart interrupted write operations and hence * the entire buffer contents will be lost as soon as a write() * call indicates EINTR to stdio. */ #define FTPD_PUTC(ch, file, label) \ do { \ int ret; \ \ do { \ START_UNSAFE; \ ret = putc((ch), (file)); \ END_UNSAFE; \ CHECKOOB(return (-1)) \ else if (ferror(file)) \ goto label; \ clearerr(file); \ } while (ret == EOF); \ } while (0) /* * Tranfer the contents of "instr" to "outstr" peer using the appropriate * encapsulation of the data subject to Mode, Structure, and Type. * * NB: Form isn't handled. */ static int send_data(FILE *instr, FILE *outstr, size_t blksize, off_t filesize, int isreg) { int c, cp, filefd, netfd; char *buf; STARTXFER; switch (type) { case TYPE_A: cp = EOF; for (;;) { c = getc(instr); CHECKOOB(return (-1)) else if (c == EOF && ferror(instr)) goto file_err; if (c == EOF) { if (ferror(instr)) { /* resume after OOB */ clearerr(instr); continue; } if (feof(instr)) /* EOF */ break; syslog(LOG_ERR, "Internal: impossible condition" " on file after getc()"); goto file_err; } if (c == '\n' && cp != '\r') { FTPD_PUTC('\r', outstr, data_err); byte_count++; } FTPD_PUTC(c, outstr, data_err); byte_count++; cp = c; } #ifdef notyet /* BSD stdio isn't ready for that */ while (fflush(outstr) == EOF) { CHECKOOB(return (-1)) else goto data_err; clearerr(outstr); } ENDXFER; #else ENDXFER; if (fflush(outstr) == EOF) goto data_err; #endif reply(226, "Transfer complete."); return (0); case TYPE_I: case TYPE_L: /* * isreg is only set if we are not doing restart and we * are sending a regular file */ netfd = fileno(outstr); filefd = fileno(instr); if (isreg) { char *msg = "Transfer complete."; off_t cnt, offset; int err; cnt = offset = 0; while (filesize > 0) { err = sendfile(filefd, netfd, offset, 0, NULL, &cnt, 0); /* * Calculate byte_count before OOB processing. * It can be used in myoob() later. */ byte_count += cnt; offset += cnt; filesize -= cnt; CHECKOOB(return (-1)) else if (err == -1) { if (errno != EINTR && cnt == 0 && offset == 0) goto oldway; goto data_err; } if (err == -1) /* resume after OOB */ continue; /* * We hit the EOF prematurely. * Perhaps the file was externally truncated. */ if (cnt == 0) { msg = "Transfer finished due to " "premature end of file."; break; } } ENDXFER; reply(226, "%s", msg); return (0); } oldway: if ((buf = malloc(blksize)) == NULL) { ENDXFER; reply(451, "Ran out of memory."); return (-1); } for (;;) { int cnt, len; char *bp; cnt = read(filefd, buf, blksize); CHECKOOB(free(buf); return (-1)) else if (cnt < 0) { free(buf); goto file_err; } if (cnt < 0) /* resume after OOB */ continue; if (cnt == 0) /* EOF */ break; for (len = cnt, bp = buf; len > 0;) { cnt = write(netfd, bp, len); CHECKOOB(free(buf); return (-1)) else if (cnt < 0) { free(buf); goto data_err; } if (cnt <= 0) continue; len -= cnt; bp += cnt; byte_count += cnt; } } ENDXFER; free(buf); reply(226, "Transfer complete."); return (0); default: ENDXFER; reply(550, "Unimplemented TYPE %d in send_data.", type); return (-1); } data_err: ENDXFER; perror_reply(426, "Data connection"); return (-1); file_err: ENDXFER; perror_reply(551, "Error on input file"); return (-1); } /* * Transfer data from peer to "outstr" using the appropriate encapulation of * the data subject to Mode, Structure, and Type. * * N.B.: Form isn't handled. */ static int receive_data(FILE *instr, FILE *outstr) { int c, cp; int bare_lfs = 0; STARTXFER; switch (type) { case TYPE_I: case TYPE_L: for (;;) { int cnt, len; char *bp; char buf[BUFSIZ]; cnt = read(fileno(instr), buf, sizeof(buf)); CHECKOOB(return (-1)) else if (cnt < 0) goto data_err; if (cnt < 0) /* resume after OOB */ continue; if (cnt == 0) /* EOF */ break; for (len = cnt, bp = buf; len > 0;) { cnt = write(fileno(outstr), bp, len); CHECKOOB(return (-1)) else if (cnt < 0) goto file_err; if (cnt <= 0) continue; len -= cnt; bp += cnt; byte_count += cnt; } } ENDXFER; return (0); case TYPE_E: ENDXFER; reply(553, "TYPE E not implemented."); return (-1); case TYPE_A: cp = EOF; for (;;) { c = getc(instr); CHECKOOB(return (-1)) else if (c == EOF && ferror(instr)) goto data_err; if (c == EOF && ferror(instr)) { /* resume after OOB */ clearerr(instr); continue; } if (cp == '\r') { if (c != '\n') FTPD_PUTC('\r', outstr, file_err); } else if (c == '\n') bare_lfs++; if (c == '\r') { byte_count++; cp = c; continue; } /* Check for EOF here in order not to lose last \r. */ if (c == EOF) { if (feof(instr)) /* EOF */ break; syslog(LOG_ERR, "Internal: impossible condition" " on data stream after getc()"); goto data_err; } byte_count++; FTPD_PUTC(c, outstr, file_err); cp = c; } #ifdef notyet /* BSD stdio isn't ready for that */ while (fflush(outstr) == EOF) { CHECKOOB(return (-1)) else goto file_err; clearerr(outstr); } ENDXFER; #else ENDXFER; if (fflush(outstr) == EOF) goto file_err; #endif if (bare_lfs) { lreply(226, "WARNING! %d bare linefeeds received in ASCII mode.", bare_lfs); (void)printf(" File may not have transferred correctly.\r\n"); } return (0); default: ENDXFER; reply(550, "Unimplemented TYPE %d in receive_data.", type); return (-1); } data_err: ENDXFER; perror_reply(426, "Data connection"); return (-1); file_err: ENDXFER; perror_reply(452, "Error writing to file"); return (-1); } void statfilecmd(char *filename) { FILE *fin; int atstart; int c, code; char line[LINE_MAX]; struct stat st; code = lstat(filename, &st) == 0 && S_ISDIR(st.st_mode) ? 212 : 213; (void)snprintf(line, sizeof(line), _PATH_LS " -lgA %s", filename); fin = ftpd_popen(line, "r"); if (fin == NULL) { perror_reply(551, filename); return; } lreply(code, "Status of %s:", filename); atstart = 1; while ((c = getc(fin)) != EOF) { if (c == '\n') { if (ferror(stdout)){ perror_reply(421, "Control connection"); (void) ftpd_pclose(fin); dologout(1); /* NOTREACHED */ } if (ferror(fin)) { perror_reply(551, filename); (void) ftpd_pclose(fin); return; } (void) putc('\r', stdout); } /* * RFC 959 says neutral text should be prepended before * a leading 3-digit number followed by whitespace, but * many ftp clients can be confused by any leading digits, * as a matter of fact. */ if (atstart && isdigit(c)) (void) putc(' ', stdout); (void) putc(c, stdout); atstart = (c == '\n'); } (void) ftpd_pclose(fin); reply(code, "End of status."); } void statcmd(void) { union sockunion *su; u_char *a, *p; char hname[NI_MAXHOST]; int ispassive; if (hostinfo) { lreply(211, "%s FTP server status:", hostname); printf(" %s\r\n", version); } else lreply(211, "FTP server status:"); printf(" Connected to %s", remotehost); if (!getnameinfo((struct sockaddr *)&his_addr, his_addr.su_len, hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) { hname[sizeof(hname) - 1] = 0; if (strcmp(hname, remotehost) != 0) printf(" (%s)", hname); } printf("\r\n"); if (logged_in) { if (guest) printf(" Logged in anonymously\r\n"); else printf(" Logged in as %s\r\n", pw->pw_name); } else if (askpasswd) printf(" Waiting for password\r\n"); else printf(" Waiting for user name\r\n"); printf(" TYPE: %s", typenames[type]); if (type == TYPE_A || type == TYPE_E) printf(", FORM: %s", formnames[form]); if (type == TYPE_L) #if CHAR_BIT == 8 printf(" %d", CHAR_BIT); #else printf(" %d", bytesize); /* need definition! */ #endif printf("; STRUcture: %s; transfer MODE: %s\r\n", strunames[stru], modenames[mode]); if (data != -1) printf(" Data connection open\r\n"); else if (pdata != -1) { ispassive = 1; su = &pasv_addr; goto printaddr; } else if (usedefault == 0) { ispassive = 0; su = &data_dest; printaddr: #define UC(b) (((int) b) & 0xff) if (epsvall) { printf(" EPSV only mode (EPSV ALL)\r\n"); goto epsvonly; } /* PORT/PASV */ if (su->su_family == AF_INET) { a = (u_char *) &su->su_sin.sin_addr; p = (u_char *) &su->su_sin.sin_port; printf(" %s (%d,%d,%d,%d,%d,%d)\r\n", ispassive ? "PASV" : "PORT", UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1])); } /* LPRT/LPSV */ { int alen, af, i; switch (su->su_family) { case AF_INET: a = (u_char *) &su->su_sin.sin_addr; p = (u_char *) &su->su_sin.sin_port; alen = sizeof(su->su_sin.sin_addr); af = 4; break; case AF_INET6: a = (u_char *) &su->su_sin6.sin6_addr; p = (u_char *) &su->su_sin6.sin6_port; alen = sizeof(su->su_sin6.sin6_addr); af = 6; break; default: af = 0; break; } if (af) { printf(" %s (%d,%d,", ispassive ? "LPSV" : "LPRT", af, alen); for (i = 0; i < alen; i++) printf("%d,", UC(a[i])); printf("%d,%d,%d)\r\n", 2, UC(p[0]), UC(p[1])); } } epsvonly:; /* EPRT/EPSV */ { int af; switch (su->su_family) { case AF_INET: af = 1; break; case AF_INET6: af = 2; break; default: af = 0; break; } if (af) { union sockunion tmp; tmp = *su; if (tmp.su_family == AF_INET6) tmp.su_sin6.sin6_scope_id = 0; if (!getnameinfo((struct sockaddr *)&tmp, tmp.su_len, hname, sizeof(hname) - 1, NULL, 0, NI_NUMERICHOST)) { hname[sizeof(hname) - 1] = 0; printf(" %s |%d|%s|%d|\r\n", ispassive ? "EPSV" : "EPRT", af, hname, htons(tmp.su_port)); } } } #undef UC } else printf(" No data connection\r\n"); reply(211, "End of status."); } void fatalerror(char *s) { reply(451, "Error in server: %s", s); reply(221, "Closing connection due to server error."); dologout(0); /* NOTREACHED */ } void reply(int n, const char *fmt, ...) { va_list ap; (void)printf("%d ", n); va_start(ap, fmt); (void)vprintf(fmt, ap); va_end(ap); (void)printf("\r\n"); (void)fflush(stdout); if (ftpdebug) { syslog(LOG_DEBUG, "<--- %d ", n); va_start(ap, fmt); vsyslog(LOG_DEBUG, fmt, ap); va_end(ap); } } void lreply(int n, const char *fmt, ...) { va_list ap; (void)printf("%d- ", n); va_start(ap, fmt); (void)vprintf(fmt, ap); va_end(ap); (void)printf("\r\n"); (void)fflush(stdout); if (ftpdebug) { syslog(LOG_DEBUG, "<--- %d- ", n); va_start(ap, fmt); vsyslog(LOG_DEBUG, fmt, ap); va_end(ap); } } static void ack(char *s) { reply(250, "%s command successful.", s); } void nack(char *s) { reply(502, "%s command not implemented.", s); } /* ARGSUSED */ void yyerror(char *s) { char *cp; if ((cp = strchr(cbuf,'\n'))) *cp = '\0'; reply(500, "%s: command not understood.", cbuf); } void delete(char *name) { struct stat st; LOGCMD("delete", name); if (lstat(name, &st) < 0) { perror_reply(550, name); return; } if (S_ISDIR(st.st_mode)) { if (rmdir(name) < 0) { perror_reply(550, name); return; } goto done; } if (guest && noguestmod) { reply(550, "Operation not permitted."); return; } if (unlink(name) < 0) { perror_reply(550, name); return; } done: ack("DELE"); } void cwd(char *path) { if (chdir(path) < 0) perror_reply(550, path); else ack("CWD"); } void makedir(char *name) { char *s; LOGCMD("mkdir", name); if (guest && noguestmkd) reply(550, "Operation not permitted."); else if (mkdir(name, 0777) < 0) perror_reply(550, name); else { if ((s = doublequote(name)) == NULL) fatalerror("Ran out of memory."); reply(257, "\"%s\" directory created.", s); free(s); } } void removedir(char *name) { LOGCMD("rmdir", name); if (rmdir(name) < 0) perror_reply(550, name); else ack("RMD"); } void pwd(void) { char *s, path[MAXPATHLEN + 1]; if (getcwd(path, sizeof(path)) == NULL) perror_reply(550, "Get current directory"); else { if ((s = doublequote(path)) == NULL) fatalerror("Ran out of memory."); reply(257, "\"%s\" is current directory.", s); free(s); } } char * renamefrom(char *name) { struct stat st; if (guest && noguestmod) { reply(550, "Operation not permitted."); return (NULL); } if (lstat(name, &st) < 0) { perror_reply(550, name); return (NULL); } reply(350, "File exists, ready for destination name."); return (name); } void renamecmd(char *from, char *to) { struct stat st; LOGCMD2("rename", from, to); if (guest && (stat(to, &st) == 0)) { reply(550, "%s: permission denied.", to); return; } if (rename(from, to) < 0) perror_reply(550, "rename"); else ack("RNTO"); } static void dolog(struct sockaddr *who) { char who_name[NI_MAXHOST]; realhostname_sa(remotehost, sizeof(remotehost) - 1, who, who->sa_len); remotehost[sizeof(remotehost) - 1] = 0; if (getnameinfo(who, who->sa_len, who_name, sizeof(who_name) - 1, NULL, 0, NI_NUMERICHOST)) *who_name = 0; who_name[sizeof(who_name) - 1] = 0; #ifdef SETPROCTITLE #ifdef VIRTUAL_HOSTING if (thishost != firsthost) snprintf(proctitle, sizeof(proctitle), "%s: connected (to %s)", remotehost, hostname); else #endif snprintf(proctitle, sizeof(proctitle), "%s: connected", remotehost); setproctitle("%s", proctitle); #endif /* SETPROCTITLE */ if (logging) { #ifdef VIRTUAL_HOSTING if (thishost != firsthost) syslog(LOG_INFO, "connection from %s (%s) to %s", remotehost, who_name, hostname); else #endif syslog(LOG_INFO, "connection from %s (%s)", remotehost, who_name); } } /* * Record logout in wtmp file * and exit with supplied status. */ void dologout(int status) { if (logged_in && dowtmp) { (void) seteuid(0); ftpd_logwtmp(wtmpid, NULL, NULL); } /* beware of flushing buffers after a SIGPIPE */ _exit(status); } static void sigurg(int signo) { recvurg = 1; } static void maskurg(int flag) { int oerrno; sigset_t sset; if (!transflag) { syslog(LOG_ERR, "Internal: maskurg() while no transfer"); return; } oerrno = errno; sigemptyset(&sset); sigaddset(&sset, SIGURG); sigprocmask(flag ? SIG_BLOCK : SIG_UNBLOCK, &sset, NULL); errno = oerrno; } static void flagxfer(int flag) { if (flag) { if (transflag) syslog(LOG_ERR, "Internal: flagxfer(1): " "transfer already under way"); transflag = 1; maskurg(0); recvurg = 0; } else { if (!transflag) syslog(LOG_ERR, "Internal: flagxfer(0): " "no active transfer"); maskurg(1); transflag = 0; } } /* * Returns 0 if OK to resume or -1 if abort requested. */ static int myoob(void) { char *cp; int ret; if (!transflag) { syslog(LOG_ERR, "Internal: myoob() while no transfer"); return (0); } cp = tmpline; ret = getline(cp, 7, stdin); if (ret == -1) { reply(221, "You could at least say goodbye."); dologout(0); } else if (ret == -2) { /* Ignore truncated command. */ return (0); } upper(cp); if (strcmp(cp, "ABOR\r\n") == 0) { tmpline[0] = '\0'; reply(426, "Transfer aborted. Data connection closed."); reply(226, "Abort successful."); return (-1); } if (strcmp(cp, "STAT\r\n") == 0) { tmpline[0] = '\0'; if (file_size != -1) reply(213, "Status: %jd of %jd bytes transferred.", (intmax_t)byte_count, (intmax_t)file_size); else reply(213, "Status: %jd bytes transferred.", (intmax_t)byte_count); } return (0); } /* * Note: a response of 425 is not mentioned as a possible response to * the PASV command in RFC959. However, it has been blessed as * a legitimate response by Jon Postel in a telephone conversation * with Rick Adams on 25 Jan 89. */ void passive(void) { socklen_t len; int on; char *p, *a; if (pdata >= 0) /* close old port if one set */ close(pdata); pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0); if (pdata < 0) { perror_reply(425, "Can't open passive connection"); return; } on = 1; if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m"); (void) seteuid(0); #ifdef IP_PORTRANGE if (ctrl_addr.su_family == AF_INET) { on = restricted_data_ports ? IP_PORTRANGE_HIGH : IP_PORTRANGE_DEFAULT; if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE, &on, sizeof(on)) < 0) goto pasv_error; } #endif #ifdef IPV6_PORTRANGE if (ctrl_addr.su_family == AF_INET6) { on = restricted_data_ports ? IPV6_PORTRANGE_HIGH : IPV6_PORTRANGE_DEFAULT; if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE, &on, sizeof(on)) < 0) goto pasv_error; } #endif pasv_addr = ctrl_addr; pasv_addr.su_port = 0; if (bind(pdata, (struct sockaddr *)&pasv_addr, pasv_addr.su_len) < 0) goto pasv_error; (void) seteuid(pw->pw_uid); len = sizeof(pasv_addr); if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0) goto pasv_error; if (listen(pdata, 1) < 0) goto pasv_error; if (pasv_addr.su_family == AF_INET) a = (char *) &pasv_addr.su_sin.sin_addr; else if (pasv_addr.su_family == AF_INET6 && IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12]; else goto pasv_error; p = (char *) &pasv_addr.su_port; #define UC(b) (((int) b) & 0xff) reply(227, "Entering Passive Mode (%d,%d,%d,%d,%d,%d)", UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]), UC(p[0]), UC(p[1])); return; pasv_error: (void) seteuid(pw->pw_uid); (void) close(pdata); pdata = -1; perror_reply(425, "Can't open passive connection"); return; } /* * Long Passive defined in RFC 1639. * 228 Entering Long Passive Mode * (af, hal, h1, h2, h3,..., pal, p1, p2...) */ void long_passive(char *cmd, int pf) { socklen_t len; int on; char *p, *a; if (pdata >= 0) /* close old port if one set */ close(pdata); if (pf != PF_UNSPEC) { if (ctrl_addr.su_family != pf) { switch (ctrl_addr.su_family) { case AF_INET: pf = 1; break; case AF_INET6: pf = 2; break; default: pf = 0; break; } /* * XXX * only EPRT/EPSV ready clients will understand this */ if (strcmp(cmd, "EPSV") == 0 && pf) { reply(522, "Network protocol mismatch, " "use (%d)", pf); } else reply(501, "Network protocol mismatch."); /*XXX*/ return; } } pdata = socket(ctrl_addr.su_family, SOCK_STREAM, 0); if (pdata < 0) { perror_reply(425, "Can't open passive connection"); return; } on = 1; if (setsockopt(pdata, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) syslog(LOG_WARNING, "pdata setsockopt (SO_REUSEADDR): %m"); (void) seteuid(0); pasv_addr = ctrl_addr; pasv_addr.su_port = 0; len = pasv_addr.su_len; #ifdef IP_PORTRANGE if (ctrl_addr.su_family == AF_INET) { on = restricted_data_ports ? IP_PORTRANGE_HIGH : IP_PORTRANGE_DEFAULT; if (setsockopt(pdata, IPPROTO_IP, IP_PORTRANGE, &on, sizeof(on)) < 0) goto pasv_error; } #endif #ifdef IPV6_PORTRANGE if (ctrl_addr.su_family == AF_INET6) { on = restricted_data_ports ? IPV6_PORTRANGE_HIGH : IPV6_PORTRANGE_DEFAULT; if (setsockopt(pdata, IPPROTO_IPV6, IPV6_PORTRANGE, &on, sizeof(on)) < 0) goto pasv_error; } #endif if (bind(pdata, (struct sockaddr *)&pasv_addr, len) < 0) goto pasv_error; (void) seteuid(pw->pw_uid); if (getsockname(pdata, (struct sockaddr *) &pasv_addr, &len) < 0) goto pasv_error; if (listen(pdata, 1) < 0) goto pasv_error; #define UC(b) (((int) b) & 0xff) if (strcmp(cmd, "LPSV") == 0) { p = (char *)&pasv_addr.su_port; switch (pasv_addr.su_family) { case AF_INET: a = (char *) &pasv_addr.su_sin.sin_addr; v4_reply: reply(228, "Entering Long Passive Mode (%d,%d,%d,%d,%d,%d,%d,%d,%d)", 4, 4, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]), 2, UC(p[0]), UC(p[1])); return; case AF_INET6: if (IN6_IS_ADDR_V4MAPPED(&pasv_addr.su_sin6.sin6_addr)) { a = (char *) &pasv_addr.su_sin6.sin6_addr.s6_addr[12]; goto v4_reply; } a = (char *) &pasv_addr.su_sin6.sin6_addr; reply(228, "Entering Long Passive Mode " "(%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d)", 6, 16, UC(a[0]), UC(a[1]), UC(a[2]), UC(a[3]), UC(a[4]), UC(a[5]), UC(a[6]), UC(a[7]), UC(a[8]), UC(a[9]), UC(a[10]), UC(a[11]), UC(a[12]), UC(a[13]), UC(a[14]), UC(a[15]), 2, UC(p[0]), UC(p[1])); return; } } else if (strcmp(cmd, "EPSV") == 0) { switch (pasv_addr.su_family) { case AF_INET: case AF_INET6: reply(229, "Entering Extended Passive Mode (|||%d|)", ntohs(pasv_addr.su_port)); return; } } else { /* more proper error code? */ } pasv_error: (void) seteuid(pw->pw_uid); (void) close(pdata); pdata = -1; perror_reply(425, "Can't open passive connection"); return; } /* * Generate unique name for file with basename "local" * and open the file in order to avoid possible races. * Try "local" first, then "local.1", "local.2" etc, up to "local.99". * Return descriptor to the file, set "name" to its name. * * Generates failure reply on error. */ static int guniquefd(char *local, char **name) { static char new[MAXPATHLEN]; struct stat st; char *cp; int count; int fd; cp = strrchr(local, '/'); if (cp) *cp = '\0'; if (stat(cp ? local : ".", &st) < 0) { perror_reply(553, cp ? local : "."); return (-1); } if (cp) { /* * Let not overwrite dirname with counter suffix. * -4 is for /nn\0 * In this extreme case dot won't be put in front of suffix. */ if (strlen(local) > sizeof(new) - 4) { reply(553, "Pathname too long."); return (-1); } *cp = '/'; } /* -4 is for the .nn we put on the end below */ (void) snprintf(new, sizeof(new) - 4, "%s", local); cp = new + strlen(new); /* * Don't generate dotfile unless requested explicitly. * This covers the case when basename gets truncated off * by buffer size. */ if (cp > new && cp[-1] != '/') *cp++ = '.'; for (count = 0; count < 100; count++) { /* At count 0 try unmodified name */ if (count) (void)sprintf(cp, "%d", count); if ((fd = open(count ? new : local, O_RDWR | O_CREAT | O_EXCL, 0666)) >= 0) { *name = count ? new : local; return (fd); } if (errno != EEXIST) { perror_reply(553, count ? new : local); return (-1); } } reply(452, "Unique file name cannot be created."); return (-1); } /* * Format and send reply containing system error number. */ void perror_reply(int code, char *string) { reply(code, "%s: %s.", string, strerror(errno)); } static char *onefile[] = { "", 0 }; void send_file_list(char *whichf) { struct stat st; DIR *dirp = NULL; struct dirent *dir; FILE *dout = NULL; char **dirlist, *dirname; int simple = 0; int freeglob = 0; glob_t gl; if (strpbrk(whichf, "~{[*?") != NULL) { int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE; memset(&gl, 0, sizeof(gl)); gl.gl_matchc = MAXGLOBARGS; flags |= GLOB_LIMIT; freeglob = 1; if (glob(whichf, flags, 0, &gl)) { reply(550, "No matching files found."); goto out; } else if (gl.gl_pathc == 0) { errno = ENOENT; perror_reply(550, whichf); goto out; } dirlist = gl.gl_pathv; } else { onefile[0] = whichf; dirlist = onefile; simple = 1; } while ((dirname = *dirlist++)) { if (stat(dirname, &st) < 0) { /* * If user typed "ls -l", etc, and the client * used NLST, do what the user meant. */ if (dirname[0] == '-' && *dirlist == NULL && dout == NULL) retrieve(_PATH_LS " %s", dirname); else perror_reply(550, whichf); goto out; } if (S_ISREG(st.st_mode)) { if (dout == NULL) { dout = dataconn("file list", -1, "w"); if (dout == NULL) goto out; STARTXFER; } START_UNSAFE; fprintf(dout, "%s%s\n", dirname, type == TYPE_A ? "\r" : ""); END_UNSAFE; if (ferror(dout)) goto data_err; byte_count += strlen(dirname) + (type == TYPE_A ? 2 : 1); CHECKOOB(goto abrt); continue; } else if (!S_ISDIR(st.st_mode)) continue; if ((dirp = opendir(dirname)) == NULL) continue; while ((dir = readdir(dirp)) != NULL) { char nbuf[MAXPATHLEN]; CHECKOOB(goto abrt); if (dir->d_name[0] == '.' && dir->d_namlen == 1) continue; if (dir->d_name[0] == '.' && dir->d_name[1] == '.' && dir->d_namlen == 2) continue; snprintf(nbuf, sizeof(nbuf), "%s/%s", dirname, dir->d_name); /* * We have to do a stat to insure it's * not a directory or special file. */ if (simple || (stat(nbuf, &st) == 0 && S_ISREG(st.st_mode))) { if (dout == NULL) { dout = dataconn("file list", -1, "w"); if (dout == NULL) goto out; STARTXFER; } START_UNSAFE; if (nbuf[0] == '.' && nbuf[1] == '/') fprintf(dout, "%s%s\n", &nbuf[2], type == TYPE_A ? "\r" : ""); else fprintf(dout, "%s%s\n", nbuf, type == TYPE_A ? "\r" : ""); END_UNSAFE; if (ferror(dout)) goto data_err; byte_count += strlen(nbuf) + (type == TYPE_A ? 2 : 1); CHECKOOB(goto abrt); } } (void) closedir(dirp); dirp = NULL; } if (dout == NULL) reply(550, "No files found."); else if (ferror(dout)) data_err: perror_reply(550, "Data connection"); else reply(226, "Transfer complete."); out: if (dout) { ENDXFER; abrt: (void) fclose(dout); data = -1; pdata = -1; } if (dirp) (void) closedir(dirp); if (freeglob) { freeglob = 0; globfree(&gl); } } void reapchild(int signo) { while (waitpid(-1, NULL, WNOHANG) > 0); } #ifdef OLD_SETPROCTITLE /* * Clobber argv so ps will show what we're doing. (Stolen from sendmail.) * Warning, since this is usually started from inetd.conf, it often doesn't * have much of an environment or arglist to overwrite. */ void setproctitle(const char *fmt, ...) { int i; va_list ap; char *p, *bp, ch; char buf[LINE_MAX]; va_start(ap, fmt); (void)vsnprintf(buf, sizeof(buf), fmt, ap); /* make ps print our process name */ p = Argv[0]; *p++ = '-'; i = strlen(buf); if (i > LastArgv - p - 2) { i = LastArgv - p - 2; buf[i] = '\0'; } bp = buf; while (ch = *bp++) if (ch != '\n' && ch != '\r') *p++ = ch; while (p < LastArgv) *p++ = ' '; } #endif /* OLD_SETPROCTITLE */ static void appendf(char **strp, char *fmt, ...) { va_list ap; char *ostr, *p; va_start(ap, fmt); vasprintf(&p, fmt, ap); va_end(ap); if (p == NULL) fatalerror("Ran out of memory."); if (*strp == NULL) *strp = p; else { ostr = *strp; asprintf(strp, "%s%s", ostr, p); if (*strp == NULL) fatalerror("Ran out of memory."); free(ostr); } } static void logcmd(char *cmd, char *file1, char *file2, off_t cnt) { char *msg = NULL; char wd[MAXPATHLEN + 1]; if (logging <= 1) return; if (getcwd(wd, sizeof(wd) - 1) == NULL) strcpy(wd, strerror(errno)); appendf(&msg, "%s", cmd); if (file1) appendf(&msg, " %s", file1); if (file2) appendf(&msg, " %s", file2); if (cnt >= 0) appendf(&msg, " = %jd bytes", (intmax_t)cnt); appendf(&msg, " (wd: %s", wd); if (guest || dochroot) appendf(&msg, "; chrooted"); appendf(&msg, ")"); syslog(LOG_INFO, "%s", msg); free(msg); } static void logxfer(char *name, off_t size, time_t start) { char buf[MAXPATHLEN + 1024]; char path[MAXPATHLEN + 1]; time_t now; if (statfd >= 0) { time(&now); if (realpath(name, path) == NULL) { syslog(LOG_NOTICE, "realpath failed on %s: %m", path); return; } snprintf(buf, sizeof(buf), "%.20s!%s!%s!%s!%jd!%ld\n", ctime(&now)+4, ident, remotehost, path, (intmax_t)size, (long)(now - start + (now == start))); write(statfd, buf, strlen(buf)); } } static char * doublequote(char *s) { int n; char *p, *s2; for (p = s, n = 0; *p; p++) if (*p == '"') n++; if ((s2 = malloc(p - s + n + 1)) == NULL) return (NULL); for (p = s2; *s; s++, p++) { if ((*p = *s) == '"') *(++p) = '"'; } *p = '\0'; return (s2); } /* setup server socket for specified address family */ /* if af is PF_UNSPEC more than one socket may be returned */ /* the returned list is dynamically allocated, so caller needs to free it */ static int * socksetup(int af, char *bindname, const char *bindport) { struct addrinfo hints, *res, *r; int error, maxs, *s, *socks; const int on = 1; memset(&hints, 0, sizeof(hints)); hints.ai_flags = AI_PASSIVE; hints.ai_family = af; hints.ai_socktype = SOCK_STREAM; error = getaddrinfo(bindname, bindport, &hints, &res); if (error) { syslog(LOG_ERR, "%s", gai_strerror(error)); if (error == EAI_SYSTEM) syslog(LOG_ERR, "%s", strerror(errno)); return NULL; } /* Count max number of sockets we may open */ for (maxs = 0, r = res; r; r = r->ai_next, maxs++) ; socks = malloc((maxs + 1) * sizeof(int)); if (!socks) { freeaddrinfo(res); syslog(LOG_ERR, "couldn't allocate memory for sockets"); return NULL; } *socks = 0; /* num of sockets counter at start of array */ s = socks + 1; for (r = res; r; r = r->ai_next) { *s = socket(r->ai_family, r->ai_socktype, r->ai_protocol); if (*s < 0) { syslog(LOG_DEBUG, "control socket: %m"); continue; } if (setsockopt(*s, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) syslog(LOG_WARNING, "control setsockopt (SO_REUSEADDR): %m"); if (r->ai_family == AF_INET6) { if (setsockopt(*s, IPPROTO_IPV6, IPV6_V6ONLY, &on, sizeof(on)) < 0) syslog(LOG_WARNING, "control setsockopt (IPV6_V6ONLY): %m"); } if (bind(*s, r->ai_addr, r->ai_addrlen) < 0) { syslog(LOG_DEBUG, "control bind: %m"); close(*s); continue; } (*socks)++; s++; } if (res) freeaddrinfo(res); if (*socks == 0) { syslog(LOG_ERR, "control socket: Couldn't bind to any socket"); free(socks); return NULL; } return(socks); } Index: head/libexec/ftpd/logwtmp.c =================================================================== --- head/libexec/ftpd/logwtmp.c (revision 262135) +++ head/libexec/ftpd/logwtmp.c (revision 262136) @@ -1,81 +1,77 @@ /* * Copyright (c) 1988, 1993 * The Regents of the University of California. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #ifndef lint #if 0 static char sccsid[] = "@(#)logwtmp.c 8.1 (Berkeley) 6/4/93"; #endif #endif /* not lint */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include "extern.h" void ftpd_logwtmp(char *id, char *user, struct sockaddr *addr) { struct utmpx ut; memset(&ut, 0, sizeof(ut)); if (user != NULL) { /* Log in. */ ut.ut_type = USER_PROCESS; (void)strncpy(ut.ut_user, user, sizeof(ut.ut_user)); if (addr != NULL) realhostname_sa(ut.ut_host, sizeof(ut.ut_host), addr, addr->sa_len); } else { /* Log out. */ ut.ut_type = DEAD_PROCESS; } ut.ut_pid = getpid(); gettimeofday(&ut.ut_tv, NULL); (void)strncpy(ut.ut_id, id, sizeof(ut.ut_id)); (void)strncpy(ut.ut_line, "ftpd", sizeof(ut.ut_line)); pututxline(&ut); } Index: head/libexec/ftpd/pathnames.h =================================================================== --- head/libexec/ftpd/pathnames.h (revision 262135) +++ head/libexec/ftpd/pathnames.h (revision 262136) @@ -1,44 +1,40 @@ /* * Copyright (c) 1989, 1993 * The Regents of the University of California. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. * * @(#)pathnames.h 8.1 (Berkeley) 6/4/93 * $FreeBSD$ */ #include #define _PATH_FTPCHROOT "/etc/ftpchroot" #define _PATH_FTPWELCOME "/etc/ftpwelcome" #define _PATH_FTPLOGINMESG "/etc/ftpmotd" #define _PATH_FTPHOSTS "/etc/ftphosts" #define _PATH_FTPDSTATFILE "/var/log/ftpd" #define _PATH_LS "/bin/ls" Index: head/libexec/ftpd/popen.c =================================================================== --- head/libexec/ftpd/popen.c (revision 262135) +++ head/libexec/ftpd/popen.c (revision 262136) @@ -1,205 +1,201 @@ /* * Copyright (c) 1988, 1993, 1994 * The Regents of the University of California. All rights reserved. * * This code is derived from software written by Ken Arnold and * published in UNIX Review, Vol. 6, No. 8. * * 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #ifndef lint #if 0 static char sccsid[] = "@(#)popen.c 8.3 (Berkeley) 4/6/94"; #endif #endif /* not lint */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include "extern.h" #include "pathnames.h" #include #include #define MAXUSRARGS 100 #define MAXGLOBARGS 1000 /* * Special version of popen which avoids call to shell. This ensures noone * may create a pipe to a hidden program as a side effect of a list or dir * command. */ static int *pids; static int fds; FILE * ftpd_popen(char *program, char *type) { char *cp; FILE *iop; int argc, gargc, pdes[2], pid; char **pop, *argv[MAXUSRARGS], *gargv[MAXGLOBARGS]; if (((*type != 'r') && (*type != 'w')) || type[1]) return (NULL); if (!pids) { if ((fds = getdtablesize()) <= 0) return (NULL); if ((pids = malloc(fds * sizeof(int))) == NULL) return (NULL); memset(pids, 0, fds * sizeof(int)); } if (pipe(pdes) < 0) return (NULL); /* break up string into pieces */ for (argc = 0, cp = program; argc < MAXUSRARGS; cp = NULL) { if (!(argv[argc++] = strtok(cp, " \t\n"))) break; } argv[argc - 1] = NULL; /* glob each piece */ gargv[0] = argv[0]; for (gargc = argc = 1; argv[argc] && gargc < (MAXGLOBARGS-1); argc++) { glob_t gl; int flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE; memset(&gl, 0, sizeof(gl)); gl.gl_matchc = MAXGLOBARGS; flags |= GLOB_LIMIT; if (glob(argv[argc], flags, NULL, &gl)) gargv[gargc++] = strdup(argv[argc]); else if (gl.gl_pathc > 0) { for (pop = gl.gl_pathv; *pop && gargc < (MAXGLOBARGS-1); pop++) gargv[gargc++] = strdup(*pop); } globfree(&gl); } gargv[gargc] = NULL; iop = NULL; fflush(NULL); pid = (strcmp(gargv[0], _PATH_LS) == 0) ? fork() : vfork(); switch(pid) { case -1: /* error */ (void)close(pdes[0]); (void)close(pdes[1]); goto pfree; /* NOTREACHED */ case 0: /* child */ if (*type == 'r') { if (pdes[1] != STDOUT_FILENO) { dup2(pdes[1], STDOUT_FILENO); (void)close(pdes[1]); } dup2(STDOUT_FILENO, STDERR_FILENO); /* stderr too! */ (void)close(pdes[0]); } else { if (pdes[0] != STDIN_FILENO) { dup2(pdes[0], STDIN_FILENO); (void)close(pdes[0]); } (void)close(pdes[1]); } /* Drop privileges before proceeding */ if (getuid() != geteuid() && setuid(geteuid()) < 0) _exit(1); if (strcmp(gargv[0], _PATH_LS) == 0) { /* Reset getopt for ls_main() */ optreset = optind = optopt = 1; /* Close syslogging to remove pwd.db missing msgs */ closelog(); /* Trigger to sense new /etc/localtime after chroot */ if (getenv("TZ") == NULL) { setenv("TZ", "", 0); tzset(); unsetenv("TZ"); tzset(); } exit(ls_main(gargc, gargv)); } execv(gargv[0], gargv); _exit(1); } /* parent; assume fdopen can't fail... */ if (*type == 'r') { iop = fdopen(pdes[0], type); (void)close(pdes[1]); } else { iop = fdopen(pdes[1], type); (void)close(pdes[0]); } pids[fileno(iop)] = pid; pfree: for (argc = 1; gargv[argc] != NULL; argc++) free(gargv[argc]); return (iop); } int ftpd_pclose(FILE *iop) { int fdes, omask, status; pid_t pid; /* * pclose returns -1 if stream is not associated with a * `popened' command, or, if already `pclosed'. */ if (pids == 0 || pids[fdes = fileno(iop)] == 0) return (-1); (void)fclose(iop); omask = sigblock(sigmask(SIGINT)|sigmask(SIGQUIT)|sigmask(SIGHUP)); while ((pid = waitpid(pids[fdes], &status, 0)) < 0 && errno == EINTR) continue; (void)sigsetmask(omask); pids[fdes] = 0; if (pid < 0) return (pid); if (WIFEXITED(status)) return (WEXITSTATUS(status)); return (1); } Index: head/libexec/getty/extern.h =================================================================== --- head/libexec/getty/extern.h (revision 262135) +++ head/libexec/getty/extern.h (revision 262136) @@ -1,60 +1,56 @@ /* * Copyright (c) 1993 * The Regents of the University of California. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. * * from: @(#)extern.h 8.1 (Berkeley) 6/4/93 * $FreeBSD$ */ struct delayval; struct termios; extern char hostname[]; extern int hopcount; extern struct termios tmode, omode; extern struct gettyflags gettyflags[]; extern struct gettynums gettynums[]; extern struct gettystrs gettystrs[]; int adelay(int, struct delayval *); const char *autobaud(void); int delaybits(void); void edithost(const char *); void gendefaults(void); void gettable(const char *, char *); void makeenv(char *[]); const char *portselector(void); void set_ttydefaults(int); void setchars(void); void setdefaults(void); void set_flags(int); int speed(int); int getty_chat(char *, int, int); Index: head/libexec/getty/getty.8 =================================================================== --- head/libexec/getty/getty.8 (revision 262135) +++ head/libexec/getty/getty.8 (revision 262136) @@ -1,128 +1,124 @@ .\" Copyright (c) 1980, 1991, 1993 .\" The Regents of the University of California. 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. -.\" 3. All advertising materials mentioning features or use of this software -.\" must display the following acknowledgement: -.\" This product includes software developed by the University of -.\" California, Berkeley and its contributors. -.\" 4. Neither the name of the University nor the names of its contributors +.\" 3. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. .\" .\" from: @(#)getty.8 8.1 (Berkeley) 6/4/93 .\" $FreeBSD$ .\" " .Dd June 4, 1993 .Dt GETTY 8 .Os .Sh NAME .Nm getty .Nd set terminal mode .Sh SYNOPSIS .Nm .Oo .Ar type .Op Ar tty .Oc .Sh DESCRIPTION The .Nm utility is called by .Xr init 8 to open and initialize the tty line, read a login name, and invoke .Xr login 1 . .Pp The argument .Ar tty is the special device file in .Pa /dev to open for the terminal (for example, ``ttyh0''). If there is no argument or the argument is .Sq Fl , the tty line is assumed to be open as file descriptor 0. .Pp The .Ar type argument can be used to make .Nm treat the terminal line specially. This argument is used as an index into the .Xr gettytab 5 database, to determine the characteristics of the line. If there is no argument, or there is no such table, the .Em default table is used. If there is no .Pa /etc/gettytab a set of system defaults is used. If indicated by the table located, .Nm will clear the terminal screen, print a banner heading, and prompt for a login name. Usually either the banner or the login prompt will include the system hostname. .Pp Most of the default actions of .Nm can be circumvented, or modified, by a suitable .Pa gettytab table. .Pp The .Nm utility can be set to timeout after some interval, which will cause dial up lines to hang up if the login name is not entered reasonably quickly. .Sh FILES .Bl -tag -width /etc/gettytab -compact .It Pa /etc/gettytab .It Pa /etc/ttys .El .Sh DIAGNOSTICS .Bl -diag .It "ttyxx: No such device or address." .It "ttyxx: No such file or address." .Pp A terminal which is turned on in the .Pa ttys file cannot be opened, likely because the requisite lines are either not configured into the system, the associated device was not attached during boot-time system configuration, or the special file in .Pa /dev does not exist. .El .Sh SEE ALSO .Xr login 1 , .Xr ioctl 2 , .Xr tty 4 , .Xr gettytab 5 , .Xr ttys 5 , .Xr init 8 .Sh HISTORY A .Nm utility appeared in .At v6 . Index: head/libexec/getty/gettytab.5 =================================================================== --- head/libexec/getty/gettytab.5 (revision 262135) +++ head/libexec/getty/gettytab.5 (revision 262136) @@ -1,541 +1,537 @@ .\" Copyright (c) 1983, 1991, 1993 .\" The Regents of the University of California. 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. -.\" 3. All advertising materials mentioning features or use of this software -.\" must display the following acknowledgement: -.\" This product includes software developed by the University of -.\" California, Berkeley and its contributors. -.\" 4. Neither the name of the University nor the names of its contributors +.\" 3. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. .\" .\" from: @(#)gettytab.5 8.4 (Berkeley) 4/19/94 .\" $FreeBSD$ .\" " .Dd April 19, 1994 .Dt GETTYTAB 5 .Os .Sh NAME .Nm gettytab .Nd terminal configuration data base .Sh SYNOPSIS .Nm .Sh DESCRIPTION The .Nm file is a simplified version of the .Xr termcap 5 data base used to describe terminal lines. The initial terminal login process .Xr getty 8 accesses the .Nm file each time it starts, allowing simpler reconfiguration of terminal characteristics. Each entry in the data base is used to describe one class of terminals. .Pp There is a default terminal class, .Va default , that is used to set global defaults for all other classes. (That is, the .Va default entry is read, then the entry for the class required is used to override particular settings.) .Sh CAPABILITIES Refer to .Xr termcap 5 for a description of the file layout. The .Va default column below lists defaults obtained if there is no entry in the table obtained, nor one in the special .Va default table. .Bl -column Name Type /usr/bin/login .It Sy "Name Type Default Description" .It "ac str unused expect-send chat script for modem answer" .It "al str unused user to auto-login instead of prompting" .It "ap bool false terminal uses any parity" .It "bk str 0377 alternate end of line character (input break)" .It "c0 num unused tty control flags to write messages" .It "c1 num unused tty control flags to read login name" .It "c2 num unused tty control flags to leave terminal as" .It "ce bool false use crt erase algorithm" .It "ck bool false use crt kill algorithm" .It "cl str" Ta Dv NULL Ta .No "screen clear sequence" .It "co bool false console - add" .Ql \en after login prompt .It "ct num 10 chat timeout for" .Va \&ac and .Va \&ic scripts .It "dc num 0 chat debug bitmask" .It "de num 0 delay secs and flush input before writing first prompt" .It "df str %+ the" Xr strftime 3 "format used for \&%d in the banner message" .It "ds str" Ta So Li ^Y Sc Ta .No "delayed suspend character" .It "dx bool false set" .Dv DECCTLQ .It "ec bool false leave echo" .Em OFF .It "ep bool false terminal uses even parity" .It "er str" Ta So Li ^? Sc Ta .No "erase character" .It "et str" Ta So Li ^D Sc Ta .No "end of text" .Pq Dv EOF character .It "ev str" Ta Dv NULL Ta .No "initial environment" .It "f0 num unused tty mode flags to write messages" .It "f1 num unused tty mode flags to read login name" .It "f2 num unused tty mode flags to leave terminal as" .It "fl str" Ta So Li ^O Sc Ta .No "output flush character" .It "hc bool false do" .Em NOT hangup line on last close .It "he str" Ta Dv NULL Ta .No "hostname editing string" .It "hn str hostname hostname" .It "ht bool false terminal has real tabs" .It "hw bool false do cts/rts hardware flow control" .It "i0 num unused tty input flags to write messages" .It "i1 num unused tty input flags to read login name" .It "i2 num unused tty input flags to leave terminal as" .It "ic str unused expect-send chat script for modem initialization" .It "if str unused display named file before prompt, like /etc/issue" .It "ig bool false ignore garbage characters in login name" .It "im str" Ta Dv NULL Ta .No "initial (banner) message" .It "in str" Ta So Li ^C Sc Ta .No "interrupt character" .It "is num unused input speed" .It "kl str" Ta So Li ^U Sc Ta .No "kill character" .It "l0 num unused tty local flags to write messages" .It "l1 num unused tty local flags to read login name" .It "l2 num unused tty local flags to leave terminal as" .It "lm str login: login prompt" .It "ln str" Ta So Li ^V Sc Ta .No "``literal next'' character" .It "lo str" Ta Pa /usr/bin/login Ta .No "program to exec when name obtained" .It "mb bool false do flow control based on carrier" .It "nc bool false terminal does not supply carrier (set clocal)" .It "nl bool false terminal has (or might have) a newline character" .It "np bool false terminal uses no parity (i.e. 8-bit characters)" .It "nx str default next table (for auto speed selection)" .It "o0 num unused tty output flags to write messages" .It "o1 num unused tty output flags to read login name" .It "o2 num unused tty output flags to leave terminal as" .It "op bool false terminal uses odd parity" .It "os num unused output speed" .It "pc str" Ta So Li \e0 Sc Ta .No "pad character" .It "pe bool false use printer (hard copy) erase algorithm" .It "pf num 0 delay" between first prompt and following flush (seconds) .It "pl bool false start PPP login program unconditionally if" .Va \&pp is specified .It "pp str unused PPP login program" .It "ps bool false line connected to a" .Tn MICOM port selector .It "qu str" Ta So Li \&^\e Sc Ta .No "quit character" .It "rp str" Ta So Li ^R Sc Ta .No "line retype character" .It "rt num unused ring timeout when using" .Va \&ac .It "rw bool false do" .Em NOT use raw for input, use cbreak .It "sp num unused line speed (input and output)" .It "su str" Ta So Li ^Z Sc Ta .No "suspend character" .It "tc str none table continuation" .It "to num 0 timeout (seconds)" .It "tt str" Ta Dv NULL Ta .No "terminal type (for environment)" .It "ub bool false do unbuffered output (of prompts etc)" .It "we str" Ta So Li ^W Sc Ta .No "word erase character" .It "xc bool false do" .Em NOT echo control chars as .Ql ^X .It "xf str" Ta So Li ^S Sc Ta Dv XOFF (stop output) character .It "xn str" Ta So Li ^Q Sc Ta Dv XON (start output) character .It "Lo str C the locale name used for \&%d in the banner message" .El .Pp The following capabilities are no longer supported by .Xr getty 8 : .Bl -column Name Type /usr/bin/login .It "bd num 0 backspace delay" .It "cb bool false use crt backspace mode" .It "cd num 0 carriage-return delay" .It "fd num 0 form-feed (vertical motion) delay" .It "lc bool false terminal has lower case" .It "nd num 0 newline (line-feed) delay" .It "uc bool false terminal is known upper case only" .El .Pp If no line speed is specified, speed will not be altered from that which prevails when getty is entered. Specifying an input or output speed will override line speed for stated direction only. .Pp Terminal modes to be used for the output of the message, for input of the login name, and to leave the terminal set as upon completion, are derived from the boolean flags specified. If the derivation should prove inadequate, any (or all) of these three may be overridden with one of the .Va \&c0 , .Va \&c1 , .Va \&c2 , .Va \&i0 , .Va \&i1 , .Va \&i2 , .Va \&l0 , .Va \&l1 , .Va \&l2 , .Va \&o0 , .Va \&o1 , or .Va \&o2 numeric specifications, which can be used to specify (usually in octal, with a leading '0') the exact values of the flags. These flags correspond to the termios .Va c_cflag , .Va c_iflag , .Va c_lflag , and .Va c_oflag fields, respectively. Each these sets must be completely specified to be effective. The .Va \&f0 , .Va \&f1 , and .Va \&f2 are excepted for backwards compatibility with a previous incarnation of the TTY sub-system. In these flags the bottom 16 bits of the (32 bits) value contain the sgttyb .Va sg_flags field, while the top 16 bits represent the local mode word. .Pp Should .Xr getty 8 receive a null character (presumed to indicate a line break) it will restart using the table indicated by the .Va \&nx entry. If there is none, it will re-use its original table. .Pp Delays are specified in milliseconds, the nearest possible delay available in the tty driver will be used. Should greater certainty be desired, delays with values 0, 1, 2, and 3 are interpreted as choosing that particular delay algorithm from the driver. .Pp The .Va \&cl screen clear string may be preceded by a (decimal) number of milliseconds of delay required (a la termcap). This delay is simulated by repeated use of the pad character .Va \&pc . .Pp The initial message, login message, and initial file; .Va \&im , .Va \&lm and .Va \&if may include any of the following character sequences, which expand to information about the environment in which .Xr getty 8 is running. .Bl -tag -offset indent -width \&%xxxxxxxxxxxxxx .It \&%d The current date and time formatted according to the .Va \&Lo and .Va \&df strings. .It \&%h The hostname of the machine, which is normally obtained from the system using .Xr gethostname 3 , but may also be overridden by the .Va \&hn table entry. In either case it may be edited with the .Va \&he string. A '@' in the .Va \&he string causes one character from the real hostname to be copied to the final hostname. A '#' in the .Va \&he string causes the next character of the real hostname to be skipped. Each character that is neither '@' nor '#' is copied into the final hostname. Surplus '@' and '#' characters are ignored. .It \&%t The tty name. .It "\&%m, \&%r, \&%s, \&%v" The type of machine, release of the operating system, name of the operating system, and version of the kernel, respectively, as returned by .Xr uname 3 . .It \&%% A .Dq % character. .El .Pp When getty execs the login process, given in the .Va \&lo string (usually .Dq Pa /usr/bin/login ) , it will have set the environment to include the terminal type, as indicated by the .Va \&tt string (if it exists). The .Va \&ev string, can be used to enter additional data into the environment. It is a list of comma separated strings, each of which will presumably be of the form .Li name=value . .Pp If a non-zero timeout is specified, with .Va \&to , then getty will exit within the indicated number of seconds, either having received a login name and passed control to .Xr login 1 , or having received an alarm signal, and exited. This may be useful to hangup dial in lines. .Pp Output from .Xr getty 8 is even parity unless .Va \&op or .Va \&np is specified. The .Va \&op string may be specified with .Va \&ap to allow any parity on input, but generate odd parity output. Note: this only applies while getty is being run, terminal driver limitations prevent a more complete implementation. The .Xr getty 8 utility does not check parity of input characters in .Dv RAW mode. .Pp If a .Va \&pp string is specified and a PPP link bring-up sequence is recognized, getty will invoke the program referenced by the .Va \&pp option. This can be used to handle incoming PPP calls. If the .Va \&pl option is true as well, .Xr getty 8 will skip the user name prompt and the PPP detection phase, and will invoke the program specified by .Va \&pp instantly. .Pp .Nm Getty provides some basic intelligent modem handling by providing a chat script feature available via two capabilities: .Pp .Bl -tag -offset indent -width \&xxxxxxxx -compact .It ic Chat script to initialize modem. .It ac Chat script to answer a call. .El .Pp A chat script is a set of expect/send string pairs. When a chat string starts, .Nm getty will wait for the first string, and if it finds it, will send the second, and so on. Strings specified are separated by one or more tabs or spaces. Strings may contain standard ASCII characters and special 'escapes', which consist of a backslash character followed by one or more characters which are interpreted as follows: .Pp .Bl -tag -offset indent -width \&xxxxxxxx -compact .It \ea bell character. .It \eb backspace. .It \en newline. .It \ee escape. .It \ef formfeed. .It \ep half-second pause. .It \er carriage return. .It \eS , \es space character. .It \et tab. .It \exNN hexadecimal byte value. .It \e0NNN octal byte value. .El .Pp Note that the .Ql \ep sequence is only valid for send strings and causes a half-second pause between sending the previous and next characters. Hexadecimal values are, at most, 2 hex digits long, and octal values are a maximum of 3 octal digits. .Pp The .Va \&ic chat sequence is used to initialize a modem or similar device. A typical example of an init chat script for a modem with a hayes compatible command set might look like this: .Pp .Dl :ic="" ATE0Q0V1\er OK\er ATS0=0\er OK\er: .Pp This script waits for nothing (which always succeeds), sends a sequence to ensure that the modem is in the correct mode (suppress command echo, send responses in verbose mode), and then disables auto-answer. It waits for an "OK" response before it terminates. The init sequence is used to check modem responses to ensure that the modem is functioning correctly. If the init script fails to complete, .Nm getty considers this to be fatal, and results in an error logged via .Xr syslogd 8 , and exiting. .Pp Similarly, an answer chat script is used to manually answer the phone in response to (usually) a "RING". When run with an answer script, .Nm getty opens the port in non-blocking mode, clears any extraneous input and waits for data on the port. As soon as any data is available, the answer chat script is started and scanned for a string, and responds according to the answer chat script. With a hayes compatible modem, this would normally look something like: .Pp .Dl :ac=RING\er ATA\er CONNECT: .Pp This causes the modem to answer the call via the "ATA" command, then scans input for a "CONNECT" string. If this is received before a .Va \&ct timeout, then a normal login sequence commences. .Pp The .Va \&ct capability specifies a timeout for all send and expect strings. This timeout is set individually for each expect wait and send string and must be at least as long as the time it takes for a connection to be established between a remote and local modem (usually around 10 seconds). .Pp In most situations, you will want to flush any additional input after the connection has been detected, and the .Va \&de capability may be used to do that, as well as delay for a short time after the connection has been established during which all of the connection data has been sent by the modem. .Sh SEE ALSO .Xr login 1 , .Xr gethostname 3 , .Xr uname 3 , .Xr termcap 5 , .Xr getty 8 , .Xr telnetd 8 .Sh HISTORY The .Nm file format appeared in .Bx 4.2 . .Sh BUGS The special characters (erase, kill, etc.) are reset to system defaults by .Xr login 1 . In .Em all cases, '#' or '^H' typed in a login name will be treated as an erase character, and '@' will be treated as a kill character. .Pp The delay stuff is a real crock. Apart form its general lack of flexibility, some of the delay algorithms are not implemented. The terminal driver should support sane delay settings. .Pp The .Va \&he capability is stupid. .Pp The .Xr termcap 5 format is horrid, something more rational should have been chosen. Index: head/libexec/getty/gettytab.h =================================================================== --- head/libexec/getty/gettytab.h (revision 262135) +++ head/libexec/getty/gettytab.h (revision 262136) @@ -1,177 +1,173 @@ /* * Copyright (c) 1983, 1993, 1994 * The Regents of the University of California. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. * * from: @(#)gettytab.h 8.2 (Berkeley) 3/30/94 * $FreeBSD$ */ /* * Getty description definitions. */ struct gettystrs { const char *field; /* name to lookup in gettytab */ char *defalt; /* value we find by looking in defaults */ char *value; /* value that we find there */ }; struct gettynums { const char *field; /* name to lookup */ long defalt; /* number we find in defaults */ long value; /* number we find there */ int set; /* we actually got this one */ }; struct gettyflags { const char *field; /* name to lookup */ char invrt; /* name existing in gettytab --> false */ char defalt; /* true/false in defaults */ char value; /* true/false flag */ char set; /* we found it */ }; /* * String values. */ #define NX gettystrs[0].value #define CL gettystrs[1].value #define IM gettystrs[2].value #define LM gettystrs[3].value #define ER gettystrs[4].value #define KL gettystrs[5].value #define ET gettystrs[6].value #define PC gettystrs[7].value #define TT gettystrs[8].value #define EV gettystrs[9].value #define LO gettystrs[10].value #define HN gettystrs[11].value #define HE gettystrs[12].value #define IN gettystrs[13].value #define QU gettystrs[14].value #define XN gettystrs[15].value #define XF gettystrs[16].value #define BK gettystrs[17].value #define SU gettystrs[18].value #define DS gettystrs[19].value #define RP gettystrs[20].value #define FL gettystrs[21].value #define WE gettystrs[22].value #define LN gettystrs[23].value #define Lo gettystrs[24].value #define PP gettystrs[25].value #define IF gettystrs[26].value #define IC gettystrs[27].value #define AC gettystrs[28].value #define AL gettystrs[29].value #define DF gettystrs[30].value /* * Numeric definitions. */ #define IS gettynums[0].value #define OS gettynums[1].value #define SP gettynums[2].value #define ND gettynums[3].value #define CD gettynums[4].value #define TD gettynums[5].value #define FD gettynums[6].value #define BD gettynums[7].value #define TO gettynums[8].value #define F0 gettynums[9].value #define F0set gettynums[9].set #define F1 gettynums[10].value #define F1set gettynums[10].set #define F2 gettynums[11].value #define F2set gettynums[11].set #define PF gettynums[12].value #define C0 gettynums[13].value #define C0set gettynums[13].set #define C1 gettynums[14].value #define C1set gettynums[14].set #define C2 gettynums[15].value #define C2set gettynums[15].set #define I0 gettynums[16].value #define I0set gettynums[16].set #define I1 gettynums[17].value #define I1set gettynums[17].set #define I2 gettynums[18].value #define I2set gettynums[18].set #define L0 gettynums[19].value #define L0set gettynums[19].set #define L1 gettynums[20].value #define L1set gettynums[20].set #define L2 gettynums[21].value #define L2set gettynums[21].set #define O0 gettynums[22].value #define O0set gettynums[22].set #define O1 gettynums[23].value #define O1set gettynums[23].set #define O2 gettynums[24].value #define O2set gettynums[24].set #define DE gettynums[25].value #define RTset gettynums[26].set #define RT gettynums[26].value #define CT gettynums[27].value #define DC gettynums[28].value /* * Boolean values. */ #define HT gettyflags[0].value #define NL gettyflags[1].value #define EP gettyflags[2].value #define EPset gettyflags[2].set #define OP gettyflags[3].value #define OPset gettyflags[3].set #define AP gettyflags[4].value #define APset gettyflags[4].set #define EC gettyflags[5].value #define CO gettyflags[6].value #define CB gettyflags[7].value #define CK gettyflags[8].value #define CE gettyflags[9].value #define PE gettyflags[10].value #define RW gettyflags[11].value #define XC gettyflags[12].value #define LC gettyflags[13].value #define UC gettyflags[14].value #define IG gettyflags[15].value #define PS gettyflags[16].value #define HC gettyflags[17].value #define UB gettyflags[18].value #define AB gettyflags[19].value #define DX gettyflags[20].value #define NP gettyflags[21].value #define NPset gettyflags[21].set #define MB gettyflags[22].value #define HW gettyflags[23].value #define NC gettyflags[24].value #define PL gettyflags[25].value Index: head/libexec/getty/init.c =================================================================== --- head/libexec/getty/init.c (revision 262135) +++ head/libexec/getty/init.c (revision 262136) @@ -1,154 +1,150 @@ /* * Copyright (c) 1983, 1993 * The Regents of the University of California. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #ifndef lint #if 0 static char sccsid[] = "@(#)from: init.c 8.1 (Berkeley) 6/4/93"; #endif static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ /* * Getty table initializations. * * Melbourne getty. */ #include #include "gettytab.h" #include "extern.h" #include "pathnames.h" static char loginmsg[] = "login: "; static char nullstr[] = ""; static char loginprg[] = _PATH_LOGIN; static char datefmt[] = "%+"; struct gettystrs gettystrs[] = { { "nx" }, /* next table */ { "cl" }, /* screen clear characters */ { "im" }, /* initial message */ { "lm", loginmsg }, /* login message */ { "er", &omode.c_cc[VERASE] }, /* erase character */ { "kl", &omode.c_cc[VKILL] }, /* kill character */ { "et", &omode.c_cc[VEOF] }, /* eof chatacter (eot) */ { "pc", nullstr }, /* pad character */ { "tt" }, /* terminal type */ { "ev" }, /* environment */ { "lo", loginprg }, /* login program */ { "hn", hostname }, /* host name */ { "he" }, /* host name edit */ { "in", &omode.c_cc[VINTR] }, /* interrupt char */ { "qu", &omode.c_cc[VQUIT] }, /* quit char */ { "xn", &omode.c_cc[VSTART] }, /* XON (start) char */ { "xf", &omode.c_cc[VSTOP] }, /* XOFF (stop) char */ { "bk", &omode.c_cc[VEOL] }, /* brk char (alt \n) */ { "su", &omode.c_cc[VSUSP] }, /* suspend char */ { "ds", &omode.c_cc[VDSUSP] }, /* delayed suspend */ { "rp", &omode.c_cc[VREPRINT] },/* reprint char */ { "fl", &omode.c_cc[VDISCARD] },/* flush output */ { "we", &omode.c_cc[VWERASE] }, /* word erase */ { "ln", &omode.c_cc[VLNEXT] }, /* literal next */ { "Lo" }, /* locale for strftime() */ { "pp" }, /* ppp login program */ { "if" }, /* sysv-like 'issue' filename */ { "ic" }, /* modem init-chat */ { "ac" }, /* modem answer-chat */ { "al" }, /* user to auto-login */ { "df", datefmt}, /* format for strftime() */ { 0 } }; struct gettynums gettynums[] = { { "is" }, /* input speed */ { "os" }, /* output speed */ { "sp" }, /* both speeds */ { "nd" }, /* newline delay */ { "cd" }, /* carriage-return delay */ { "td" }, /* tab delay */ { "fd" }, /* form-feed delay */ { "bd" }, /* backspace delay */ { "to" }, /* timeout */ { "f0" }, /* output flags */ { "f1" }, /* input flags */ { "f2" }, /* user mode flags */ { "pf" }, /* delay before flush at 1st prompt */ { "c0" }, /* output c_flags */ { "c1" }, /* input c_flags */ { "c2" }, /* user mode c_flags */ { "i0" }, /* output i_flags */ { "i1" }, /* input i_flags */ { "i2" }, /* user mode i_flags */ { "l0" }, /* output l_flags */ { "l1" }, /* input l_flags */ { "l2" }, /* user mode l_flags */ { "o0" }, /* output o_flags */ { "o1" }, /* input o_flags */ { "o2" }, /* user mode o_flags */ { "de" }, /* delay before sending 1st prompt */ { "rt" }, /* reset timeout */ { "ct" }, /* chat script timeout */ { "dc" }, /* debug chat script value */ { 0 } }; struct gettyflags gettyflags[] = { { "ht", 0 }, /* has tabs */ { "nl", 1 }, /* has newline char */ { "ep", 0 }, /* even parity */ { "op", 0 }, /* odd parity */ { "ap", 0 }, /* any parity */ { "ec", 1 }, /* no echo */ { "co", 0 }, /* console special */ { "cb", 0 }, /* crt backspace */ { "ck", 0 }, /* crt kill */ { "ce", 0 }, /* crt erase */ { "pe", 0 }, /* printer erase */ { "rw", 1 }, /* don't use raw */ { "xc", 1 }, /* don't ^X ctl chars */ { "lc", 0 }, /* terminal las lower case */ { "uc", 0 }, /* terminal has no lower case */ { "ig", 0 }, /* ignore garbage */ { "ps", 0 }, /* do port selector speed select */ { "hc", 1 }, /* don't set hangup on close */ { "ub", 0 }, /* unbuffered output */ { "ab", 0 }, /* auto-baud detect with '\r' */ { "dx", 0 }, /* set decctlq */ { "np", 0 }, /* no parity at all (8bit chars) */ { "mb", 0 }, /* do MDMBUF flow control */ { "hw", 0 }, /* do CTSRTS flow control */ { "nc", 0 }, /* set clocal (no carrier) */ { "pl", 0 }, /* use PPP instead of login(1) */ { 0 } }; Index: head/libexec/getty/main.c =================================================================== --- head/libexec/getty/main.c (revision 262135) +++ head/libexec/getty/main.c (revision 262136) @@ -1,818 +1,814 @@ /*- * Copyright (c) 1980, 1993 * The Regents of the University of California. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #ifndef lint static const char copyright[] = "@(#) Copyright (c) 1980, 1993\n\ The Regents of the University of California. All rights reserved.\n"; #endif /* not lint */ #ifndef lint #if 0 static char sccsid[] = "@(#)from: main.c 8.1 (Berkeley) 6/20/93"; #endif #endif /* not lint */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "gettytab.h" #include "extern.h" #include "pathnames.h" /* * Set the amount of running time that getty should accumulate * before deciding that something is wrong and exit. */ #define GETTY_TIMEOUT 60 /* seconds */ #undef CTRL #define CTRL(x) (x&037) /* defines for auto detection of incoming PPP calls (->PAP/CHAP) */ #define PPP_FRAME 0x7e /* PPP Framing character */ #define PPP_STATION 0xff /* "All Station" character */ #define PPP_ESCAPE 0x7d /* Escape Character */ #define PPP_CONTROL 0x03 /* PPP Control Field */ #define PPP_CONTROL_ESCAPED 0x23 /* PPP Control Field, escaped */ #define PPP_LCP_HI 0xc0 /* LCP protocol - high byte */ #define PPP_LCP_LOW 0x21 /* LCP protocol - low byte */ /* original mode; flags've been reset using values from */ struct termios omode; /* current mode */ struct termios tmode; int crmod, digit, lower, upper; char hostname[MAXHOSTNAMELEN]; char name[MAXLOGNAME*3]; char dev[] = _PATH_DEV; char ttyn[32]; #define OBUFSIZ 128 #define TABBUFSIZ 512 char defent[TABBUFSIZ]; char tabent[TABBUFSIZ]; const char *tname; char *env[128]; char partab[] = { 0001,0201,0201,0001,0201,0001,0001,0201, 0202,0004,0003,0205,0005,0206,0201,0001, 0201,0001,0001,0201,0001,0201,0201,0001, 0001,0201,0201,0001,0201,0001,0001,0201, 0200,0000,0000,0200,0000,0200,0200,0000, 0000,0200,0200,0000,0200,0000,0000,0200, 0000,0200,0200,0000,0200,0000,0000,0200, 0200,0000,0000,0200,0000,0200,0200,0000, 0200,0000,0000,0200,0000,0200,0200,0000, 0000,0200,0200,0000,0200,0000,0000,0200, 0000,0200,0200,0000,0200,0000,0000,0200, 0200,0000,0000,0200,0000,0200,0200,0000, 0000,0200,0200,0000,0200,0000,0000,0200, 0200,0000,0000,0200,0000,0200,0200,0000, 0200,0000,0000,0200,0000,0200,0200,0000, 0000,0200,0200,0000,0200,0000,0000,0201 }; #define ERASE tmode.c_cc[VERASE] #define KILL tmode.c_cc[VKILL] #define EOT tmode.c_cc[VEOF] #define puts Gputs static void defttymode(void); static void dingdong(int); static void dogettytab(void); static int getname(void); static void interrupt(int); static void oflush(void); static void prompt(void); static void putchr(int); static void putf(const char *); static void putpad(const char *); static void puts(const char *); static void timeoverrun(int); static char *getline(int); static void setttymode(int); static int opentty(const char *, int); jmp_buf timeout; static void dingdong(int signo __unused) { alarm(0); longjmp(timeout, 1); } jmp_buf intrupt; static void interrupt(int signo __unused) { longjmp(intrupt, 1); } /* * Action to take when getty is running too long. */ static void timeoverrun(int signo __unused) { syslog(LOG_ERR, "getty exiting due to excessive running time"); exit(1); } int main(int argc, char *argv[]) { extern char **environ; int first_sleep = 1, first_time = 1; struct rlimit limit; int rval; signal(SIGINT, SIG_IGN); signal(SIGQUIT, SIG_IGN); openlog("getty", LOG_ODELAY|LOG_CONS|LOG_PID, LOG_AUTH); gethostname(hostname, sizeof(hostname) - 1); hostname[sizeof(hostname) - 1] = '\0'; if (hostname[0] == '\0') strcpy(hostname, "Amnesiac"); /* * Limit running time to deal with broken or dead lines. */ (void)signal(SIGXCPU, timeoverrun); limit.rlim_max = RLIM_INFINITY; limit.rlim_cur = GETTY_TIMEOUT; (void)setrlimit(RLIMIT_CPU, &limit); gettable("default", defent); gendefaults(); tname = "default"; if (argc > 1) tname = argv[1]; /* * The following is a work around for vhangup interactions * which cause great problems getting window systems started. * If the tty line is "-", we do the old style getty presuming * that the file descriptors are already set up for us. * J. Gettys - MIT Project Athena. */ if (argc <= 2 || strcmp(argv[2], "-") == 0) strcpy(ttyn, ttyname(STDIN_FILENO)); else { strcpy(ttyn, dev); strncat(ttyn, argv[2], sizeof(ttyn)-sizeof(dev)); if (strcmp(argv[0], "+") != 0) { chown(ttyn, 0, 0); chmod(ttyn, 0600); revoke(ttyn); /* * Do the first scan through gettytab. * Terminal mode parameters will be wrong until * defttymode() called, but they're irrelevant for * the initial setup of the terminal device. */ dogettytab(); /* * Init or answer modem sequence has been specified. */ if (IC || AC) { if (!opentty(ttyn, O_RDWR|O_NONBLOCK)) exit(1); defttymode(); setttymode(1); } if (IC) { if (getty_chat(IC, CT, DC) > 0) { syslog(LOG_ERR, "modem init problem on %s", ttyn); (void)tcsetattr(STDIN_FILENO, TCSANOW, &tmode); exit(1); } } if (AC) { int i, rfds; struct timeval to; rfds = 1 << 0; /* FD_SET */ to.tv_sec = RT; to.tv_usec = 0; i = select(32, (fd_set*)&rfds, (fd_set*)NULL, (fd_set*)NULL, RT ? &to : NULL); if (i < 0) { syslog(LOG_ERR, "select %s: %m", ttyn); } else if (i == 0) { syslog(LOG_NOTICE, "recycle tty %s", ttyn); (void)tcsetattr(STDIN_FILENO, TCSANOW, &tmode); exit(0); /* recycle for init */ } i = getty_chat(AC, CT, DC); if (i > 0) { syslog(LOG_ERR, "modem answer problem on %s", ttyn); (void)tcsetattr(STDIN_FILENO, TCSANOW, &tmode); exit(1); } } else { /* maybe blocking open */ if (!opentty(ttyn, O_RDWR | (NC ? O_NONBLOCK : 0 ))) exit(1); } } } defttymode(); for (;;) { /* * if a delay was specified then sleep for that * number of seconds before writing the initial prompt */ if (first_sleep && DE) { sleep(DE); /* remove any noise */ (void)tcflush(STDIN_FILENO, TCIOFLUSH); } first_sleep = 0; setttymode(0); if (AB) { tname = autobaud(); dogettytab(); continue; } if (PS) { tname = portselector(); dogettytab(); continue; } if (CL && *CL) putpad(CL); edithost(HE); /* if this is the first time through this, and an issue file has been given, then send it */ if (first_time && IF) { int fd; if ((fd = open(IF, O_RDONLY)) != -1) { char * cp; while ((cp = getline(fd)) != NULL) { putf(cp); } close(fd); } } first_time = 0; if (IM && *IM && !(PL && PP)) putf(IM); if (setjmp(timeout)) { cfsetispeed(&tmode, B0); cfsetospeed(&tmode, B0); (void)tcsetattr(STDIN_FILENO, TCSANOW, &tmode); exit(1); } if (TO) { signal(SIGALRM, dingdong); alarm(TO); } rval = 0; if (AL) { const char *p = AL; char *q = name; while (*p && q < &name[sizeof name - 1]) { if (isupper(*p)) upper = 1; else if (islower(*p)) lower = 1; else if (isdigit(*p)) digit = 1; *q++ = *p++; } } else if (!(PL && PP)) rval = getname(); if (rval == 2 || (PL && PP)) { oflush(); alarm(0); limit.rlim_max = RLIM_INFINITY; limit.rlim_cur = RLIM_INFINITY; (void)setrlimit(RLIMIT_CPU, &limit); execle(PP, "ppplogin", ttyn, (char *) 0, env); syslog(LOG_ERR, "%s: %m", PP); exit(1); } else if (rval || AL) { int i; oflush(); alarm(0); signal(SIGALRM, SIG_DFL); if (name[0] == '\0') continue; if (name[0] == '-') { puts("user names may not start with '-'."); continue; } if (!(upper || lower || digit)) { if (AL) { syslog(LOG_ERR, "invalid auto-login name: %s", AL); exit(1); } else continue; } set_flags(2); if (crmod) { tmode.c_iflag |= ICRNL; tmode.c_oflag |= ONLCR; } #if REALLY_OLD_TTYS if (upper || UC) tmode.sg_flags |= LCASE; if (lower || LC) tmode.sg_flags &= ~LCASE; #endif if (tcsetattr(STDIN_FILENO, TCSANOW, &tmode) < 0) { syslog(LOG_ERR, "tcsetattr %s: %m", ttyn); exit(1); } signal(SIGINT, SIG_DFL); for (i = 0; environ[i] != (char *)0; i++) env[i] = environ[i]; makeenv(&env[i]); limit.rlim_max = RLIM_INFINITY; limit.rlim_cur = RLIM_INFINITY; (void)setrlimit(RLIMIT_CPU, &limit); execle(LO, "login", AL ? "-fp" : "-p", name, (char *) 0, env); syslog(LOG_ERR, "%s: %m", LO); exit(1); } alarm(0); signal(SIGALRM, SIG_DFL); signal(SIGINT, SIG_IGN); if (NX && *NX) { tname = NX; dogettytab(); } } } static int opentty(const char *tty, int flags) { int i; int failopenlogged = 0; while ((i = open(tty, flags)) == -1) { if (!failopenlogged) { syslog(LOG_ERR, "open %s: %m", tty); failopenlogged = 1; } sleep(60); } if (login_tty(i) < 0) { if (daemon(0,0) < 0) { syslog(LOG_ERR,"daemon: %m"); close(i); return 0; } if (login_tty(i) < 0) { syslog(LOG_ERR, "login_tty %s: %m", tty); close(i); return 0; } } return 1; } static void defttymode(void) { struct termios def; /* Start with default tty settings. */ if (tcgetattr(STDIN_FILENO, &tmode) < 0) { syslog(LOG_ERR, "tcgetattr %s: %m", ttyn); exit(1); } omode = tmode; /* fill c_cc for dogettytab() */ dogettytab(); /* * Don't rely on the driver too much, and initialize crucial * things according to . Avoid clobbering * the c_cc[] settings however, the console drivers might wish * to leave their idea of the preferred VERASE key value * there. */ cfmakesane(&def); tmode.c_iflag = def.c_iflag; tmode.c_oflag = def.c_oflag; tmode.c_lflag = def.c_lflag; tmode.c_cflag = def.c_cflag; if (NC) tmode.c_cflag |= CLOCAL; omode = tmode; } static void setttymode(int raw) { int off = 0; (void)tcflush(STDIN_FILENO, TCIOFLUSH); /* clear out the crap */ ioctl(STDIN_FILENO, FIONBIO, &off); /* turn off non-blocking mode */ ioctl(STDIN_FILENO, FIOASYNC, &off); /* ditto for async mode */ if (IS) cfsetispeed(&tmode, speed(IS)); else if (SP) cfsetispeed(&tmode, speed(SP)); if (OS) cfsetospeed(&tmode, speed(OS)); else if (SP) cfsetospeed(&tmode, speed(SP)); set_flags(0); setchars(); if (raw) cfmakeraw(&tmode); if (tcsetattr(STDIN_FILENO, TCSANOW, &tmode) < 0) { syslog(LOG_ERR, "tcsetattr %s: %m", ttyn); exit(1); } } static int getname(void) { int c; char *np; unsigned char cs; int ppp_state = 0; int ppp_connection = 0; /* * Interrupt may happen if we use CBREAK mode */ if (setjmp(intrupt)) { signal(SIGINT, SIG_IGN); return (0); } signal(SIGINT, interrupt); set_flags(1); prompt(); oflush(); if (PF > 0) { sleep(PF); PF = 0; } if (tcsetattr(STDIN_FILENO, TCSANOW, &tmode) < 0) { syslog(LOG_ERR, "%s: %m", ttyn); exit(1); } crmod = digit = lower = upper = 0; np = name; for (;;) { oflush(); if (read(STDIN_FILENO, &cs, 1) <= 0) exit(0); if ((c = cs&0177) == 0) return (0); /* PPP detection state machine.. Look for sequences: PPP_FRAME, PPP_STATION, PPP_ESCAPE, PPP_CONTROL_ESCAPED or PPP_FRAME, PPP_STATION, PPP_CONTROL (deviant from RFC) See RFC1662. Derived from code from Michael Hancock, and Erik 'PPP' Olson, */ if (PP && (cs == PPP_FRAME)) { ppp_state = 1; } else if (ppp_state == 1 && cs == PPP_STATION) { ppp_state = 2; } else if (ppp_state == 2 && cs == PPP_ESCAPE) { ppp_state = 3; } else if ((ppp_state == 2 && cs == PPP_CONTROL) || (ppp_state == 3 && cs == PPP_CONTROL_ESCAPED)) { ppp_state = 4; } else if (ppp_state == 4 && cs == PPP_LCP_HI) { ppp_state = 5; } else if (ppp_state == 5 && cs == PPP_LCP_LOW) { ppp_connection = 1; break; } else { ppp_state = 0; } if (c == EOT || c == CTRL('d')) exit(0); if (c == '\r' || c == '\n' || np >= &name[sizeof name-1]) { putf("\r\n"); break; } if (islower(c)) lower = 1; else if (isupper(c)) upper = 1; else if (c == ERASE || c == '\b' || c == 0177) { if (np > name) { np--; if (cfgetospeed(&tmode) >= 1200) puts("\b \b"); else putchr(cs); } continue; } else if (c == KILL || c == CTRL('u')) { putchr('\r'); if (cfgetospeed(&tmode) < 1200) putchr('\n'); /* this is the way they do it down under ... */ else if (np > name) puts(" \r"); prompt(); digit = lower = upper = 0; np = name; continue; } else if (isdigit(c)) digit = 1; if (IG && (c <= ' ' || c > 0176)) continue; *np++ = c; putchr(cs); } signal(SIGINT, SIG_IGN); *np = 0; if (c == '\r') crmod = 1; if ((upper && !lower && !LC) || UC) for (np = name; *np; np++) if (isupper(*np)) *np = tolower(*np); return (1 + ppp_connection); } static void putpad(const char *s) { int pad = 0; speed_t ospeed = cfgetospeed(&tmode); if (isdigit(*s)) { while (isdigit(*s)) { pad *= 10; pad += *s++ - '0'; } pad *= 10; if (*s == '.' && isdigit(s[1])) { pad += s[1] - '0'; s += 2; } } puts(s); /* * If no delay needed, or output speed is * not comprehensible, then don't try to delay. */ if (pad == 0 || ospeed <= 0) return; /* * Round up by a half a character frame, and then do the delay. * Too bad there are no user program accessible programmed delays. * Transmitting pad characters slows many terminals down and also * loads the system. */ pad = (pad * ospeed + 50000) / 100000; while (pad--) putchr(*PC); } static void puts(const char *s) { while (*s) putchr(*s++); } char outbuf[OBUFSIZ]; int obufcnt = 0; static void putchr(int cc) { char c; c = cc; if (!NP) { c |= partab[c&0177] & 0200; if (OP) c ^= 0200; } if (!UB) { outbuf[obufcnt++] = c; if (obufcnt >= OBUFSIZ) oflush(); } else write(STDOUT_FILENO, &c, 1); } static void oflush(void) { if (obufcnt) write(STDOUT_FILENO, outbuf, obufcnt); obufcnt = 0; } static void prompt(void) { putf(LM); if (CO) putchr('\n'); } static char * getline(int fd) { int i = 0; static char linebuf[512]; /* * This is certainly slow, but it avoids having to include * stdio.h unnecessarily. Issue files should be small anyway. */ while (i < (sizeof linebuf - 3) && read(fd, linebuf+i, 1)==1) { if (linebuf[i] == '\n') { /* Don't rely on newline mode, assume raw */ linebuf[i++] = '\r'; linebuf[i++] = '\n'; linebuf[i] = '\0'; return linebuf; } ++i; } linebuf[i] = '\0'; return i ? linebuf : 0; } static void putf(const char *cp) { extern char editedhost[]; time_t t; char *slash, db[100]; static struct utsname kerninfo; if (!*kerninfo.sysname) uname(&kerninfo); while (*cp) { if (*cp != '%') { putchr(*cp++); continue; } switch (*++cp) { case 't': slash = strrchr(ttyn, '/'); if (slash == (char *) 0) puts(ttyn); else puts(&slash[1]); break; case 'h': puts(editedhost); break; case 'd': { t = (time_t)0; (void)time(&t); if (Lo) (void)setlocale(LC_TIME, Lo); (void)strftime(db, sizeof(db), DF, localtime(&t)); puts(db); break; case 's': puts(kerninfo.sysname); break; case 'm': puts(kerninfo.machine); break; case 'r': puts(kerninfo.release); break; case 'v': puts(kerninfo.version); break; } case '%': putchr('%'); break; } cp++; } } /* * Read a gettytab database entry and perform necessary quirks. */ static void dogettytab(void) { /* Read the database entry. */ gettable(tname, tabent); /* * Avoid inheriting the parity values from the default entry * if any of them is set in the current entry. * Mixing different parity settings is unreasonable. */ if (OPset || EPset || APset || NPset) OPset = EPset = APset = NPset = 1; /* Fill in default values for unset capabilities. */ setdefaults(); } Index: head/libexec/getty/pathnames.h =================================================================== --- head/libexec/getty/pathnames.h (revision 262135) +++ head/libexec/getty/pathnames.h (revision 262136) @@ -1,40 +1,36 @@ /* * Copyright (c) 1989, 1993 * The Regents of the University of California. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. * * from: @(#)pathnames.h 8.1 (Berkeley) 6/4/93 * $FreeBSD$ */ #include #define _PATH_GETTYTAB "/etc/gettytab" #define _PATH_LOGIN "/usr/bin/login" Index: head/libexec/getty/subr.c =================================================================== --- head/libexec/getty/subr.c (revision 262135) +++ head/libexec/getty/subr.c (revision 262136) @@ -1,697 +1,693 @@ /* * Copyright (c) 1983, 1993 * The Regents of the University of California. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #ifndef lint #if 0 static char sccsid[] = "@(#)from: subr.c 8.1 (Berkeley) 6/4/93"; #endif static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ /* * Melbourne getty. */ #ifdef DEBUG #include #endif #include #include #include #include #include #include #include #include #include "gettytab.h" #include "pathnames.h" #include "extern.h" /* * Get a table entry. */ void gettable(const char *name, char *buf) { struct gettystrs *sp; struct gettynums *np; struct gettyflags *fp; long n; int l; char *p; char *msg = NULL; const char *dba[2]; static int firsttime = 1; dba[0] = _PATH_GETTYTAB; dba[1] = 0; if (firsttime) { /* * we need to strdup() anything in the strings array * initially in order to simplify things later */ for (sp = gettystrs; sp->field; sp++) if (sp->value != NULL) { /* handle these ones more carefully */ if (sp >= &gettystrs[4] && sp <= &gettystrs[6]) l = 2; else l = strlen(sp->value) + 1; if ((p = malloc(l)) != NULL) { strncpy(p, sp->value, l); p[l-1] = '\0'; } /* * replace, even if NULL, else we'll * have problems with free()ing static mem */ sp->value = p; } firsttime = 0; } switch (cgetent(&buf, (char **)dba, (char *)name)) { case 1: msg = "%s: couldn't resolve 'tc=' in gettytab '%s'"; case 0: break; case -1: msg = "%s: unknown gettytab entry '%s'"; break; case -2: msg = "%s: retrieving gettytab entry '%s': %m"; break; case -3: msg = "%s: recursive 'tc=' reference gettytab entry '%s'"; break; default: msg = "%s: unexpected cgetent() error for entry '%s'"; break; } if (msg != NULL) { syslog(LOG_ERR, msg, "getty", name); return; } for (sp = gettystrs; sp->field; sp++) { if ((l = cgetstr(buf, (char*)sp->field, &p)) >= 0) { if (sp->value) { /* prefer existing value */ if (strcmp(p, sp->value) != 0) free(sp->value); else { free(p); p = sp->value; } } sp->value = p; } else if (l == -1) { free(sp->value); sp->value = NULL; } } for (np = gettynums; np->field; np++) { if (cgetnum(buf, (char*)np->field, &n) == -1) np->set = 0; else { np->set = 1; np->value = n; } } for (fp = gettyflags; fp->field; fp++) { if (cgetcap(buf, (char *)fp->field, ':') == NULL) fp->set = 0; else { fp->set = 1; fp->value = 1 ^ fp->invrt; } } #ifdef DEBUG printf("name=\"%s\", buf=\"%s\"\r\n", name, buf); for (sp = gettystrs; sp->field; sp++) printf("cgetstr: %s=%s\r\n", sp->field, sp->value); for (np = gettynums; np->field; np++) printf("cgetnum: %s=%d\r\n", np->field, np->value); for (fp = gettyflags; fp->field; fp++) printf("cgetflags: %s='%c' set='%c'\r\n", fp->field, fp->value + '0', fp->set + '0'); #endif /* DEBUG */ } void gendefaults(void) { struct gettystrs *sp; struct gettynums *np; struct gettyflags *fp; for (sp = gettystrs; sp->field; sp++) if (sp->value) sp->defalt = strdup(sp->value); for (np = gettynums; np->field; np++) if (np->set) np->defalt = np->value; for (fp = gettyflags; fp->field; fp++) if (fp->set) fp->defalt = fp->value; else fp->defalt = fp->invrt; } void setdefaults(void) { struct gettystrs *sp; struct gettynums *np; struct gettyflags *fp; for (sp = gettystrs; sp->field; sp++) if (!sp->value) sp->value = !sp->defalt ? sp->defalt : strdup(sp->defalt); for (np = gettynums; np->field; np++) if (!np->set) np->value = np->defalt; for (fp = gettyflags; fp->field; fp++) if (!fp->set) fp->value = fp->defalt; } static char ** charnames[] = { &ER, &KL, &IN, &QU, &XN, &XF, &ET, &BK, &SU, &DS, &RP, &FL, &WE, &LN, 0 }; static char * charvars[] = { &tmode.c_cc[VERASE], &tmode.c_cc[VKILL], &tmode.c_cc[VINTR], &tmode.c_cc[VQUIT], &tmode.c_cc[VSTART], &tmode.c_cc[VSTOP], &tmode.c_cc[VEOF], &tmode.c_cc[VEOL], &tmode.c_cc[VSUSP], &tmode.c_cc[VDSUSP], &tmode.c_cc[VREPRINT], &tmode.c_cc[VDISCARD], &tmode.c_cc[VWERASE], &tmode.c_cc[VLNEXT], 0 }; void setchars(void) { int i; const char *p; for (i = 0; charnames[i]; i++) { p = *charnames[i]; if (p && *p) *charvars[i] = *p; else *charvars[i] = _POSIX_VDISABLE; } } /* Macros to clear/set/test flags. */ #define SET(t, f) (t) |= (f) #define CLR(t, f) (t) &= ~(f) #define ISSET(t, f) ((t) & (f)) void set_flags(int n) { tcflag_t iflag, oflag, cflag, lflag; switch (n) { case 0: if (C0set && I0set && L0set && O0set) { tmode.c_cflag = C0; tmode.c_iflag = I0; tmode.c_lflag = L0; tmode.c_oflag = O0; return; } break; case 1: if (C1set && I1set && L1set && O1set) { tmode.c_cflag = C1; tmode.c_iflag = I1; tmode.c_lflag = L1; tmode.c_oflag = O1; return; } break; default: if (C2set && I2set && L2set && O2set) { tmode.c_cflag = C2; tmode.c_iflag = I2; tmode.c_lflag = L2; tmode.c_oflag = O2; return; } break; } iflag = omode.c_iflag; oflag = omode.c_oflag; cflag = omode.c_cflag; lflag = omode.c_lflag; if (NP) { CLR(cflag, CSIZE|PARENB); SET(cflag, CS8); CLR(iflag, ISTRIP|INPCK|IGNPAR); } else if (AP || EP || OP) { CLR(cflag, CSIZE); SET(cflag, CS7|PARENB); SET(iflag, ISTRIP); if (OP && !EP) { SET(iflag, INPCK|IGNPAR); SET(cflag, PARODD); if (AP) CLR(iflag, INPCK); } else if (EP && !OP) { SET(iflag, INPCK|IGNPAR); CLR(cflag, PARODD); if (AP) CLR(iflag, INPCK); } else if (AP || (EP && OP)) { CLR(iflag, INPCK|IGNPAR); CLR(cflag, PARODD); } } /* else, leave as is */ #if 0 if (UC) f |= LCASE; #endif if (HC) SET(cflag, HUPCL); else CLR(cflag, HUPCL); if (MB) SET(cflag, MDMBUF); else CLR(cflag, MDMBUF); if (HW) SET(cflag, CRTSCTS); else CLR(cflag, CRTSCTS); if (NL) { SET(iflag, ICRNL); SET(oflag, ONLCR|OPOST); } else { CLR(iflag, ICRNL); CLR(oflag, ONLCR); } if (!HT) SET(oflag, OXTABS|OPOST); else CLR(oflag, OXTABS); #ifdef XXX_DELAY SET(f, delaybits()); #endif if (n == 1) { /* read mode flags */ if (RW) { iflag = 0; CLR(oflag, OPOST); CLR(cflag, CSIZE|PARENB); SET(cflag, CS8); lflag = 0; } else { CLR(lflag, ICANON); } goto out; } if (n == 0) goto out; #if 0 if (CB) SET(f, CRTBS); #endif if (CE) SET(lflag, ECHOE); else CLR(lflag, ECHOE); if (CK) SET(lflag, ECHOKE); else CLR(lflag, ECHOKE); if (PE) SET(lflag, ECHOPRT); else CLR(lflag, ECHOPRT); if (EC) SET(lflag, ECHO); else CLR(lflag, ECHO); if (XC) SET(lflag, ECHOCTL); else CLR(lflag, ECHOCTL); if (DX) SET(lflag, IXANY); else CLR(lflag, IXANY); out: tmode.c_iflag = iflag; tmode.c_oflag = oflag; tmode.c_cflag = cflag; tmode.c_lflag = lflag; } #ifdef XXX_DELAY struct delayval { unsigned delay; /* delay in ms */ int bits; }; /* * below are random guesses, I can't be bothered checking */ struct delayval crdelay[] = { { 1, CR1 }, { 2, CR2 }, { 3, CR3 }, { 83, CR1 }, { 166, CR2 }, { 0, CR3 }, }; struct delayval nldelay[] = { { 1, NL1 }, /* special, calculated */ { 2, NL2 }, { 3, NL3 }, { 100, NL2 }, { 0, NL3 }, }; struct delayval bsdelay[] = { { 1, BS1 }, { 0, 0 }, }; struct delayval ffdelay[] = { { 1, FF1 }, { 1750, FF1 }, { 0, FF1 }, }; struct delayval tbdelay[] = { { 1, TAB1 }, { 2, TAB2 }, { 3, XTABS }, /* this is expand tabs */ { 100, TAB1 }, { 0, TAB2 }, }; int delaybits(void) { int f; f = adelay(CD, crdelay); f |= adelay(ND, nldelay); f |= adelay(FD, ffdelay); f |= adelay(TD, tbdelay); f |= adelay(BD, bsdelay); return (f); } int adelay(int ms, struct delayval *dp) { if (ms == 0) return (0); while (dp->delay && ms > dp->delay) dp++; return (dp->bits); } #endif char editedhost[MAXHOSTNAMELEN]; void edithost(const char *pat) { const char *host = HN; char *res = editedhost; if (!pat) pat = ""; while (*pat) { switch (*pat) { case '#': if (*host) host++; break; case '@': if (*host) *res++ = *host++; break; default: *res++ = *pat; break; } if (res == &editedhost[sizeof editedhost - 1]) { *res = '\0'; return; } pat++; } if (*host) strncpy(res, host, sizeof editedhost - (res - editedhost) - 1); else *res = '\0'; editedhost[sizeof editedhost - 1] = '\0'; } static struct speedtab { int speed; int uxname; } speedtab[] = { { 50, B50 }, { 75, B75 }, { 110, B110 }, { 134, B134 }, { 150, B150 }, { 200, B200 }, { 300, B300 }, { 600, B600 }, { 1200, B1200 }, { 1800, B1800 }, { 2400, B2400 }, { 4800, B4800 }, { 9600, B9600 }, { 19200, EXTA }, { 19, EXTA }, /* for people who say 19.2K */ { 38400, EXTB }, { 38, EXTB }, { 7200, EXTB }, /* alternative */ { 57600, B57600 }, { 115200, B115200 }, { 230400, B230400 }, { 0 } }; int speed(int val) { struct speedtab *sp; if (val <= B230400) return (val); for (sp = speedtab; sp->speed; sp++) if (sp->speed == val) return (sp->uxname); return (B300); /* default in impossible cases */ } void makeenv(char *env[]) { static char termbuf[128] = "TERM="; char *p, *q; char **ep; ep = env; if (TT && *TT) { strlcat(termbuf, TT, sizeof(termbuf)); *ep++ = termbuf; } if ((p = EV)) { q = p; while ((q = strchr(q, ','))) { *q++ = '\0'; *ep++ = p; p = q; } if (*p) *ep++ = p; } *ep = (char *)0; } /* * This speed select mechanism is written for the Develcon DATASWITCH. * The Develcon sends a string of the form "B{speed}\n" at a predefined * baud rate. This string indicates the user's actual speed. * The routine below returns the terminal type mapped from derived speed. */ struct portselect { const char *ps_baud; const char *ps_type; } portspeeds[] = { { "B110", "std.110" }, { "B134", "std.134" }, { "B150", "std.150" }, { "B300", "std.300" }, { "B600", "std.600" }, { "B1200", "std.1200" }, { "B2400", "std.2400" }, { "B4800", "std.4800" }, { "B9600", "std.9600" }, { "B19200", "std.19200" }, { 0 } }; const char * portselector(void) { char c, baud[20]; const char *type = "default"; struct portselect *ps; int len; alarm(5*60); for (len = 0; len < sizeof (baud) - 1; len++) { if (read(STDIN_FILENO, &c, 1) <= 0) break; c &= 0177; if (c == '\n' || c == '\r') break; if (c == 'B') len = 0; /* in case of leading garbage */ baud[len] = c; } baud[len] = '\0'; for (ps = portspeeds; ps->ps_baud; ps++) if (strcmp(ps->ps_baud, baud) == 0) { type = ps->ps_type; break; } sleep(2); /* wait for connection to complete */ return (type); } /* * This auto-baud speed select mechanism is written for the Micom 600 * portselector. Selection is done by looking at how the character '\r' * is garbled at the different speeds. */ const char * autobaud(void) { int rfds; struct timeval timeout; char c; const char *type = "9600-baud"; (void)tcflush(0, TCIOFLUSH); rfds = 1 << 0; timeout.tv_sec = 5; timeout.tv_usec = 0; if (select(32, (fd_set *)&rfds, (fd_set *)NULL, (fd_set *)NULL, &timeout) <= 0) return (type); if (read(STDIN_FILENO, &c, sizeof(char)) != sizeof(char)) return (type); timeout.tv_sec = 0; timeout.tv_usec = 20; (void) select(32, (fd_set *)NULL, (fd_set *)NULL, (fd_set *)NULL, &timeout); (void)tcflush(0, TCIOFLUSH); switch (c & 0377) { case 0200: /* 300-baud */ type = "300-baud"; break; case 0346: /* 1200-baud */ type = "1200-baud"; break; case 015: /* 2400-baud */ case 0215: type = "2400-baud"; break; default: /* 4800-baud */ type = "4800-baud"; break; case 0377: /* 9600-baud */ type = "9600-baud"; break; } return (type); } Index: head/libexec/getty/ttys.5 =================================================================== --- head/libexec/getty/ttys.5 (revision 262135) +++ head/libexec/getty/ttys.5 (revision 262136) @@ -1,175 +1,171 @@ .\" Copyright (c) 1985, 1991, 1993 .\" The Regents of the University of California. 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. -.\" 3. All advertising materials mentioning features or use of this software -.\" must display the following acknowledgement: -.\" This product includes software developed by the University of -.\" California, Berkeley and its contributors. -.\" 4. Neither the name of the University nor the names of its contributors +.\" 3. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. .\" .\" from: @(#)ttys.5 8.1 (Berkeley) 6/4/93 .\" $FreeBSD$ .\" " .Dd May 27, 2005 .Dt TTYS 5 .Os .Sh NAME .Nm ttys .Nd terminal initialization information .Sh DESCRIPTION The file .Nm contains information that is used by various routines to initialize and control the use of terminal special files. This information is read with the .Xr getttyent 3 library routines. There is one line in the .Nm file per special device file. Fields are separated by tabs and/or spaces. Fields comprised of more than one word should be enclosed in double quotes (``"''). Blank lines and comments may appear anywhere in the file; comments are delimited by hash marks (``#'') and new lines. Any unspecified fields will default to null. .Pp The first field is normally the name of the terminal special file as it is found in .Pa /dev . However, it can be any arbitrary string when the associated command is not related to a tty. .Pp The second field of the file is the command to execute for the line, usually .Xr getty 8 , which initializes and opens the line, setting the speed, waiting for a user name and executing the .Xr login 1 program. It can be, however, any desired command, for example the start up for a window system terminal emulator or some other daemon process, and can contain multiple words if quoted. .Pp The third field is the type of terminal usually connected to that tty line, normally the one found in the .Xr termcap 5 data base file. The environment variable .Ev TERM is initialized with the value by either .Xr getty 8 or .Xr login 1 . .Pp The remaining fields set flags in the .Fa ty_status entry (see .Xr getttyent 3 ) , specify a window system process that .Xr init 8 will maintain for the terminal line, optionally determine the type of tty (whether dialin, network or otherwise), or specify a tty group name that allows the login class database (see .Xr login.conf 5 ) to refer to many ttys as a group, to selectively allow or deny access or enable or disable accounting facilities for ttys as a group. .Pp As flag values, the strings ``on'' and ``off'' specify that .Xr init 8 should (should not) execute the command given in the second field. ``onifconsole'' will cause this line to be enabled if and only if it is an active kernel console device (it is equivalent to ``on'' in this case). The flag ``secure'' (if the console is enabled) allows users with a uid of 0 to login on this line. The flag ``dialin'' indicates that a tty entry describes a dialin line, and ``network'' indicates that a tty entry provides a network connection. Either of these strings may also be specified in the terminal type field. The string ``window='' may be followed by a quoted command string which .Xr init 8 will execute .Em before starting the command specified by the second field. .Pp The string ``group='' may be followed by a group name comprised of alphanumeric characters that can be used by .Xr login.conf 5 to refer to many tty lines as a group to enable or disable access and accounting facilities. If no group is specified, then the tty becomes a member of the group "none". For backwards compatibility, the ``group='' should appear last on the line, immediately before the optional comment. .Pp Both the second field and any command specified with ``window='' will be split into words and executed using .Xr execve 2 . Words are separated by any combinations of tabs and spaces. Arguments containing whitespace should be enclosed in single quotes .Pq Li ' . Note that no shell-style globbing or other variable substitution occurs. .Sh FILES .Bl -tag -width /etc/ttys -compact .It Pa /etc/ttys .El .Sh EXAMPLES .Bd -literal # root login on console at 1200 baud console "/usr/libexec/getty std.1200" vt100 on secure # dialup at 1200 baud, no root logins ttyd0 "/usr/libexec/getty d1200" dialup on group=dialup # 555-1234 # Mike's terminal: hp2621 ttyh0 "/usr/libexec/getty std.9600" hp2621-nl on group=dialup # 457 Evans # John's terminal: vt100 ttyh1 "/usr/libexec/getty std.9600" vt100 on group=dialup # 459 Evans # terminal emulate/window system ttyv0 "/usr/local/bin/xterm -display :0" xterm on window="/usr/local/bin/X :0" # Network pseudo ttys -- don't enable getty ttyp0 none network group=pty ttyp1 none network off group=pty .Ed .Sh SEE ALSO .Xr login 1 , .Xr getttyent 3 , .Xr gettytab 5 , .Xr login.conf 5 , .Xr termcap 5 , .Xr getty 8 , .Xr init 8 .\".Xr init 8 , .\".Xr ttyflags 8 .Sh HISTORY A .Nm file appeared in .At v6 . Index: head/libexec/mknetid/parse_group.c =================================================================== --- head/libexec/mknetid/parse_group.c (revision 262135) +++ head/libexec/mknetid/parse_group.c (revision 262136) @@ -1,161 +1,157 @@ /* * Copyright (c) 1989, 1993 * The Regents of the University of California. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #ifndef lint #if 0 static const char sccsid[] = "@(#)getgrent.c 8.2 (Berkeley) 3/21/94"; #endif static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ /* * This is a slightly modified chunk of getgrent(3). All the YP support * and unneeded functions have been stripped out. */ #include #include #include #include #include FILE *_gr_fp; static struct group _gr_group; static int _gr_stayopen; static int grscan(int, int); static int start_gr(void); #define MAXGRP 200 static char *members[MAXGRP]; #define MAXLINELENGTH 1024 static char line[MAXLINELENGTH]; struct group * _getgrent(void) { if (!_gr_fp && !start_gr()) { return NULL; } if (!grscan(0, 0)) return(NULL); return(&_gr_group); } static int start_gr(void) { return 1; } int _setgroupent(int stayopen) { if (!start_gr()) return(0); _gr_stayopen = stayopen; return(1); } int _setgrent(void) { return(_setgroupent(0)); } void _endgrent(void) { if (_gr_fp) { (void)fclose(_gr_fp); _gr_fp = NULL; } } static int grscan(int search, int gid) { char *cp, **m; char *bp; for (;;) { if (!fgets(line, sizeof(line), _gr_fp)) return(0); bp = line; /* skip lines that are too big */ if (!strchr(line, '\n')) { int ch; while ((ch = getc(_gr_fp)) != '\n' && ch != EOF) ; continue; } if ((_gr_group.gr_name = strsep(&bp, ":\n")) == NULL) break; if (_gr_group.gr_name[0] == '+') continue; if ((_gr_group.gr_passwd = strsep(&bp, ":\n")) == NULL) break; if (!(cp = strsep(&bp, ":\n"))) continue; _gr_group.gr_gid = atoi(cp); if (search && _gr_group.gr_gid != gid) continue; cp = NULL; if (bp == NULL) /* !! Must check for this! */ break; for (m = _gr_group.gr_mem = members;; bp++) { if (m == &members[MAXGRP - 1]) break; if (*bp == ',') { if (cp) { *bp = '\0'; *m++ = cp; cp = NULL; } } else if (*bp == '\0' || *bp == '\n' || *bp == ' ') { if (cp) { *bp = '\0'; *m++ = cp; } break; } else if (cp == NULL) cp = bp; } *m = NULL; return(1); } /* NOTREACHED */ return (0); } Index: head/libexec/rbootd/bpf.c =================================================================== --- head/libexec/rbootd/bpf.c (revision 262135) +++ head/libexec/rbootd/bpf.c (revision 262136) @@ -1,410 +1,406 @@ /* * Copyright (c) 1988, 1992 The University of Utah and the Center * for Software Science (CSS). * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * the Center for Software Science of the University of Utah Computer * Science Department. CSS requests users of this software to return * to css-dist@cs.utah.edu any improvements that they make and grant * CSS redistribution rights. * * 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. * * from: @(#)bpf.c 8.1 (Berkeley) 6/4/93 * * From: Utah Hdr: bpf.c 3.1 92/07/06 * Author: Jeff Forys, University of Utah CSS */ #ifndef lint #if 0 static const char sccsid[] = "@(#)bpf.c 8.1 (Berkeley) 6/4/93"; #endif static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "defs.h" #include "pathnames.h" static int BpfFd = -1; static unsigned BpfLen = 0; static u_int8_t *BpfPkt = NULL; /* ** BpfOpen -- Open and initialize a BPF device. ** ** Parameters: ** None. ** ** Returns: ** File descriptor of opened BPF device (for select() etc). ** ** Side Effects: ** If an error is encountered, the program terminates here. */ int BpfOpen(void) { struct ifreq ifr; char bpfdev[32]; int n = 0; /* * Open the first available BPF device. */ do { (void) sprintf(bpfdev, _PATH_BPF, n++); BpfFd = open(bpfdev, O_RDWR); } while (BpfFd < 0 && (errno == EBUSY || errno == EPERM)); if (BpfFd < 0) { syslog(LOG_ERR, "bpf: no available devices: %m"); Exit(0); } /* * Set interface name for bpf device, get data link layer * type and make sure it's type Ethernet. */ (void) strncpy(ifr.ifr_name, IntfName, sizeof(ifr.ifr_name)); if (ioctl(BpfFd, BIOCSETIF, (caddr_t)&ifr) < 0) { syslog(LOG_ERR, "bpf: ioctl(BIOCSETIF,%s): %m", IntfName); Exit(0); } /* * Make sure we are dealing with an Ethernet device. */ if (ioctl(BpfFd, BIOCGDLT, (caddr_t)&n) < 0) { syslog(LOG_ERR, "bpf: ioctl(BIOCGDLT): %m"); Exit(0); } if (n != DLT_EN10MB) { syslog(LOG_ERR,"bpf: %s: data-link type %d unsupported", IntfName, n); Exit(0); } /* * On read(), return packets immediately (do not buffer them). */ n = 1; if (ioctl(BpfFd, BIOCIMMEDIATE, (caddr_t)&n) < 0) { syslog(LOG_ERR, "bpf: ioctl(BIOCIMMEDIATE): %m"); Exit(0); } /* * Try to enable the chip/driver's multicast address filter to * grab our RMP address. If this fails, try promiscuous mode. * If this fails, there's no way we are going to get any RMP * packets so just exit here. */ #ifdef MSG_EOR ifr.ifr_addr.sa_len = RMP_ADDRLEN + 2; #endif ifr.ifr_addr.sa_family = AF_UNSPEC; memmove((char *)&ifr.ifr_addr.sa_data[0], &RmpMcastAddr[0], RMP_ADDRLEN); if (ioctl(BpfFd, BIOCPROMISC, (caddr_t)0) < 0) { syslog(LOG_ERR, "bpf: can't set promiscuous mode: %m"); Exit(0); } /* * Ask BPF how much buffer space it requires and allocate one. */ if (ioctl(BpfFd, BIOCGBLEN, (caddr_t)&BpfLen) < 0) { syslog(LOG_ERR, "bpf: ioctl(BIOCGBLEN): %m"); Exit(0); } if (BpfPkt == NULL) BpfPkt = (u_int8_t *)malloc(BpfLen); if (BpfPkt == NULL) { syslog(LOG_ERR, "bpf: out of memory (%u bytes for bpfpkt)", BpfLen); Exit(0); } /* * Write a little program to snarf RMP Boot packets and stuff * it down BPF's throat (i.e. set up the packet filter). */ { #define RMP ((struct rmp_packet *)0) static struct bpf_insn bpf_insn[] = { { BPF_LD|BPF_B|BPF_ABS, 0, 0, (long)&RMP->hp_llc.dsap }, { BPF_JMP|BPF_JEQ|BPF_K, 0, 5, IEEE_DSAP_HP }, { BPF_LD|BPF_H|BPF_ABS, 0, 0, (long)&RMP->hp_llc.cntrl }, { BPF_JMP|BPF_JEQ|BPF_K, 0, 3, IEEE_CNTL_HP }, { BPF_LD|BPF_H|BPF_ABS, 0, 0, (long)&RMP->hp_llc.dxsap }, { BPF_JMP|BPF_JEQ|BPF_K, 0, 1, HPEXT_DXSAP }, { BPF_RET|BPF_K, 0, 0, RMP_MAX_PACKET }, { BPF_RET|BPF_K, 0, 0, 0x0 } }; #undef RMP static struct bpf_program bpf_pgm = { sizeof(bpf_insn)/sizeof(bpf_insn[0]), bpf_insn }; if (ioctl(BpfFd, BIOCSETF, (caddr_t)&bpf_pgm) < 0) { syslog(LOG_ERR, "bpf: ioctl(BIOCSETF): %m"); Exit(0); } } return(BpfFd); } /* ** BPF GetIntfName -- Return the name of a network interface attached to ** the system, or 0 if none can be found. The interface ** must be configured up; the lowest unit number is ** preferred; loopback is ignored. ** ** Parameters: ** errmsg - if no network interface found, *errmsg explains why. ** ** Returns: ** A (static) pointer to interface name, or NULL on error. ** ** Side Effects: ** None. */ char * BpfGetIntfName(char **errmsg) { struct ifreq ibuf[8], *ifrp, *ifend, *mp; struct ifconf ifc; int fd; int minunit, n; char *cp; static char device[sizeof(ifrp->ifr_name)]; static char errbuf[128] = "No Error!"; if (errmsg != NULL) *errmsg = errbuf; if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0) { (void) strcpy(errbuf, "bpf: socket: %m"); return(NULL); } ifc.ifc_len = sizeof ibuf; ifc.ifc_buf = (caddr_t)ibuf; if (ioctl(fd, SIOCGIFCONF, (char *)&ifc) < 0 || ifc.ifc_len < sizeof(struct ifreq)) { (void) strcpy(errbuf, "bpf: ioctl(SIOCGIFCONF): %m"); return(NULL); } ifrp = ibuf; ifend = (struct ifreq *)((char *)ibuf + ifc.ifc_len); mp = 0; minunit = 666; for (; ifrp < ifend; ++ifrp) { if (ioctl(fd, SIOCGIFFLAGS, (char *)ifrp) < 0) { (void) strcpy(errbuf, "bpf: ioctl(SIOCGIFFLAGS): %m"); return(NULL); } /* * If interface is down or this is the loopback interface, * ignore it. */ if ((ifrp->ifr_flags & IFF_UP) == 0 || #ifdef IFF_LOOPBACK (ifrp->ifr_flags & IFF_LOOPBACK)) #else (strcmp(ifrp->ifr_name, "lo0") == 0)) #endif continue; for (cp = ifrp->ifr_name; !isdigit(*cp); ++cp) ; n = atoi(cp); if (n < minunit) { minunit = n; mp = ifrp; } } (void) close(fd); if (mp == 0) { (void) strcpy(errbuf, "bpf: no interfaces found"); return(NULL); } (void) strcpy(device, mp->ifr_name); return(device); } /* ** BpfRead -- Read packets from a BPF device and fill in `rconn'. ** ** Parameters: ** rconn - filled in with next packet. ** doread - is True if we can issue a read() syscall. ** ** Returns: ** True if `rconn' contains a new packet, False otherwise. ** ** Side Effects: ** None. */ int BpfRead(RMPCONN *rconn, int doread) { int datlen, caplen, hdrlen; static u_int8_t *bp = NULL, *ep = NULL; int cc; /* * The read() may block, or it may return one or more packets. * We let the caller decide whether or not we can issue a read(). */ if (doread) { if ((cc = read(BpfFd, (char *)BpfPkt, (int)BpfLen)) < 0) { syslog(LOG_ERR, "bpf: read: %m"); return(0); } else { bp = BpfPkt; ep = BpfPkt + cc; } } #define bhp ((struct bpf_hdr *)bp) /* * If there is a new packet in the buffer, stuff it into `rconn' * and return a success indication. */ if (bp < ep) { datlen = bhp->bh_datalen; caplen = bhp->bh_caplen; hdrlen = bhp->bh_hdrlen; if (caplen != datlen) syslog(LOG_ERR, "bpf: short packet dropped (%d of %d bytes)", caplen, datlen); else if (caplen > sizeof(struct rmp_packet)) syslog(LOG_ERR, "bpf: large packet dropped (%d bytes)", caplen); else { rconn->rmplen = caplen; memmove((char *)&rconn->tstamp, (char *)&bhp->bh_tstamp, sizeof(struct timeval)); memmove((char *)&rconn->rmp, (char *)bp + hdrlen, caplen); } bp += BPF_WORDALIGN(caplen + hdrlen); return(1); } #undef bhp return(0); } /* ** BpfWrite -- Write packet to BPF device. ** ** Parameters: ** rconn - packet to send. ** ** Returns: ** True if write succeeded, False otherwise. ** ** Side Effects: ** None. */ int BpfWrite(RMPCONN *rconn) { if (write(BpfFd, (char *)&rconn->rmp, rconn->rmplen) < 0) { syslog(LOG_ERR, "write: %s: %m", EnetStr(rconn)); return(0); } return(1); } /* ** BpfClose -- Close a BPF device. ** ** Parameters: ** None. ** ** Returns: ** Nothing. ** ** Side Effects: ** None. */ void BpfClose(void) { struct ifreq ifr; if (BpfPkt != NULL) { free((char *)BpfPkt); BpfPkt = NULL; } if (BpfFd == -1) return; #ifdef MSG_EOR ifr.ifr_addr.sa_len = RMP_ADDRLEN + 2; #endif ifr.ifr_addr.sa_family = AF_UNSPEC; memmove((char *)&ifr.ifr_addr.sa_data[0], &RmpMcastAddr[0], RMP_ADDRLEN); if (ioctl(BpfFd, SIOCDELMULTI, (caddr_t)&ifr) < 0) (void) ioctl(BpfFd, BIOCPROMISC, (caddr_t)0); (void) close(BpfFd); BpfFd = -1; } Index: head/libexec/rbootd/conf.c =================================================================== --- head/libexec/rbootd/conf.c (revision 262135) +++ head/libexec/rbootd/conf.c (revision 262136) @@ -1,93 +1,89 @@ /* * Copyright (c) 1988, 1992 The University of Utah and the Center * for Software Science (CSS). * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * the Center for Software Science of the University of Utah Computer * Science Department. CSS requests users of this software to return * to css-dist@cs.utah.edu any improvements that they make and grant * CSS redistribution rights. * * 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. * * from: @(#)conf.c 8.1 (Berkeley) 6/4/93 * * From: Utah Hdr: conf.c 3.1 92/07/06 * Author: Jeff Forys, University of Utah CSS */ #ifndef lint #if 0 static const char sccsid[] = "@(#)conf.c 8.1 (Berkeley) 6/4/93"; #endif static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ #include #include #include #include "defs.h" #include "pathnames.h" /* ** Define (and possibly initialize) global variables here. ** ** Caveat: ** The maximum number of bootable files (`char *BootFiles[]') is ** limited to C_MAXFILE (i.e. the maximum number of files that ** can be spec'd in the configuration file). This was done to ** simplify the boot file search code. */ char MyHost[MAXHOSTNAMELEN]; /* host name */ pid_t MyPid; /* process id */ int DebugFlg = 0; /* set true if debugging */ int BootAny = 0; /* set true if we boot anyone */ char *ConfigFile = NULL; /* configuration file */ char *DfltConfig = _PATH_RBOOTDCONF; /* default configuration file */ char *PidFile = _PATH_RBOOTDPID; /* file w/pid of server */ char *BootDir = _PATH_RBOOTDLIB; /* directory w/boot files */ char *DbgFile = _PATH_RBOOTDDBG; /* debug output file */ FILE *DbgFp = NULL; /* debug file pointer */ char *IntfName = NULL; /* intf we are attached to */ u_int16_t SessionID = 0; /* generated session ID */ char *BootFiles[C_MAXFILE]; /* list of boot files */ CLIENT *Clients = NULL; /* list of addrs we'll accept */ RMPCONN *RmpConns = NULL; /* list of active connections */ u_int8_t RmpMcastAddr[RMP_ADDRLEN] = RMP_ADDR; /* RMP multicast address */ Index: head/libexec/rbootd/defs.h =================================================================== --- head/libexec/rbootd/defs.h (revision 262135) +++ head/libexec/rbootd/defs.h (revision 262136) @@ -1,186 +1,182 @@ /* * Copyright (c) 1988, 1992 The University of Utah and the Center * for Software Science (CSS). * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * the Center for Software Science of the University of Utah Computer * Science Department. CSS requests users of this software to return * to css-dist@cs.utah.edu any improvements that they make and grant * CSS redistribution rights. * * 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. * * from: @(#)defs.h 8.1 (Berkeley) 6/4/93 * * From: Utah Hdr: defs.h 3.1 92/07/06 * Author: Jeff Forys, University of Utah CSS * * $FreeBSD$ */ #include "rmp.h" #include "rmp_var.h" /* ** Common #define's and external variables. All other files should ** include this. */ /* * This may be defined in , if not, it's defined here. */ #ifndef MAXHOSTNAMELEN #define MAXHOSTNAMELEN 256 #endif /* * SIGUSR1 and SIGUSR2 are defined in for 4.3BSD systems. */ #ifndef SIGUSR1 #define SIGUSR1 SIGEMT #endif #ifndef SIGUSR2 #define SIGUSR2 SIGFPE #endif /* * These can be faster & more efficient than strcmp()/strncmp()... */ #define STREQN(s1,s2) ((*s1 == *s2) && (strcmp(s1,s2) == 0)) #define STRNEQN(s1,s2,n) ((*s1 == *s2) && (strncmp(s1,s2,n) == 0)) /* * Configuration file limitations. */ #define C_MAXFILE 10 /* max number of boot-able files */ #define C_LINELEN 1024 /* max length of line */ /* * Direction of packet (used as argument to DispPkt). */ #define DIR_RCVD 0 #define DIR_SENT 1 #define DIR_NONE 2 /* * These need not be functions, so... */ #define FreeStr(str) free(str) #define FreeClient(cli) free(cli) #define GenSessID() (++SessionID ? SessionID: ++SessionID) /* * Converting an Ethernet address to a string is done in many routines. * Using `rmp.hp_hdr.saddr' works because this field is *never* changed; * it will *always* contain the source address of the packet. */ #define EnetStr(rptr) GetEtherAddr(&(rptr)->rmp.hp_hdr.saddr[0]) /* * Every machine we can boot will have one of these allocated for it * (unless there are no restrictions on who we can boot). */ typedef struct client_s { u_int8_t addr[RMP_ADDRLEN]; /* addr of machine */ char *files[C_MAXFILE]; /* boot-able files */ struct client_s *next; /* ptr to next */ } CLIENT; /* * Every active connection has one of these allocated for it. */ typedef struct rmpconn_s { struct rmp_packet rmp; /* RMP packet */ int rmplen; /* length of packet */ struct timeval tstamp; /* last time active */ int bootfd; /* open boot file */ struct rmpconn_s *next; /* ptr to next */ } RMPCONN; /* * All these variables are defined in "conf.c". */ extern char MyHost[]; /* this hosts' name */ extern pid_t MyPid; /* this processes' ID */ extern int DebugFlg; /* set true if debugging */ extern int BootAny; /* set true if we can boot anyone */ extern char *ConfigFile; /* configuration file */ extern char *DfltConfig; /* default configuration file */ extern char *DbgFile; /* debug output file */ extern char *PidFile; /* file containing pid of server */ extern char *BootDir; /* directory w/boot files */ extern FILE *DbgFp; /* debug file pointer */ extern char *IntfName; /* interface we are attached to */ extern u_int16_t SessionID; /* generated session ID */ extern char *BootFiles[]; /* list of boot files */ extern CLIENT *Clients; /* list of addrs we'll accept */ extern RMPCONN *RmpConns; /* list of active connections */ extern u_int8_t RmpMcastAddr[]; /* RMP multicast address */ void AddConn(RMPCONN *); int BootDone(RMPCONN *); void BpfClose(void); char *BpfGetIntfName(char **); int BpfOpen(void); int BpfRead(RMPCONN *, int); int BpfWrite(RMPCONN *); void DebugOff(int); void DebugOn(int); void DispPkt(RMPCONN *, int); void DoTimeout(void); void DspFlnm(u_int, char *); void Exit(int); CLIENT *FindClient(RMPCONN *); RMPCONN *FindConn(RMPCONN *); void FreeClients(void); void FreeConn(RMPCONN *); void FreeConns(void); int GetBootFiles(void); char *GetEtherAddr(u_int8_t *); CLIENT *NewClient(u_int8_t *); RMPCONN *NewConn(RMPCONN *); char *NewStr(char *); u_int8_t *ParseAddr(char *); int ParseConfig(void); void ProcessPacket(RMPCONN *, CLIENT *); void ReConfig(int); void RemoveConn(RMPCONN *); int SendBootRepl(struct rmp_packet *, RMPCONN *, char *[]); int SendFileNo(struct rmp_packet *, RMPCONN *, char *[]); int SendPacket(RMPCONN *); int SendReadRepl(RMPCONN *); int SendServerID(RMPCONN *); Index: head/libexec/rbootd/parseconf.c =================================================================== --- head/libexec/rbootd/parseconf.c (revision 262135) +++ head/libexec/rbootd/parseconf.c (revision 262136) @@ -1,362 +1,358 @@ /* * Copyright (c) 1988, 1992 The University of Utah and the Center * for Software Science (CSS). * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * the Center for Software Science of the University of Utah Computer * Science Department. CSS requests users of this software to return * to css-dist@cs.utah.edu any improvements that they make and grant * CSS redistribution rights. * * 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. * * from: @(#)parseconf.c 8.1 (Berkeley) 6/4/93 * * From: Utah Hdr: parseconf.c 3.1 92/07/06 * Author: Jeff Forys, University of Utah CSS */ #ifndef lint #if 0 static const char sccsid[] = "@(#)parseconf.c 8.1 (Berkeley) 6/4/93"; #endif static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ #include #include #include #include #include #include #include #include #include #include #include #include "defs.h" /* ** ParseConfig -- parse the config file into linked list of clients. ** ** Parameters: ** None. ** ** Returns: ** 1 on success, 0 otherwise. ** ** Side Effects: ** - Linked list of clients will be (re)allocated. ** ** Warnings: ** - GetBootFiles() must be called before this routine ** to create a linked list of default boot files. */ int ParseConfig(void) { FILE *fp; CLIENT *client; u_int8_t *addr; char line[C_LINELEN]; char *cp, *bcp; int i, j; int omask, linecnt = 0; if (BootAny) /* ignore config file */ return(1); FreeClients(); /* delete old list of clients */ if ((fp = fopen(ConfigFile, "r")) == NULL) { syslog(LOG_ERR, "ParseConfig: can't open config file (%s)", ConfigFile); return(0); } /* * We've got to block SIGHUP to prevent reconfiguration while * dealing with the linked list of Clients. This can be done * when actually linking the new client into the list, but * this could have unexpected results if the server was HUP'd * whilst reconfiguring. Hence, it is done here. */ omask = sigblock(sigmask(SIGHUP)); /* * GETSTR positions `bcp' at the start of the current token, * and null terminates it. `cp' is positioned at the start * of the next token. spaces & commas are separators. */ #define GETSTR while (isspace(*cp) || *cp == ',') cp++; \ bcp = cp; \ while (*cp && *cp!=',' && !isspace(*cp)) cp++; \ if (*cp) *cp++ = '\0' /* * For each line, parse it into a new CLIENT struct. */ while (fgets(line, C_LINELEN, fp) != NULL) { linecnt++; /* line counter */ if (*line == '\0' || *line == '#') /* ignore comment */ continue; if ((cp = strchr(line,'#')) != NULL) /* trash comments */ *cp = '\0'; cp = line; /* init `cp' */ GETSTR; /* get RMP addr */ if (bcp == cp) /* all delimiters */ continue; /* * Get an RMP address from a string. Abort on failure. */ if ((addr = ParseAddr(bcp)) == NULL) { syslog(LOG_ERR, "ParseConfig: line %d: can't parse <%s>", linecnt, bcp); continue; } if ((client = NewClient(addr)) == NULL) /* alloc new client */ continue; GETSTR; /* get first file */ /* * If no boot files are spec'd, use the default list. * Otherwise, validate each file (`bcp') against the * list of boot-able files. */ i = 0; if (bcp == cp) /* no files spec'd */ for (; i < C_MAXFILE && BootFiles[i] != NULL; i++) client->files[i] = BootFiles[i]; else { do { /* * For each boot file spec'd, make sure it's * in our list. If so, include a pointer to * it in the CLIENT's list of boot files. */ for (j = 0; ; j++) { if (j==C_MAXFILE||BootFiles[j]==NULL) { syslog(LOG_ERR, "ParseConfig: line %d: no boot file (%s)", linecnt, bcp); break; } if (STREQN(BootFiles[j], bcp)) { if (i < C_MAXFILE) client->files[i++] = BootFiles[j]; else syslog(LOG_ERR, "ParseConfig: line %d: too many boot files (%s)", linecnt, bcp); break; } } GETSTR; /* get next file */ } while (bcp != cp); /* * Restricted list of boot files were spec'd, * however, none of them were found. Since we * apparently can't let them boot "just anything", * the entire record is invalidated. */ if (i == 0) { FreeClient(client); continue; } } /* * Link this client into the linked list of clients. * SIGHUP has already been blocked. */ if (Clients) client->next = Clients; Clients = client; } (void) fclose(fp); /* close config file */ (void) sigsetmask(omask); /* reset signal mask */ return(1); /* return success */ } /* ** ParseAddr -- Parse a string containing an RMP address. ** ** This routine is fairly liberal at parsing an RMP address. The ** address must contain 6 octets consisting of between 0 and 2 hex ** chars (upper/lower case) separated by colons. If two colons are ** together (e.g. "::", the octet between them is recorded as being ** zero. Hence, the following addrs are all valid and parse to the ** same thing: ** ** 08:00:09:00:66:ad 8::9:0:66:AD 8::9::66:aD ** ** For clarity, an RMP address is really an Ethernet address, but ** since the HP boot code uses IEEE 802.3, it's really an IEEE ** 802.3 address. Of course, all of these are identical. ** ** Parameters: ** str - string representation of an RMP address. ** ** Returns: ** pointer to a static array of RMP_ADDRLEN bytes. ** ** Side Effects: ** None. ** ** Warnings: ** - The return value points to a static buffer; it must ** be copied if it's to be saved. */ u_int8_t * ParseAddr(char *str) { static u_int8_t addr[RMP_ADDRLEN]; char *cp; unsigned i; int part, subpart; memset((char *)&addr[0], 0, RMP_ADDRLEN); /* zero static buffer */ part = subpart = 0; for (cp = str; *cp; cp++) { /* * A colon (`:') must be used to delimit each octet. */ if (*cp == ':') { if (++part == RMP_ADDRLEN) /* too many parts */ return(NULL); subpart = 0; continue; } /* * Convert hex character to an integer. */ if (isdigit(*cp)) i = *cp - '0'; else { i = (isupper(*cp)? tolower(*cp): *cp) - 'a' + 10; if (i < 10 || i > 15) /* not a hex char */ return(NULL); } if (subpart++) { if (subpart > 2) /* too many hex chars */ return(NULL); addr[part] <<= 4; } addr[part] |= i; } if (part != (RMP_ADDRLEN-1)) /* too few parts */ return(NULL); return(&addr[0]); } /* ** GetBootFiles -- record list of files in current (boot) directory. ** ** Parameters: ** None. ** ** Returns: ** Number of boot files on success, 0 on failure. ** ** Side Effects: ** Strings in `BootFiles' are freed/allocated. ** ** Warnings: ** - After this routine is called, ParseConfig() must be ** called to re-order it's list of boot file pointers. */ int GetBootFiles(void) { DIR *dfd; struct stat statb; struct dirent *dp; int i; /* * Free the current list of boot files. */ for (i = 0; i < C_MAXFILE && BootFiles[i] != NULL; i++) { FreeStr(BootFiles[i]); BootFiles[i] = NULL; } /* * Open current directory to read boot file names. */ if ((dfd = opendir(".")) == NULL) { /* open BootDir */ syslog(LOG_ERR, "GetBootFiles: can't open directory (%s)\n", BootDir); return(0); } /* * Read each boot file name and allocate space for it in the * list of boot files (BootFiles). All boot files read after * C_MAXFILE will be ignored. */ i = 0; for (dp = readdir(dfd); dp != NULL; dp = readdir(dfd)) { if (stat(dp->d_name, &statb) < 0 || (statb.st_mode & S_IFMT) != S_IFREG) continue; if (i == C_MAXFILE) syslog(LOG_ERR, "GetBootFiles: too many boot files (%s ignored)", dp->d_name); else if ((BootFiles[i] = NewStr(dp->d_name)) != NULL) i++; } (void) closedir(dfd); /* close BootDir */ if (i == 0) /* can't find any boot files */ syslog(LOG_ERR, "GetBootFiles: no boot files (%s)\n", BootDir); return(i); } Index: head/libexec/rbootd/pathnames.h =================================================================== --- head/libexec/rbootd/pathnames.h (revision 262135) +++ head/libexec/rbootd/pathnames.h (revision 262136) @@ -1,53 +1,49 @@ /* * Copyright (c) 1988, 1992 The University of Utah and the Center * for Software Science (CSS). * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * the Center for Software Science of the University of Utah Computer * Science Department. CSS requests users of this software to return * to css-dist@cs.utah.edu any improvements that they make and grant * CSS redistribution rights. * * 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. * * from: @(#)pathnames.h 8.1 (Berkeley) 6/4/93 * * From: Utah Hdr: pathnames.h 3.1 92/07/06 * Author: Jeff Forys, University of Utah CSS * * $FreeBSD$ */ #define _PATH_BPF "/dev/bpf%d" #define _PATH_RBOOTDCONF "/etc/rbootd.conf" #define _PATH_RBOOTDDBG "/tmp/rbootd.dbg" #define _PATH_RBOOTDLIB "/usr/mdec/rbootd" #define _PATH_RBOOTDPID "/var/run/rbootd.pid" Index: head/libexec/rbootd/rbootd.8 =================================================================== --- head/libexec/rbootd/rbootd.8 (revision 262135) +++ head/libexec/rbootd/rbootd.8 (revision 262136) @@ -1,157 +1,153 @@ .\" Copyright (c) 1988, 1992 The University of Utah and the Center .\" for Software Science (CSS). .\" Copyright (c) 1992, 1993 .\" The Regents of the University of California. All rights reserved. .\" .\" This code is derived from software contributed to Berkeley by .\" the Center for Software Science of the University of Utah Computer .\" Science Department. CSS requests users of this software to return .\" to css-dist@cs.utah.edu any improvements that they make and grant .\" CSS redistribution rights. .\" .\" 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. -.\" 3. All advertising materials mentioning features or use of this software -.\" must display the following acknowledgement: -.\" This product includes software developed by the University of -.\" California, Berkeley and its contributors. -.\" 4. Neither the name of the University nor the names of its contributors +.\" 3. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. .\" .\" from: @(#)rbootd.8 8.2 (Berkeley) 12/11/93 .\" $FreeBSD$ .\" .\" Utah Hdr: rbootd.man 3.1 92/07/06 .\" Author: Jeff Forys, University of Utah CSS .\" .Dd December 11, 1993 .Dt RBOOTD 8 .Os .Sh NAME .Nm rbootd .Nd HP remote boot server .Sh SYNOPSIS .Nm .Op Fl ad .Op Fl i Ar interface .Op config_file .Sh DESCRIPTION The .Nm utility services boot requests from Hewlett-Packard workstations over a local area network. All boot files must reside in the boot file directory; further, if a client supplies path information in its boot request, it will be silently stripped away before processing. By default, .Nm only responds to requests from machines listed in its configuration file. .Pp The options are as follows: .Bl -tag -width indent .It Fl a Respond to boot requests from any machine. The configuration file is ignored if this option is specified. .It Fl d Run .Nm in debug mode. Packets sent and received are displayed to the terminal. .It Fl i Ar interface Service boot requests on specified interface. If unspecified, .Nm searches the system interface list for the lowest numbered, configured ``up'' interface (excluding loopback). Ties are broken by choosing the earliest match. .El .Pp Specifying .Ar config_file on the command line causes .Nm to use a different configuration file from the default. .Pp The configuration file is a text file where each line describes a particular machine. A line must start with a machine's Ethernet address followed by an optional list of boot file names. An Ethernet address is specified in hexadecimal with each of its six octets separated by a colon. The boot file names come from the boot file directory. The ethernet address and boot file(s) must be separated by white-space and/or comma characters. A pound sign causes the remainder of a line to be ignored. .Pp Here is a sample configuration file: .Bd -literal # # ethernet addr boot file(s) comments # 08:00:09:0:66:ad SYSHPBSD # snake (4.3BSD) 08:00:09:0:59:5b # vandy (anything) 8::9:1:C6:75 SYSHPBSD,SYSHPUX # jaguar (either) .Ed .Pp The .Nm utility logs status and error messages via .Xr syslog 3 . A startup message is always logged, and in the case of fatal errors (or deadly signals) a message is logged announcing the server's termination. In general, a non-fatal error is handled by ignoring the event that caused it (e.g.\& an invalid Ethernet address in the config file causes that line to be invalidated). .Pp The following signals have the specified effect when sent to the server process using the .Xr kill 1 command: .Bl -tag -width SIGUSR1 -offset xxxxxxxx .It SIGHUP Drop all active connections and reconfigure. .It SIGUSR1 Turn on debugging, do nothing if already on. .It SIGUSR2 Turn off debugging, do nothing if already off. .El .Sh "FILES" .Bl -tag -width /usr/libexec/rbootd -compact .It Pa /dev/bpf# packet-filter device .It Pa /etc/rbootd.conf configuration file .It Pa /tmp/rbootd.dbg debug output .It Pa /usr/mdec/rbootd directory containing boot files .It Pa /var/run/rbootd.pid process id .El .Sh SEE ALSO .Xr kill 1 , .Xr socket 2 , .Xr signal 3 , .Xr syslog 3 .Sh BUGS If multiple servers are started on the same interface, each will receive and respond to the same boot packets. Index: head/libexec/rbootd/rbootd.c =================================================================== --- head/libexec/rbootd/rbootd.c (revision 262135) +++ head/libexec/rbootd/rbootd.c (revision 262136) @@ -1,453 +1,449 @@ /* * Copyright (c) 1988, 1992 The University of Utah and the Center * for Software Science (CSS). * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * the Center for Software Science of the University of Utah Computer * Science Department. CSS requests users of this software to return * to css-dist@cs.utah.edu any improvements that they make and grant * CSS redistribution rights. * * 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. * * from: @(#)rbootd.c 8.1 (Berkeley) 6/4/93 * * From: Utah Hdr: rbootd.c 3.1 92/07/06 * Author: Jeff Forys, University of Utah CSS */ #ifndef lint static const char copyright[] = "@(#) Copyright (c) 1992, 1993\n\ The Regents of the University of California. All rights reserved.\n"; #endif /* not lint */ #ifndef lint #if 0 static const char sccsid[] = "@(#)rbootd.c 8.1 (Berkeley) 6/4/93"; #endif #endif /* not lint */ #include __FBSDID("$FreeBSD$"); #include #include #include #include #include #include #include #include #include #include #include #include #include "defs.h" static void usage(void); int main(int argc, char *argv[]) { int c, fd, omask, maxfds; fd_set rset; /* * Close any open file descriptors. * Temporarily leave stdin & stdout open for `-d', * and stderr open for any pre-syslog error messages. */ { int i, nfds = getdtablesize(); for (i = 0; i < nfds; i++) if (i != fileno(stdin) && i != fileno(stdout) && i != fileno(stderr)) (void) close(i); } /* * Parse any arguments. */ while ((c = getopt(argc, argv, "adi:")) != -1) switch(c) { case 'a': BootAny++; break; case 'd': DebugFlg++; break; case 'i': IntfName = optarg; break; default: usage(); } for (; optind < argc; optind++) { if (ConfigFile == NULL) ConfigFile = argv[optind]; else { warnx("too many config files (`%s' ignored)", argv[optind]); } } if (ConfigFile == NULL) /* use default config file */ ConfigFile = DfltConfig; if (DebugFlg) { DbgFp = stdout; /* output to stdout */ (void) signal(SIGUSR1, SIG_IGN); /* dont muck w/DbgFp */ (void) signal(SIGUSR2, SIG_IGN); (void) fclose(stderr); /* finished with it */ } else { if (daemon(0, 0)) err(1, "can't detach from terminal"); (void) signal(SIGUSR1, DebugOn); (void) signal(SIGUSR2, DebugOff); } openlog("rbootd", LOG_PID, LOG_DAEMON); /* * If no interface was specified, get one now. * * This is convoluted because we want to get the default interface * name for the syslog("restarted") message. If BpfGetIntfName() * runs into an error, it will return a syslog-able error message * (in `errmsg') which will be displayed here. */ if (IntfName == NULL) { char *errmsg; if ((IntfName = BpfGetIntfName(&errmsg)) == NULL) { /* Backslash to avoid trigraph '??)'. */ syslog(LOG_NOTICE, "restarted (?\?)"); /* BpfGetIntfName() returns safe names, using %m */ syslog(LOG_ERR, "%s", errmsg); Exit(0); } } syslog(LOG_NOTICE, "restarted (%s)", IntfName); (void) signal(SIGHUP, ReConfig); (void) signal(SIGINT, Exit); (void) signal(SIGTERM, Exit); /* * Grab our host name and pid. */ if (gethostname(MyHost, MAXHOSTNAMELEN - 1) < 0) { syslog(LOG_ERR, "gethostname: %m"); Exit(0); } MyHost[MAXHOSTNAMELEN - 1] = '\0'; MyPid = getpid(); /* * Write proc's pid to a file. */ { FILE *fp; if ((fp = fopen(PidFile, "w")) != NULL) { (void) fprintf(fp, "%d\n", (int) MyPid); (void) fclose(fp); } else { syslog(LOG_WARNING, "fopen: failed (%s)", PidFile); } } /* * All boot files are relative to the boot directory, we might * as well chdir() there to make life easier. */ if (chdir(BootDir) < 0) { syslog(LOG_ERR, "chdir: %m (%s)", BootDir); Exit(0); } /* * Initial configuration. */ omask = sigblock(sigmask(SIGHUP)); /* prevent reconfig's */ if (GetBootFiles() == 0) /* get list of boot files */ Exit(0); if (ParseConfig() == 0) /* parse config file */ Exit(0); /* * Open and initialize a BPF device for the appropriate interface. * If an error is encountered, a message is displayed and Exit() * is called. */ fd = BpfOpen(); (void) sigsetmask(omask); /* allow reconfig's */ /* * Main loop: receive a packet, determine where it came from, * and if we service this host, call routine to handle request. */ maxfds = fd + 1; FD_ZERO(&rset); FD_SET(fd, &rset); for (;;) { struct timeval timeout; fd_set r; int nsel; r = rset; if (RmpConns == NULL) { /* timeout isn't necessary */ nsel = select(maxfds, &r, NULL, NULL, NULL); } else { timeout.tv_sec = RMP_TIMEOUT; timeout.tv_usec = 0; nsel = select(maxfds, &r, NULL, NULL, &timeout); } if (nsel < 0) { if (errno == EINTR) continue; syslog(LOG_ERR, "select: %m"); Exit(0); } else if (nsel == 0) { /* timeout */ DoTimeout(); /* clear stale conns */ continue; } if (FD_ISSET(fd, &r)) { RMPCONN rconn; CLIENT *client, *FindClient(); int doread = 1; while (BpfRead(&rconn, doread)) { doread = 0; if (DbgFp != NULL) /* display packet */ DispPkt(&rconn,DIR_RCVD); omask = sigblock(sigmask(SIGHUP)); /* * If we do not restrict service, set the * client to NULL (ProcessPacket() handles * this). Otherwise, check that we can * service this host; if not, log a message * and ignore the packet. */ if (BootAny) { client = NULL; } else if ((client=FindClient(&rconn))==NULL) { syslog(LOG_INFO, "%s: boot packet ignored", EnetStr(&rconn)); (void) sigsetmask(omask); continue; } ProcessPacket(&rconn,client); (void) sigsetmask(omask); } } } } static void usage(void) { fprintf(stderr, "usage: rbootd [-ad] [-i interface] [config_file]\n"); exit (1); } /* ** DoTimeout -- Free any connections that have timed out. ** ** Parameters: ** None. ** ** Returns: ** Nothing. ** ** Side Effects: ** - Timed out connections in `RmpConns' will be freed. */ void DoTimeout(void) { RMPCONN *rtmp; time_t now; /* * For each active connection, if RMP_TIMEOUT seconds have passed * since the last packet was sent, delete the connection. */ now = time(NULL); for (rtmp = RmpConns; rtmp != NULL; rtmp = rtmp->next) if ((rtmp->tstamp.tv_sec + RMP_TIMEOUT) < now) { syslog(LOG_WARNING, "%s: connection timed out (%u)", EnetStr(rtmp), rtmp->rmp.r_type); RemoveConn(rtmp); } } /* ** FindClient -- Find client associated with a packet. ** ** Parameters: ** rconn - the new packet. ** ** Returns: ** Pointer to client info if found, NULL otherwise. ** ** Side Effects: ** None. ** ** Warnings: ** - This routine must be called with SIGHUP blocked since ** a reconfigure can invalidate the information returned. */ CLIENT * FindClient(RMPCONN *rconn) { CLIENT *ctmp; for (ctmp = Clients; ctmp != NULL; ctmp = ctmp->next) if (bcmp((char *)&rconn->rmp.hp_hdr.saddr[0], (char *)&ctmp->addr[0], RMP_ADDRLEN) == 0) break; return(ctmp); } /* ** Exit -- Log an error message and exit. ** ** Parameters: ** sig - caught signal (or zero if not dying on a signal). ** ** Returns: ** Does not return. ** ** Side Effects: ** - This process ceases to exist. */ void Exit(int sig) { if (sig > 0) syslog(LOG_ERR, "going down on signal %d", sig); else syslog(LOG_ERR, "going down with fatal error"); BpfClose(); exit(1); } /* ** ReConfig -- Get new list of boot files and reread config files. ** ** Parameters: ** None. ** ** Returns: ** Nothing. ** ** Side Effects: ** - All active connections are dropped. ** - List of boot-able files is changed. ** - List of clients is changed. ** ** Warnings: ** - This routine must be called with SIGHUP blocked. */ void ReConfig(int signo __unused) { syslog(LOG_NOTICE, "reconfiguring boot server"); FreeConns(); if (GetBootFiles() == 0) Exit(0); if (ParseConfig() == 0) Exit(0); } /* ** DebugOff -- Turn off debugging. ** ** Parameters: ** None. ** ** Returns: ** Nothing. ** ** Side Effects: ** - Debug file is closed. */ void DebugOff(int signo __unused) { if (DbgFp != NULL) (void) fclose(DbgFp); DbgFp = NULL; } /* ** DebugOn -- Turn on debugging. ** ** Parameters: ** None. ** ** Returns: ** Nothing. ** ** Side Effects: ** - Debug file is opened/truncated if not already opened, ** otherwise do nothing. */ void DebugOn(int signo __unused) { if (DbgFp == NULL) { if ((DbgFp = fopen(DbgFile, "w")) == NULL) syslog(LOG_ERR, "can't open debug file (%s)", DbgFile); } } Index: head/libexec/rbootd/rmp.h =================================================================== --- head/libexec/rbootd/rmp.h (revision 262135) +++ head/libexec/rbootd/rmp.h (revision 262136) @@ -1,97 +1,93 @@ /* * Copyright (c) 1988, 1992 The University of Utah and the Center * for Software Science (CSS). * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * the Center for Software Science of the University of Utah Computer * Science Department. CSS requests users of this software to return * to css-dist@cs.utah.edu any improvements that they make and grant * CSS redistribution rights. * * 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. * * from: @(#)rmp.h 8.1 (Berkeley) 6/4/93 * * From: Utah Hdr: rmp.h 3.1 92/07/06 * Author: Jeff Forys, University of Utah CSS * * $FreeBSD$ */ /* * Define MIN/MAX sizes of RMP (ethernet) packet. * For ease of computation, the 4 octet CRC field is not included. * * MCLBYTES is for bpfwrite(); it is adamant about using a cluster. */ #define RMP_MAX_PACKET MIN(1514,MCLBYTES) #define RMP_MIN_PACKET 60 /* * Define RMP/Ethernet Multicast address (9:0:9:0:0:4) and its length. */ #define RMP_ADDR { 0x9, 0x0, 0x9, 0x0, 0x0, 0x4 } #define RMP_ADDRLEN 6 /* * Define IEEE802.2 (Logical Link Control) information. */ #define IEEE_DSAP_HP 0xF8 /* Destination Service Access Point */ #define IEEE_SSAP_HP 0xF8 /* Source Service Access Point */ #define IEEE_CNTL_HP 0x0300 /* Type 1 / I format control information */ #define HPEXT_DXSAP 0x608 /* HP Destination Service Access Point */ #define HPEXT_SXSAP 0x609 /* HP Source Service Access Point */ /* * 802.3-style "Ethernet" header. */ struct hp_hdr { u_int8_t daddr[RMP_ADDRLEN]; u_int8_t saddr[RMP_ADDRLEN]; u_int16_t len; }; /* * HP uses 802.2 LLC with their own local extensions. This struct makes * sense out of this data (encapsulated in the above 802.3 packet). */ struct hp_llc { u_int8_t dsap; /* 802.2 DSAP */ u_int8_t ssap; /* 802.2 SSAP */ u_int16_t cntrl; /* 802.2 control field */ u_int16_t filler; /* HP filler (must be zero) */ u_int16_t dxsap; /* HP extended DSAP */ u_int16_t sxsap; /* HP extended SSAP */ }; Index: head/libexec/rbootd/rmp_var.h =================================================================== --- head/libexec/rbootd/rmp_var.h (revision 262135) +++ head/libexec/rbootd/rmp_var.h (revision 262136) @@ -1,246 +1,242 @@ /* * Copyright (c) 1988, 1992 The University of Utah and the Center * for Software Science (CSS). * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * the Center for Software Science of the University of Utah Computer * Science Department. CSS requests users of this software to return * to css-dist@cs.utah.edu any improvements that they make and grant * CSS redistribution rights. * * 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. * * from: @(#)rmp_var.h 8.1 (Berkeley) 6/4/93 * * from: Utah Hdr: rmp_var.h 3.1 92/07/06 * Author: Jeff Forys, University of Utah CSS * * $FreeBSD$ */ /* * Possible values for "rmp_type" fields. */ #define RMP_BOOT_REQ 1 /* boot request packet */ #define RMP_BOOT_REPL 129 /* boot reply packet */ #define RMP_READ_REQ 2 /* read request packet */ #define RMP_READ_REPL 130 /* read reply packet */ #define RMP_BOOT_DONE 3 /* boot complete packet */ /* * Useful constants. */ #define RMP_VERSION 2 /* protocol version */ #define RMP_TIMEOUT 600 /* timeout connection after ten minutes */ #define RMP_PROBESID 0xffff /* session ID for probes */ #define RMP_HOSTLEN 13 /* max length of server's name */ #define RMP_MACHLEN 20 /* length of machine type field */ /* * RMP error codes */ #define RMP_E_OKAY 0 #define RMP_E_EOF 2 /* read reply: returned end of file */ #define RMP_E_ABORT 3 /* abort operation */ #define RMP_E_BUSY 4 /* boot reply: server busy */ #define RMP_E_TIMEOUT 5 /* lengthen time out (not implemented) */ #define RMP_E_NOFILE 16 /* boot reply: file does not exist */ #define RMP_E_OPENFILE 17 /* boot reply: file open failed */ #define RMP_E_NODFLT 18 /* boot reply: default file does not exist */ #define RMP_E_OPENDFLT 19 /* boot reply: default file open failed */ #define RMP_E_BADSID 25 /* read reply: bad session ID */ #define RMP_E_BADPACKET 27 /* Bad packet detected */ /* * RMPDATALEN is the maximum number of data octets that can be stuffed * into an RMP packet. This excludes the 802.2 LLC w/HP extensions. */ #define RMPDATALEN (RMP_MAX_PACKET - (sizeof(struct hp_hdr) + \ sizeof(struct hp_llc))) /* * Define sizes of packets we send. Boot and Read replies are variable * in length depending on the length of `s'. * * Also, define how much space `restofpkt' can take up for outgoing * Boot and Read replies. Boot Request packets are effectively * limited to 255 bytes due to the preceding 1-byte length field. */ #define RMPBOOTSIZE(s) (sizeof(struct hp_hdr) + sizeof(struct hp_llc) + \ sizeof(struct rmp_boot_repl) + s - sizeof(restofpkt)) #define RMPREADSIZE(s) (sizeof(struct hp_hdr) + sizeof(struct hp_llc) + \ sizeof(struct rmp_read_repl) + s - sizeof(restofpkt) \ - sizeof(u_int8_t)) #define RMPDONESIZE (sizeof(struct hp_hdr) + sizeof(struct hp_llc) + \ sizeof(struct rmp_boot_done)) #define RMPBOOTDATA 255 #define RMPREADDATA (RMPDATALEN - \ (2*sizeof(u_int8_t)+sizeof(u_int16_t)+sizeof(u_word))) /* * This protocol defines some field sizes as "rest of ethernet packet". * There is no easy way to specify this in C, so we use a one character * field to denote it, and index past it to the end of the packet. */ typedef char restofpkt; /* * Due to the RMP packet layout, we'll run into alignment problems * on machines that can't access (or don't, by default, align) words * on half-word boundaries. If you know that your machine does not suffer * from this problem, add it to the vax/tahoe/m68k #define below. * * The following macros are used to deal with this problem: * WORDZE(w) Return True if u_word `w' is zero, False otherwise. * ZEROWORD(w) Set u_word `w' to zero. * COPYWORD(w1,w2) Copy u_word `w1' to `w2'. * GETWORD(w,i) Copy u_word `w' into int `i'. * PUTWORD(i,w) Copy int `i' into u_word `w'. * * N.B. Endianness is handled by use of ntohl/htonl */ #if defined(__vax__) || defined(__tahoe__) || defined(__m68k__) typedef u_int32_t u_word; #define WORDZE(w) ((w) == 0) #define ZEROWORD(w) (w) = 0 #define COPYWORD(w1,w2) (w2) = (w1) #define GETWORD(w, i) (i) = ntohl(w) #define PUTWORD(i, w) (w) = htonl(i) #else #define _WORD_HIGHPART 0 #define _WORD_LOWPART 1 typedef struct _uword { u_int16_t val[2]; } u_word; #define WORDZE(w) \ ((w.val[_WORD_HIGHPART] == 0) && (w.val[_WORD_LOWPART] == 0)) #define ZEROWORD(w) \ (w).val[_WORD_HIGHPART] = (w).val[_WORD_LOWPART] = 0 #define COPYWORD(w1, w2) \ { (w2).val[_WORD_HIGHPART] = (w1).val[_WORD_HIGHPART]; \ (w2).val[_WORD_LOWPART] = (w1).val[_WORD_LOWPART]; \ } #define GETWORD(w, i) \ (i) = (((u_int32_t)ntohs((w).val[_WORD_HIGHPART])) << 16) | ntohs((w).val[_WORD_LOWPART]) #define PUTWORD(i, w) \ { (w).val[_WORD_HIGHPART] = htons((u_int16_t) ((i >> 16) & 0xffff)); \ (w).val[_WORD_LOWPART] = htons((u_int16_t) (i & 0xffff)); \ } #endif /* * Packet structures. */ struct rmp_raw { /* generic RMP packet */ u_int8_t rmp_type; /* packet type */ u_int8_t rmp_rawdata[RMPDATALEN-1]; }; struct rmp_boot_req { /* boot request */ u_int8_t rmp_type; /* packet type (RMP_BOOT_REQ) */ u_int8_t rmp_retcode; /* return code (0) */ u_word rmp_seqno; /* sequence number (real time clock) */ u_int16_t rmp_session; /* session id (normally 0) */ u_int16_t rmp_version; /* protocol version (RMP_VERSION) */ char rmp_machtype[RMP_MACHLEN]; /* machine type */ u_int8_t rmp_flnmsize; /* length of rmp_flnm */ restofpkt rmp_flnm; /* name of file to be read */ }; struct rmp_boot_repl { /* boot reply */ u_int8_t rmp_type; /* packet type (RMP_BOOT_REPL) */ u_int8_t rmp_retcode; /* return code (normally 0) */ u_word rmp_seqno; /* sequence number (from boot req) */ u_int16_t rmp_session; /* session id (generated) */ u_int16_t rmp_version; /* protocol version (RMP_VERSION) */ u_int8_t rmp_flnmsize; /* length of rmp_flnm */ restofpkt rmp_flnm; /* name of file (from boot req) */ }; struct rmp_read_req { /* read request */ u_int8_t rmp_type; /* packet type (RMP_READ_REQ) */ u_int8_t rmp_retcode; /* return code (0) */ u_word rmp_offset; /* file relative byte offset */ u_int16_t rmp_session; /* session id (from boot repl) */ u_int16_t rmp_size; /* max no of bytes to send */ }; struct rmp_read_repl { /* read reply */ u_int8_t rmp_type; /* packet type (RMP_READ_REPL) */ u_int8_t rmp_retcode; /* return code (normally 0) */ u_word rmp_offset; /* byte offset (from read req) */ u_int16_t rmp_session; /* session id (from read req) */ restofpkt rmp_data; /* data (max size from read req) */ u_int8_t rmp_unused; /* padding to 16-bit boundary */ }; struct rmp_boot_done { /* boot complete */ u_int8_t rmp_type; /* packet type (RMP_BOOT_DONE) */ u_int8_t rmp_retcode; /* return code (0) */ u_word rmp_unused; /* not used (0) */ u_int16_t rmp_session; /* session id (from read repl) */ }; struct rmp_packet { struct hp_hdr hp_hdr; struct hp_llc hp_llc; union { struct rmp_boot_req rmp_brq; /* boot request */ struct rmp_boot_repl rmp_brpl; /* boot reply */ struct rmp_read_req rmp_rrq; /* read request */ struct rmp_read_repl rmp_rrpl; /* read reply */ struct rmp_boot_done rmp_done; /* boot complete */ struct rmp_raw rmp_raw; /* raw data */ } rmp_proto; }; /* * Make life easier... */ #define r_type rmp_proto.rmp_raw.rmp_type #define r_data rmp_proto.rmp_raw.rmp_rawdata #define r_brq rmp_proto.rmp_brq #define r_brpl rmp_proto.rmp_brpl #define r_rrq rmp_proto.rmp_rrq #define r_rrpl rmp_proto.rmp_rrpl #define r_done rmp_proto.rmp_done Index: head/libexec/rbootd/rmpproto.c =================================================================== --- head/libexec/rbootd/rmpproto.c (revision 262135) +++ head/libexec/rbootd/rmpproto.c (revision 262136) @@ -1,587 +1,583 @@ /* * Copyright (c) 1988, 1992 The University of Utah and the Center * for Software Science (CSS). * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * the Center for Software Science of the University of Utah Computer * Science Department. CSS requests users of this software to return * to css-dist@cs.utah.edu any improvements that they make and grant * CSS redistribution rights. * * 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. * * from: @(#)rmpproto.c 8.1 (Berkeley) 6/4/93 * * From: Utah Hdr: rmpproto.c 3.1 92/07/06 * Author: Jeff Forys, University of Utah CSS */ #ifndef lint #if 0 static const char sccsid[] = "@(#)rmpproto.c 8.1 (Berkeley) 6/4/93"; #endif static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ #include #include #include #include #include #include #include #include #include #include "defs.h" /* ** ProcessPacket -- determine packet type and do what's required. ** ** An RMP BOOT packet has been received. Look at the type field ** and process Boot Requests, Read Requests, and Boot Complete ** packets. Any other type will be dropped with a warning msg. ** ** Parameters: ** rconn - the new connection ** client - list of files available to this host ** ** Returns: ** Nothing. ** ** Side Effects: ** - If this is a valid boot request, it will be added to ** the linked list of outstanding requests (RmpConns). ** - If this is a valid boot complete, its associated ** entry in RmpConns will be deleted. ** - Also, unless we run out of memory, a reply will be ** sent to the host that sent the packet. */ void ProcessPacket(RMPCONN *rconn, CLIENT *client) { struct rmp_packet *rmp; RMPCONN *rconnout; rmp = &rconn->rmp; /* cache pointer to RMP packet */ switch(rmp->r_type) { /* do what we came here to do */ case RMP_BOOT_REQ: /* boot request */ if ((rconnout = NewConn(rconn)) == NULL) return; /* * If the Session ID is 0xffff, this is a "probe" * packet and we do not want to add the connection * to the linked list of active connections. There * are two types of probe packets, if the Sequence * Number is 0 they want to know our host name, o/w * they want the name of the file associated with * the number spec'd by the Sequence Number. * * If this is an actual boot request, open the file * and send a reply. If SendBootRepl() does not * return 0, add the connection to the linked list * of active connections, otherwise delete it since * an error was encountered. */ if (ntohs(rmp->r_brq.rmp_session) == RMP_PROBESID) { if (WORDZE(rmp->r_brq.rmp_seqno)) (void) SendServerID(rconnout); else (void) SendFileNo(rmp, rconnout, client? client->files: BootFiles); FreeConn(rconnout); } else { if (SendBootRepl(rmp, rconnout, client? client->files: BootFiles)) AddConn(rconnout); else FreeConn(rconnout); } break; case RMP_BOOT_REPL: /* boot reply (not valid) */ syslog(LOG_WARNING, "%s: sent a boot reply", EnetStr(rconn)); break; case RMP_READ_REQ: /* read request */ /* * Send a portion of the boot file. */ (void) SendReadRepl(rconn); break; case RMP_READ_REPL: /* read reply (not valid) */ syslog(LOG_WARNING, "%s: sent a read reply", EnetStr(rconn)); break; case RMP_BOOT_DONE: /* boot complete */ /* * Remove the entry from the linked list of active * connections. */ (void) BootDone(rconn); break; default: /* unknown RMP packet type */ syslog(LOG_WARNING, "%s: unknown packet type (%u)", EnetStr(rconn), rmp->r_type); } } /* ** SendServerID -- send our host name to who ever requested it. ** ** Parameters: ** rconn - the reply packet to be formatted. ** ** Returns: ** 1 on success, 0 on failure. ** ** Side Effects: ** none. */ int SendServerID(RMPCONN *rconn) { struct rmp_packet *rpl; char *src, *dst; u_int8_t *size; rpl = &rconn->rmp; /* cache ptr to RMP packet */ /* * Set up assorted fields in reply packet. */ rpl->r_brpl.rmp_type = RMP_BOOT_REPL; rpl->r_brpl.rmp_retcode = RMP_E_OKAY; ZEROWORD(rpl->r_brpl.rmp_seqno); rpl->r_brpl.rmp_session = 0; rpl->r_brpl.rmp_version = htons(RMP_VERSION); size = &rpl->r_brpl.rmp_flnmsize; /* ptr to length of host name */ /* * Copy our host name into the reply packet incrementing the * length as we go. Stop at RMP_HOSTLEN or the first dot. */ src = MyHost; dst = (char *) &rpl->r_brpl.rmp_flnm; for (*size = 0; *size < RMP_HOSTLEN; (*size)++) { if (*src == '.' || *src == '\0') break; *dst++ = *src++; } rconn->rmplen = RMPBOOTSIZE(*size); /* set packet length */ return(SendPacket(rconn)); /* send packet */ } /* ** SendFileNo -- send the name of a bootable file to the requester. ** ** Parameters: ** req - RMP BOOT packet containing the request. ** rconn - the reply packet to be formatted. ** filelist - list of files available to the requester. ** ** Returns: ** 1 on success, 0 on failure. ** ** Side Effects: ** none. */ int SendFileNo(struct rmp_packet *req, RMPCONN *rconn, char *filelist[]) { struct rmp_packet *rpl; char *src, *dst; u_int8_t *size; int i; GETWORD(req->r_brpl.rmp_seqno, i); /* SeqNo is really FileNo */ rpl = &rconn->rmp; /* cache ptr to RMP packet */ /* * Set up assorted fields in reply packet. */ rpl->r_brpl.rmp_type = RMP_BOOT_REPL; PUTWORD(i, rpl->r_brpl.rmp_seqno); i--; rpl->r_brpl.rmp_session = 0; rpl->r_brpl.rmp_version = htons(RMP_VERSION); size = &rpl->r_brpl.rmp_flnmsize; /* ptr to length of filename */ *size = 0; /* init length to zero */ /* * Copy the file name into the reply packet incrementing the * length as we go. Stop at end of string or when RMPBOOTDATA * characters have been copied. Also, set return code to * indicate success or "no more files". */ if (i < C_MAXFILE && filelist[i] != NULL) { src = filelist[i]; dst = (char *)&rpl->r_brpl.rmp_flnm; for (; *src && *size < RMPBOOTDATA; (*size)++) { if (*src == '\0') break; *dst++ = *src++; } rpl->r_brpl.rmp_retcode = RMP_E_OKAY; } else rpl->r_brpl.rmp_retcode = RMP_E_NODFLT; rconn->rmplen = RMPBOOTSIZE(*size); /* set packet length */ return(SendPacket(rconn)); /* send packet */ } /* ** SendBootRepl -- open boot file and respond to boot request. ** ** Parameters: ** req - RMP BOOT packet containing the request. ** rconn - the reply packet to be formatted. ** filelist - list of files available to the requester. ** ** Returns: ** 1 on success, 0 on failure. ** ** Side Effects: ** none. */ int SendBootRepl(struct rmp_packet *req, RMPCONN *rconn, char *filelist[]) { int retval; char *filename, filepath[RMPBOOTDATA+1]; RMPCONN *oldconn; struct rmp_packet *rpl; char *src, *dst1, *dst2; u_int8_t i; /* * If another connection already exists, delete it since we * are obviously starting again. */ if ((oldconn = FindConn(rconn)) != NULL) { syslog(LOG_WARNING, "%s: dropping existing connection", EnetStr(oldconn)); RemoveConn(oldconn); } rpl = &rconn->rmp; /* cache ptr to RMP packet */ /* * Set up assorted fields in reply packet. */ rpl->r_brpl.rmp_type = RMP_BOOT_REPL; COPYWORD(req->r_brq.rmp_seqno, rpl->r_brpl.rmp_seqno); rpl->r_brpl.rmp_session = htons(GenSessID()); rpl->r_brpl.rmp_version = htons(RMP_VERSION); rpl->r_brpl.rmp_flnmsize = req->r_brq.rmp_flnmsize; /* * Copy file name to `filepath' string, and into reply packet. */ src = &req->r_brq.rmp_flnm; dst1 = filepath; dst2 = &rpl->r_brpl.rmp_flnm; for (i = 0; i < req->r_brq.rmp_flnmsize; i++) *dst1++ = *dst2++ = *src++; *dst1 = '\0'; /* * If we are booting HP-UX machines, their secondary loader will * ask for files like "/hp-ux". As a security measure, we do not * allow boot files to lay outside the boot directory (unless they * are purposely link'd out. So, make `filename' become the path- * stripped file name and spoof the client into thinking that it * really got what it wanted. */ filename = (filename = strrchr(filepath,'/'))? ++filename: filepath; /* * Check that this is a valid boot file name. */ for (i = 0; i < C_MAXFILE && filelist[i] != NULL; i++) if (STREQN(filename, filelist[i])) goto match; /* * Invalid boot file name, set error and send reply packet. */ rpl->r_brpl.rmp_retcode = RMP_E_NOFILE; retval = 0; goto sendpkt; match: /* * This is a valid boot file. Open the file and save the file * descriptor associated with this connection and set success * indication. If the file couldnt be opened, set error: * "no such file or dir" - RMP_E_NOFILE * "file table overflow" - RMP_E_BUSY * "too many open files" - RMP_E_BUSY * anything else - RMP_E_OPENFILE */ if ((rconn->bootfd = open(filename, O_RDONLY, 0600)) < 0) { rpl->r_brpl.rmp_retcode = (errno == ENOENT)? RMP_E_NOFILE: (errno == EMFILE || errno == ENFILE)? RMP_E_BUSY: RMP_E_OPENFILE; retval = 0; } else { rpl->r_brpl.rmp_retcode = RMP_E_OKAY; retval = 1; } sendpkt: syslog(LOG_INFO, "%s: request to boot %s (%s)", EnetStr(rconn), filename, retval? "granted": "denied"); rconn->rmplen = RMPBOOTSIZE(rpl->r_brpl.rmp_flnmsize); return (retval & SendPacket(rconn)); } /* ** SendReadRepl -- send a portion of the boot file to the requester. ** ** Parameters: ** rconn - the reply packet to be formatted. ** ** Returns: ** 1 on success, 0 on failure. ** ** Side Effects: ** none. */ int SendReadRepl(RMPCONN *rconn) { int retval = 0; RMPCONN *oldconn; struct rmp_packet *rpl, *req; int size = 0; int madeconn = 0; /* * Find the old connection. If one doesn't exist, create one only * to return the error code. */ if ((oldconn = FindConn(rconn)) == NULL) { if ((oldconn = NewConn(rconn)) == NULL) return(0); syslog(LOG_ERR, "SendReadRepl: no active connection (%s)", EnetStr(rconn)); madeconn++; } req = &rconn->rmp; /* cache ptr to request packet */ rpl = &oldconn->rmp; /* cache ptr to reply packet */ if (madeconn) { /* no active connection above; abort */ rpl->r_rrpl.rmp_retcode = RMP_E_ABORT; retval = 1; goto sendpkt; } /* * Make sure Session ID's match. */ if (ntohs(req->r_rrq.rmp_session) != ((rpl->r_type == RMP_BOOT_REPL)? ntohs(rpl->r_brpl.rmp_session): ntohs(rpl->r_rrpl.rmp_session))) { syslog(LOG_ERR, "SendReadRepl: bad session id (%s)", EnetStr(rconn)); rpl->r_rrpl.rmp_retcode = RMP_E_BADSID; retval = 1; goto sendpkt; } /* * If the requester asks for more data than we can fit, * silently clamp the request size down to RMPREADDATA. * * N.B. I do not know if this is "legal", however it seems * to work. This is necessary for bpfwrite() on machines * with MCLBYTES less than 1514. */ if (ntohs(req->r_rrq.rmp_size) > RMPREADDATA) req->r_rrq.rmp_size = htons(RMPREADDATA); /* * Position read head on file according to info in request packet. */ GETWORD(req->r_rrq.rmp_offset, size); if (lseek(oldconn->bootfd, (off_t)size, SEEK_SET) < 0) { syslog(LOG_ERR, "SendReadRepl: lseek: %m (%s)", EnetStr(rconn)); rpl->r_rrpl.rmp_retcode = RMP_E_ABORT; retval = 1; goto sendpkt; } /* * Read data directly into reply packet. */ if ((size = read(oldconn->bootfd, &rpl->r_rrpl.rmp_data, (int) ntohs(req->r_rrq.rmp_size))) <= 0) { if (size < 0) { syslog(LOG_ERR, "SendReadRepl: read: %m (%s)", EnetStr(rconn)); rpl->r_rrpl.rmp_retcode = RMP_E_ABORT; } else { rpl->r_rrpl.rmp_retcode = RMP_E_EOF; } retval = 1; goto sendpkt; } /* * Set success indication. */ rpl->r_rrpl.rmp_retcode = RMP_E_OKAY; sendpkt: /* * Set up assorted fields in reply packet. */ rpl->r_rrpl.rmp_type = RMP_READ_REPL; COPYWORD(req->r_rrq.rmp_offset, rpl->r_rrpl.rmp_offset); rpl->r_rrpl.rmp_session = req->r_rrq.rmp_session; oldconn->rmplen = RMPREADSIZE(size); /* set size of packet */ retval &= SendPacket(oldconn); /* send packet */ if (madeconn) /* clean up after ourself */ FreeConn(oldconn); return (retval); } /* ** BootDone -- free up memory allocated for a connection. ** ** Parameters: ** rconn - incoming boot complete packet. ** ** Returns: ** 1 on success, 0 on failure. ** ** Side Effects: ** none. */ int BootDone(RMPCONN *rconn) { RMPCONN *oldconn; struct rmp_packet *rpl; /* * If we can't find the connection, ignore the request. */ if ((oldconn = FindConn(rconn)) == NULL) { syslog(LOG_ERR, "BootDone: no existing connection (%s)", EnetStr(rconn)); return(0); } rpl = &oldconn->rmp; /* cache ptr to RMP packet */ /* * Make sure Session ID's match. */ if (ntohs(rconn->rmp.r_rrq.rmp_session) != ((rpl->r_type == RMP_BOOT_REPL)? ntohs(rpl->r_brpl.rmp_session): ntohs(rpl->r_rrpl.rmp_session))) { syslog(LOG_ERR, "BootDone: bad session id (%s)", EnetStr(rconn)); return(0); } RemoveConn(oldconn); /* remove connection */ syslog(LOG_INFO, "%s: boot complete", EnetStr(rconn)); return(1); } /* ** SendPacket -- send an RMP packet to a remote host. ** ** Parameters: ** rconn - packet to be sent. ** ** Returns: ** 1 on success, 0 on failure. ** ** Side Effects: ** none. */ int SendPacket(RMPCONN *rconn) { /* * Set Ethernet Destination address to Source (BPF and the enet * driver will take care of getting our source address set). */ memmove((char *)&rconn->rmp.hp_hdr.daddr[0], (char *)&rconn->rmp.hp_hdr.saddr[0], RMP_ADDRLEN); rconn->rmp.hp_hdr.len = htons(rconn->rmplen - sizeof(struct hp_hdr)); /* * Reverse 802.2/HP Extended Source & Destination Access Pts. */ rconn->rmp.hp_llc.dxsap = htons(HPEXT_SXSAP); rconn->rmp.hp_llc.sxsap = htons(HPEXT_DXSAP); /* * Last time this connection was active. */ (void)gettimeofday(&rconn->tstamp, NULL); if (DbgFp != NULL) /* display packet */ DispPkt(rconn,DIR_SENT); /* * Send RMP packet to remote host. */ return(BpfWrite(rconn)); } Index: head/libexec/rbootd/utils.c =================================================================== --- head/libexec/rbootd/utils.c (revision 262135) +++ head/libexec/rbootd/utils.c (revision 262136) @@ -1,548 +1,544 @@ /* * Copyright (c) 1988, 1992 The University of Utah and the Center * for Software Science (CSS). * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * the Center for Software Science of the University of Utah Computer * Science Department. CSS requests users of this software to return * to css-dist@cs.utah.edu any improvements that they make and grant * CSS redistribution rights. * * 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. * * from: @(#)utils.c 8.1 (Berkeley) 6/4/93 * * From: Utah Hdr: utils.c 3.1 92/07/06 * Author: Jeff Forys, University of Utah CSS */ #ifndef lint #if 0 static const char sccsid[] = "@(#)utils.c 8.1 (Berkeley) 6/4/93"; #endif static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ #include #include #include #include #include #include #include #include #include #include #include #include "defs.h" /* ** DispPkt -- Display the contents of an RMPCONN packet. ** ** Parameters: ** rconn - packet to be displayed. ** direct - direction packet is going (DIR_*). ** ** Returns: ** Nothing. ** ** Side Effects: ** None. */ void DispPkt(RMPCONN *rconn, int direct) { static const char BootFmt[] = "\t\tRetCode:%u SeqNo:%x SessID:%x Vers:%u"; static const char ReadFmt[] = "\t\tRetCode:%u Offset:%x SessID:%x\n"; struct tm *tmp; struct rmp_packet *rmp; int i, omask; u_int32_t t; /* * Since we will be working with RmpConns as well as DbgFp, we * must block signals that can affect either. */ omask = sigblock(sigmask(SIGHUP)|sigmask(SIGUSR1)|sigmask(SIGUSR2)); if (DbgFp == NULL) { /* sanity */ (void) sigsetmask(omask); return; } /* display direction packet is going using '>>>' or '<<<' */ fputs((direct==DIR_RCVD)?"<<< ":(direct==DIR_SENT)?">>> ":"", DbgFp); /* display packet timestamp */ tmp = localtime((time_t *)&rconn->tstamp.tv_sec); fprintf(DbgFp, "%02d:%02d:%02d.%06ld ", tmp->tm_hour, tmp->tm_min, tmp->tm_sec, rconn->tstamp.tv_usec); /* display src or dst addr and information about network interface */ fprintf(DbgFp, "Addr: %s Intf: %s\n", EnetStr(rconn), IntfName); rmp = &rconn->rmp; /* display IEEE 802.2 Logical Link Control header */ (void) fprintf(DbgFp, "\t802.2 LLC: DSAP:%x SSAP:%x CTRL:%x\n", rmp->hp_llc.dsap, rmp->hp_llc.ssap, ntohs(rmp->hp_llc.cntrl)); /* display HP extensions to 802.2 Logical Link Control header */ (void) fprintf(DbgFp, "\tHP Ext: DXSAP:%x SXSAP:%x\n", ntohs(rmp->hp_llc.dxsap), ntohs(rmp->hp_llc.sxsap)); /* * Display information about RMP packet using type field to * determine what kind of packet this is. */ switch(rmp->r_type) { case RMP_BOOT_REQ: /* boot request */ (void) fprintf(DbgFp, "\tBoot Request:"); GETWORD(rmp->r_brq.rmp_seqno, t); if (ntohs(rmp->r_brq.rmp_session) == RMP_PROBESID) { if (WORDZE(rmp->r_brq.rmp_seqno)) fputs(" (Send Server ID)", DbgFp); else fprintf(DbgFp," (Send Filename #%u)",t); } (void) fputc('\n', DbgFp); (void) fprintf(DbgFp, BootFmt, rmp->r_brq.rmp_retcode, t, ntohs(rmp->r_brq.rmp_session), ntohs(rmp->r_brq.rmp_version)); (void) fprintf(DbgFp, "\n\t\tMachine Type: "); for (i = 0; i < RMP_MACHLEN; i++) (void) fputc(rmp->r_brq.rmp_machtype[i], DbgFp); DspFlnm(rmp->r_brq.rmp_flnmsize, &rmp->r_brq.rmp_flnm); break; case RMP_BOOT_REPL: /* boot reply */ fprintf(DbgFp, "\tBoot Reply:\n"); GETWORD(rmp->r_brpl.rmp_seqno, t); (void) fprintf(DbgFp, BootFmt, rmp->r_brpl.rmp_retcode, t, ntohs(rmp->r_brpl.rmp_session), ntohs(rmp->r_brpl.rmp_version)); DspFlnm(rmp->r_brpl.rmp_flnmsize,&rmp->r_brpl.rmp_flnm); break; case RMP_READ_REQ: /* read request */ (void) fprintf(DbgFp, "\tRead Request:\n"); GETWORD(rmp->r_rrq.rmp_offset, t); (void) fprintf(DbgFp, ReadFmt, rmp->r_rrq.rmp_retcode, t, ntohs(rmp->r_rrq.rmp_session)); (void) fprintf(DbgFp, "\t\tNoOfBytes: %u\n", ntohs(rmp->r_rrq.rmp_size)); break; case RMP_READ_REPL: /* read reply */ (void) fprintf(DbgFp, "\tRead Reply:\n"); GETWORD(rmp->r_rrpl.rmp_offset, t); (void) fprintf(DbgFp, ReadFmt, rmp->r_rrpl.rmp_retcode, t, ntohs(rmp->r_rrpl.rmp_session)); (void) fprintf(DbgFp, "\t\tNoOfBytesSent: %zu\n", rconn->rmplen - RMPREADSIZE(0)); break; case RMP_BOOT_DONE: /* boot complete */ (void) fprintf(DbgFp, "\tBoot Complete:\n"); (void) fprintf(DbgFp, "\t\tRetCode:%u SessID:%x\n", rmp->r_done.rmp_retcode, ntohs(rmp->r_done.rmp_session)); break; default: /* ??? */ (void) fprintf(DbgFp, "\tUnknown Type:(%d)\n", rmp->r_type); } (void) fputc('\n', DbgFp); (void) fflush(DbgFp); (void) sigsetmask(omask); /* reset old signal mask */ } /* ** GetEtherAddr -- convert an RMP (Ethernet) address into a string. ** ** An RMP BOOT packet has been received. Look at the type field ** and process Boot Requests, Read Requests, and Boot Complete ** packets. Any other type will be dropped with a warning msg. ** ** Parameters: ** addr - array of RMP_ADDRLEN bytes. ** ** Returns: ** Pointer to static string representation of `addr'. ** ** Side Effects: ** None. ** ** Warnings: ** - The return value points to a static buffer; it must ** be copied if it's to be saved. */ char * GetEtherAddr(u_int8_t *addr) { static char Hex[] = "0123456789abcdef"; static char etherstr[RMP_ADDRLEN*3]; int i; char *cp; /* * For each byte in `addr', convert it to ":". * The last byte does not get a trailing `:' appended. */ i = 0; cp = etherstr; for(;;) { *cp++ = Hex[*addr >> 4 & 0xf]; *cp++ = Hex[*addr++ & 0xf]; if (++i == RMP_ADDRLEN) break; *cp++ = ':'; } *cp = '\0'; return(etherstr); } /* ** DispFlnm -- Print a string of bytes to DbgFp (often, a file name). ** ** Parameters: ** size - number of bytes to print. ** flnm - address of first byte. ** ** Returns: ** Nothing. ** ** Side Effects: ** - Characters are sent to `DbgFp'. */ void DspFlnm(u_int size, char *flnm) { int i; (void) fprintf(DbgFp, "\n\t\tFile Name (%u): <", size); for (i = 0; i < size; i++) (void) fputc(*flnm++, DbgFp); (void) fputs(">\n", DbgFp); } /* ** NewClient -- allocate memory for a new CLIENT. ** ** Parameters: ** addr - RMP (Ethernet) address of new client. ** ** Returns: ** Ptr to new CLIENT or NULL if we ran out of memory. ** ** Side Effects: ** - Memory will be malloc'd for the new CLIENT. ** - If malloc() fails, a log message will be generated. */ CLIENT * NewClient(u_int8_t *addr) { CLIENT *ctmp; if ((ctmp = (CLIENT *) malloc(sizeof(CLIENT))) == NULL) { syslog(LOG_ERR, "NewClient: out of memory (%s)", GetEtherAddr(addr)); return(NULL); } memset(ctmp, 0, sizeof(CLIENT)); memmove(&ctmp->addr[0], addr, RMP_ADDRLEN); return(ctmp); } /* ** FreeClient -- free linked list of Clients. ** ** Parameters: ** None. ** ** Returns: ** Nothing. ** ** Side Effects: ** - All malloc'd memory associated with the linked list of ** CLIENTS will be free'd; `Clients' will be set to NULL. ** ** Warnings: ** - This routine must be called with SIGHUP blocked. */ void FreeClients(void) { CLIENT *ctmp; while (Clients != NULL) { ctmp = Clients; Clients = Clients->next; FreeClient(ctmp); } } /* ** NewStr -- allocate memory for a character array. ** ** Parameters: ** str - null terminated character array. ** ** Returns: ** Ptr to new character array or NULL if we ran out of memory. ** ** Side Effects: ** - Memory will be malloc'd for the new character array. ** - If malloc() fails, a log message will be generated. */ char * NewStr(char *str) { char *stmp; if ((stmp = (char *)malloc((unsigned) (strlen(str)+1))) == NULL) { syslog(LOG_ERR, "NewStr: out of memory (%s)", str); return(NULL); } (void) strcpy(stmp, str); return(stmp); } /* ** To save time, NewConn and FreeConn maintain a cache of one RMPCONN ** in `LastFree' (defined below). */ static RMPCONN *LastFree = NULL; /* ** NewConn -- allocate memory for a new RMPCONN connection. ** ** Parameters: ** rconn - initialization template for new connection. ** ** Returns: ** Ptr to new RMPCONN or NULL if we ran out of memory. ** ** Side Effects: ** - Memory may be malloc'd for the new RMPCONN (if not cached). ** - If malloc() fails, a log message will be generated. */ RMPCONN * NewConn(RMPCONN *rconn) { RMPCONN *rtmp; if (LastFree == NULL) { /* nothing cached; make a new one */ if ((rtmp = (RMPCONN *) malloc(sizeof(RMPCONN))) == NULL) { syslog(LOG_ERR, "NewConn: out of memory (%s)", EnetStr(rconn)); return(NULL); } } else { /* use the cached RMPCONN */ rtmp = LastFree; LastFree = NULL; } /* * Copy template into `rtmp', init file descriptor to `-1' and * set ptr to next elem NULL. */ memmove((char *)rtmp, (char *)rconn, sizeof(RMPCONN)); rtmp->bootfd = -1; rtmp->next = NULL; return(rtmp); } /* ** FreeConn -- Free memory associated with an RMPCONN connection. ** ** Parameters: ** rtmp - ptr to RMPCONN to be free'd. ** ** Returns: ** Nothing. ** ** Side Effects: ** - Memory associated with `rtmp' may be free'd (or cached). ** - File desc associated with `rtmp->bootfd' will be closed. */ void FreeConn(RMPCONN *rtmp) { /* * If the file descriptor is in use, close the file. */ if (rtmp->bootfd >= 0) { (void) close(rtmp->bootfd); rtmp->bootfd = -1; } if (LastFree == NULL) /* cache for next time */ rtmp = LastFree; else /* already one cached; free this one */ free((char *)rtmp); } /* ** FreeConns -- free linked list of RMPCONN connections. ** ** Parameters: ** None. ** ** Returns: ** Nothing. ** ** Side Effects: ** - All malloc'd memory associated with the linked list of ** connections will be free'd; `RmpConns' will be set to NULL. ** - If LastFree is != NULL, it too will be free'd & NULL'd. ** ** Warnings: ** - This routine must be called with SIGHUP blocked. */ void FreeConns(void) { RMPCONN *rtmp; while (RmpConns != NULL) { rtmp = RmpConns; RmpConns = RmpConns->next; FreeConn(rtmp); } if (LastFree != NULL) { free((char *)LastFree); LastFree = NULL; } } /* ** AddConn -- Add a connection to the linked list of connections. ** ** Parameters: ** rconn - connection to be added. ** ** Returns: ** Nothing. ** ** Side Effects: ** - RmpConn will point to new connection. ** ** Warnings: ** - This routine must be called with SIGHUP blocked. */ void AddConn(RMPCONN *rconn) { if (RmpConns != NULL) rconn->next = RmpConns; RmpConns = rconn; } /* ** FindConn -- Find a connection in the linked list of connections. ** ** We use the RMP (Ethernet) address as the basis for determining ** if this is the same connection. According to the Remote Maint ** Protocol, we can only have one connection with any machine. ** ** Parameters: ** rconn - connection to be found. ** ** Returns: ** Matching connection from linked list or NULL if not found. ** ** Side Effects: ** None. ** ** Warnings: ** - This routine must be called with SIGHUP blocked. */ RMPCONN * FindConn(RMPCONN *rconn) { RMPCONN *rtmp; for (rtmp = RmpConns; rtmp != NULL; rtmp = rtmp->next) if (bcmp((char *)&rconn->rmp.hp_hdr.saddr[0], (char *)&rtmp->rmp.hp_hdr.saddr[0], RMP_ADDRLEN) == 0) break; return(rtmp); } /* ** RemoveConn -- Remove a connection from the linked list of connections. ** ** Parameters: ** rconn - connection to be removed. ** ** Returns: ** Nothing. ** ** Side Effects: ** - If found, an RMPCONN will cease to exist and it will ** be removed from the linked list. ** ** Warnings: ** - This routine must be called with SIGHUP blocked. */ void RemoveConn(RMPCONN *rconn) { RMPCONN *thisrconn, *lastrconn; if (RmpConns == rconn) { /* easy case */ RmpConns = RmpConns->next; FreeConn(rconn); } else { /* must traverse linked list */ lastrconn = RmpConns; /* set back ptr */ thisrconn = lastrconn->next; /* set current ptr */ while (thisrconn != NULL) { if (rconn == thisrconn) { /* found it */ lastrconn->next = thisrconn->next; FreeConn(thisrconn); break; } lastrconn = thisrconn; thisrconn = thisrconn->next; } } } Index: head/libexec/revnetgroup/parse_netgroup.c =================================================================== --- head/libexec/revnetgroup/parse_netgroup.c (revision 262135) +++ head/libexec/revnetgroup/parse_netgroup.c (revision 262136) @@ -1,364 +1,360 @@ /* * Copyright (c) 1992, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Rick Macklem at The University of Guelph. * * 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #ifndef lint static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ /* * This is a specially hacked-up version of getnetgrent.c used to parse * data from the stored hash table of netgroup info rather than from a * file. It's used mainly for the parse_netgroup() function. All the YP * stuff and file support has been stripped out since it isn't needed. */ #include #include #include #include #include #include "hash.h" /* * Static Variables and functions used by setnetgrent(), getnetgrent() and * __endnetgrent(). * There are two linked lists: * - linelist is just used by setnetgrent() to parse the net group file via. * parse_netgrp() * - netgrp is the list of entries for the current netgroup */ struct linelist { struct linelist *l_next; /* Chain ptr. */ int l_parsed; /* Flag for cycles */ char *l_groupname; /* Name of netgroup */ char *l_line; /* Netgroup entrie(s) to be parsed */ }; struct netgrp { struct netgrp *ng_next; /* Chain ptr */ char *ng_str[3]; /* Field pointers, see below */ }; #define NG_HOST 0 /* Host name */ #define NG_USER 1 /* User name */ #define NG_DOM 2 /* and Domain name */ static struct linelist *linehead = (struct linelist *)0; static struct netgrp *nextgrp = (struct netgrp *)0; static struct { struct netgrp *gr; char *grname; } grouphead = { (struct netgrp *)0, (char *)0, }; static int parse_netgrp(char *group); static struct linelist *read_for_group(char *group); extern struct group_entry *gtable[]; /* * setnetgrent() * Parse the netgroup file looking for the netgroup and build the list * of netgrp structures. Let parse_netgrp() and read_for_group() do * most of the work. */ void __setnetgrent(char *group) { /* Sanity check */ if (group == NULL || !strlen(group)) return; if (grouphead.gr == (struct netgrp *)0 || strcmp(group, grouphead.grname)) { __endnetgrent(); if (parse_netgrp(group)) __endnetgrent(); else { grouphead.grname = (char *) malloc(strlen(group) + 1); strcpy(grouphead.grname, group); } } nextgrp = grouphead.gr; } /* * Get the next netgroup off the list. */ int __getnetgrent(char **hostp, char **userp, char **domp) { if (nextgrp) { *hostp = nextgrp->ng_str[NG_HOST]; *userp = nextgrp->ng_str[NG_USER]; *domp = nextgrp->ng_str[NG_DOM]; nextgrp = nextgrp->ng_next; return (1); } return (0); } /* * __endnetgrent() - cleanup */ void __endnetgrent(void) { struct linelist *lp, *olp; struct netgrp *gp, *ogp; lp = linehead; while (lp) { olp = lp; lp = lp->l_next; free(olp->l_groupname); free(olp->l_line); free((char *)olp); } linehead = (struct linelist *)0; if (grouphead.grname) { free(grouphead.grname); grouphead.grname = (char *)0; } gp = grouphead.gr; while (gp) { ogp = gp; gp = gp->ng_next; if (ogp->ng_str[NG_HOST]) free(ogp->ng_str[NG_HOST]); if (ogp->ng_str[NG_USER]) free(ogp->ng_str[NG_USER]); if (ogp->ng_str[NG_DOM]) free(ogp->ng_str[NG_DOM]); free((char *)ogp); } grouphead.gr = (struct netgrp *)0; } /* * Parse the netgroup file setting up the linked lists. */ static int parse_netgrp(char *group) { char *spos, *epos; int len, strpos; #ifdef DEBUG int fields; #endif char *pos, *gpos; struct netgrp *grp; struct linelist *lp = linehead; /* * First, see if the line has already been read in. */ while (lp) { if (!strcmp(group, lp->l_groupname)) break; lp = lp->l_next; } if (lp == (struct linelist *)0 && (lp = read_for_group(group)) == (struct linelist *)0) return (1); if (lp->l_parsed) { #ifdef DEBUG /* * This error message is largely superfluous since the * code handles the error condition successfully, and * spewing it out from inside libc can actually hose * certain programs. */ warnx("cycle in netgroup %s", lp->l_groupname); #endif return (1); } else lp->l_parsed = 1; pos = lp->l_line; /* Watch for null pointer dereferences, dammit! */ while (pos != NULL && *pos != '\0') { if (*pos == '(') { grp = (struct netgrp *)malloc(sizeof (struct netgrp)); bzero((char *)grp, sizeof (struct netgrp)); grp->ng_next = grouphead.gr; grouphead.gr = grp; pos++; gpos = strsep(&pos, ")"); #ifdef DEBUG fields = 0; #endif for (strpos = 0; strpos < 3; strpos++) { if ((spos = strsep(&gpos, ","))) { #ifdef DEBUG fields++; #endif while (*spos == ' ' || *spos == '\t') spos++; if ((epos = strpbrk(spos, " \t"))) { *epos = '\0'; len = epos - spos; } else len = strlen(spos); if (len > 0) { grp->ng_str[strpos] = (char *) malloc(len + 1); bcopy(spos, grp->ng_str[strpos], len + 1); } } else { /* * All other systems I've tested * return NULL for empty netgroup * fields. It's up to user programs * to handle the NULLs appropriately. */ grp->ng_str[strpos] = NULL; } } #ifdef DEBUG /* * Note: on other platforms, malformed netgroup * entries are not normally flagged. While we * can catch bad entries and report them, we should * stay silent by default for compatibility's sake. */ if (fields < 3) warnx("bad entry (%s%s%s%s%s) in netgroup \"%s\"", grp->ng_str[NG_HOST] == NULL ? "" : grp->ng_str[NG_HOST], grp->ng_str[NG_USER] == NULL ? "" : ",", grp->ng_str[NG_USER] == NULL ? "" : grp->ng_str[NG_USER], grp->ng_str[NG_DOM] == NULL ? "" : ",", grp->ng_str[NG_DOM] == NULL ? "" : grp->ng_str[NG_DOM], lp->l_groupname); #endif } else { spos = strsep(&pos, ", \t"); if (parse_netgrp(spos)) continue; } /* Watch for null pointer dereferences, dammit! */ if (pos != NULL) while (*pos == ' ' || *pos == ',' || *pos == '\t') pos++; } return (0); } /* * Read the netgroup file and save lines until the line for the netgroup * is found. Return 1 if eof is encountered. */ static struct linelist * read_for_group(char *group) { char *pos, *spos, *linep = NULL, *olinep = NULL; int len, olen; int cont; struct linelist *lp; char line[LINSIZ + 1]; char *data = NULL; data = lookup (gtable, group); sprintf(line, "%s %s", group, data); pos = (char *)&line; #ifdef CANT_HAPPEN if (*pos == '#') continue; #endif while (*pos == ' ' || *pos == '\t') pos++; spos = pos; while (*pos != ' ' && *pos != '\t' && *pos != '\n' && *pos != '\0') pos++; len = pos - spos; while (*pos == ' ' || *pos == '\t') pos++; if (*pos != '\n' && *pos != '\0') { lp = (struct linelist *)malloc(sizeof (*lp)); lp->l_parsed = 0; lp->l_groupname = (char *)malloc(len + 1); bcopy(spos, lp->l_groupname, len); *(lp->l_groupname + len) = '\0'; len = strlen(pos); olen = 0; /* * Loop around handling line continuations. */ do { if (*(pos + len - 1) == '\n') len--; if (*(pos + len - 1) == '\\') { len--; cont = 1; } else cont = 0; if (len > 0) { linep = (char *)malloc(olen + len + 1); if (olen > 0) { bcopy(olinep, linep, olen); free(olinep); } bcopy(pos, linep + olen, len); olen += len; *(linep + olen) = '\0'; olinep = linep; } #ifdef CANT_HAPPEN if (cont) { if (fgets(line, LINSIZ, netf)) { pos = line; len = strlen(pos); } else cont = 0; } #endif } while (cont); lp->l_line = linep; lp->l_next = linehead; linehead = lp; #ifdef CANT_HAPPEN /* * If this is the one we wanted, we are done. */ if (!strcmp(lp->l_groupname, group)) #endif return (lp); } return ((struct linelist *)0); } Index: head/libexec/rlogind/rlogind.8 =================================================================== --- head/libexec/rlogind/rlogind.8 (revision 262135) +++ head/libexec/rlogind/rlogind.8 (revision 262136) @@ -1,197 +1,193 @@ .\" Copyright (c) 1983, 1989, 1991, 1993 .\" The Regents of the University of California. 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. -.\" 3. All advertising materials mentioning features or use of this software -.\" must display the following acknowledgement: -.\" This product includes software developed by the University of -.\" California, Berkeley and its contributors. -.\" 4. Neither the name of the University nor the names of its contributors +.\" 3. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. .\" .\" @(#)rlogind.8 8.1 (Berkeley) 6/4/93 .\" $FreeBSD$ .\" .Dd February 9, 2005 .Dt RLOGIND 8 .Os .Sh NAME .Nm rlogind .Nd remote login server .Sh SYNOPSIS .Nm .Op Fl Daln .Sh DESCRIPTION The .Nm utility is the server for the .Xr rlogin 1 program. The server provides a remote login facility with authentication based on privileged port numbers from trusted hosts. .Pp Options supported by .Nm : .Bl -tag -width indent .It Fl D Set TCP_NODELAY socket option. This improves responsiveness at the expense of some additional network traffic. .It Fl a Ask hostname for verification. .It Fl l Prevent any authentication based on the user's .Dq Pa .rhosts file, unless the user is logging in as the superuser. .It Fl n Disable keep-alive messages. .El .Pp The .Nm utility listens for service requests at the port indicated in the .Dq login service specification; see .Xr services 5 . When a service request is received the following protocol is initiated: .Bl -enum .It The server checks the client's source port. If the port is not in the range 512-1023, the server aborts the connection. .It The server checks the client's source address and requests the corresponding host name (see .Xr gethostbyaddr 3 , .Xr hosts 5 and .Xr named 8 ) . If the hostname cannot be determined, the dot-notation representation of the host address is used. If the hostname is in the same domain as the server (according to the last two components of the domain name), or if the .Fl a option is given, the addresses for the hostname are requested, verifying that the name and address correspond. Normal authentication is bypassed if the address verification fails. .El .Pp Once the source port and address have been checked, .Nm proceeds with the authentication process described in .Xr rshd 8 . It then allocates a pseudo terminal (see .Xr pty 4 ) , and manipulates file descriptors so that the slave half of the pseudo terminal becomes the .Em stdin , .Em stdout , and .Em stderr for a login process. The login process is an instance of the .Xr login 1 program, invoked with the .Fl f option if authentication has succeeded. If automatic authentication fails, the user is prompted to log in as if on a standard terminal line. .Pp The parent of the login process manipulates the master side of the pseudo terminal, operating as an intermediary between the login process and the client instance of the .Xr rlogin 1 program. In normal operation, the packet protocol described in .Xr pty 4 is invoked to provide .Ql ^S/^Q type facilities and propagate interrupt signals to the remote programs. The login process propagates the client terminal's baud rate and terminal type, as found in the environment variable, .Ev TERM ; see .Xr environ 7 . The screen or window size of the terminal is requested from the client, and window size changes from the client are propagated to the pseudo terminal. .Pp Transport-level keepalive messages are enabled unless the .Fl n option is present. The use of keepalive messages allows sessions to be timed out if the client crashes or becomes unreachable. .Sh FILES .Bl -tag -width /etc/hostsxxxxxxxx -compact .It Pa /etc/hosts .It Pa /etc/hosts.equiv .It Ev $HOME Ns Pa /.rhosts .It Pa /var/run/nologin .El .Sh DIAGNOSTICS All initial diagnostic messages are indicated by a leading byte with a value of 1, after which any network connections are closed. If there are no errors before .Xr login 1 is invoked, a null byte is returned as in indication of success. .Bl -tag -width Ds .It Sy Try again. A .Xr fork 2 by the server failed. .El .Sh SEE ALSO .Xr login 1 , .Xr ruserok 3 , .Xr hosts 5 , .Xr hosts.equiv 5 , .Xr login.conf 5 , .Xr nologin 5 , .Xr services 5 , .Xr rshd 8 .Sh HISTORY The .Nm utility appeared in .Bx 4.2 . .Pp IPv6 support was added by WIDE/KAME project. .Sh BUGS The authentication procedure used here assumes the integrity of each client machine and the connecting medium. This is insecure, but is useful in an .Dq open environment. .Pp A facility to allow all data exchanges to be encrypted should be present. .Pp A more extensible protocol should be used. Index: head/libexec/rlogind/rlogind.c =================================================================== --- head/libexec/rlogind/rlogind.c (revision 262135) +++ head/libexec/rlogind/rlogind.c (revision 262136) @@ -1,589 +1,585 @@ /*- * Copyright (c) 1983, 1988, 1989, 1993 * The Regents of the University of California. All rights reserved. * Copyright (c) 2002 Networks Associates Technology, Inc. * All rights reserved. * * Portions of this software were developed for the FreeBSD Project by * ThinkSec AS and NAI Labs, the Security Research Division of Network * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 * ("CBOSS"), as part of the DARPA CHATS research program. * * 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #if 0 #ifndef lint static const char copyright[] = "@(#) Copyright (c) 1983, 1988, 1989, 1993\n\ The Regents of the University of California. All rights reserved.\n"; #endif /* not lint */ #ifndef lint static const char sccsid[] = "@(#)rlogind.c 8.1 (Berkeley) 6/4/93"; #endif /* not lint */ #endif #include __FBSDID("$FreeBSD$"); /* * remote login server: * \0 * remuser\0 * locuser\0 * terminal_type/speed\0 * data */ #define FD_SETSIZE 16 /* don't need many bits for select */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef TIOCPKT_WINDOW #define TIOCPKT_WINDOW 0x80 #endif #define ARGSTR "Daln" char *env[2]; #define NMAX 30 char lusername[NMAX+1], rusername[NMAX+1]; static char term[64] = "TERM="; #define ENVSIZE (sizeof("TERM=")-1) /* skip null for concatenation */ int keepalive = 1; int check_all = 0; int no_delay; struct passwd *pwd; union sockunion { struct sockinet { u_char si_len; u_char si_family; u_short si_port; } su_si; struct sockaddr_in su_sin; struct sockaddr_in6 su_sin6; }; #define su_len su_si.si_len #define su_family su_si.si_family #define su_port su_si.si_port void doit(int, union sockunion *); int control(int, char *, int); void protocol(int, int); void cleanup(int); void fatal(int, char *, int); int do_rlogin(union sockunion *); void getstr(char *, int, char *); void setup_term(int); int do_krb_login(struct sockaddr_in *); void usage(void); int main(int argc, char *argv[]) { extern int __check_rhosts_file; union sockunion from; socklen_t fromlen; int ch, on; openlog("rlogind", LOG_PID | LOG_CONS, LOG_AUTH); opterr = 0; while ((ch = getopt(argc, argv, ARGSTR)) != -1) switch (ch) { case 'D': no_delay = 1; break; case 'a': check_all = 1; break; case 'l': __check_rhosts_file = 0; break; case 'n': keepalive = 0; break; case '?': default: usage(); break; } argc -= optind; argv += optind; fromlen = sizeof (from); if (getpeername(0, (struct sockaddr *)&from, &fromlen) < 0) { syslog(LOG_ERR,"Can't get peer name of remote host: %m"); fatal(STDERR_FILENO, "Can't get peer name of remote host", 1); } on = 1; if (keepalive && setsockopt(0, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof (on)) < 0) syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m"); if (no_delay && setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0) syslog(LOG_WARNING, "setsockopt (TCP_NODELAY): %m"); if (from.su_family == AF_INET) { on = IPTOS_LOWDELAY; if (setsockopt(0, IPPROTO_IP, IP_TOS, (char *)&on, sizeof(int)) < 0) syslog(LOG_WARNING, "setsockopt (IP_TOS): %m"); } doit(0, &from); return 0; } int child; int netf; char line[MAXPATHLEN]; int confirmed; struct winsize win = { 0, 0, 0, 0 }; void doit(int f, union sockunion *fromp) { int master, pid, on = 1; int authenticated = 0; char hostname[2 * MAXHOSTNAMELEN + 1]; char nameinfo[2 * INET6_ADDRSTRLEN + 1]; char c; alarm(60); read(f, &c, 1); if (c != 0) exit(1); alarm(0); realhostname_sa(hostname, sizeof(hostname) - 1, (struct sockaddr *)fromp, fromp->su_len); /* error check ? */ fromp->su_port = ntohs((u_short)fromp->su_port); hostname[sizeof(hostname) - 1] = '\0'; { if ((fromp->su_family != AF_INET #ifdef INET6 && fromp->su_family != AF_INET6 #endif ) || fromp->su_port >= IPPORT_RESERVED || fromp->su_port < IPPORT_RESERVED/2) { getnameinfo((struct sockaddr *)fromp, fromp->su_len, nameinfo, sizeof(nameinfo), NULL, 0, NI_NUMERICHOST); /* error check ? */ syslog(LOG_NOTICE, "Connection from %s on illegal port", nameinfo); fatal(f, "Permission denied", 0); } #ifdef IP_OPTIONS if (fromp->su_family == AF_INET) { u_char optbuf[BUFSIZ/3]; socklen_t optsize = sizeof(optbuf); int ipproto, i; struct protoent *ip; if ((ip = getprotobyname("ip")) != NULL) ipproto = ip->p_proto; else ipproto = IPPROTO_IP; if (getsockopt(0, ipproto, IP_OPTIONS, (char *)optbuf, &optsize) == 0 && optsize != 0) { for (i = 0; i < optsize; ) { u_char c = optbuf[i]; if (c == IPOPT_LSRR || c == IPOPT_SSRR) { syslog(LOG_NOTICE, "Connection refused from %s with IP option %s", inet_ntoa(fromp->su_sin.sin_addr), c == IPOPT_LSRR ? "LSRR" : "SSRR"); exit(1); } if (c == IPOPT_EOL) break; i += (c == IPOPT_NOP) ? 1 : optbuf[i+1]; } } } #endif if (do_rlogin(fromp) == 0) authenticated++; } if (confirmed == 0) { write(f, "", 1); confirmed = 1; /* we sent the null! */ } netf = f; pid = forkpty(&master, line, NULL, &win); if (pid < 0) { if (errno == ENOENT) fatal(f, "Out of ptys", 0); else fatal(f, "Forkpty", 1); } if (pid == 0) { if (f > 2) /* f should always be 0, but... */ (void) close(f); setup_term(0); if (*lusername=='-') { syslog(LOG_ERR, "tried to pass user \"%s\" to login", lusername); fatal(STDERR_FILENO, "invalid user", 0); } if (authenticated) { execl(_PATH_LOGIN, "login", "-p", "-h", hostname, "-f", lusername, (char *)NULL); } else execl(_PATH_LOGIN, "login", "-p", "-h", hostname, lusername, (char *)NULL); fatal(STDERR_FILENO, _PATH_LOGIN, 1); /*NOTREACHED*/ } ioctl(f, FIONBIO, &on); ioctl(master, FIONBIO, &on); ioctl(master, TIOCPKT, &on); signal(SIGCHLD, cleanup); protocol(f, master); signal(SIGCHLD, SIG_IGN); cleanup(0); } char magic[2] = { 0377, 0377 }; char oobdata[] = {TIOCPKT_WINDOW}; /* * Handle a "control" request (signaled by magic being present) * in the data stream. For now, we are only willing to handle * window size changes. */ int control(int pty, char *cp, int n) { struct winsize w; if (n < 4 + (int)sizeof(w) || cp[2] != 's' || cp[3] != 's') return (0); oobdata[0] &= ~TIOCPKT_WINDOW; /* we know he heard */ bcopy(cp+4, (char *)&w, sizeof(w)); w.ws_row = ntohs(w.ws_row); w.ws_col = ntohs(w.ws_col); w.ws_xpixel = ntohs(w.ws_xpixel); w.ws_ypixel = ntohs(w.ws_ypixel); (void)ioctl(pty, TIOCSWINSZ, &w); return (4+sizeof (w)); } /* * rlogin "protocol" machine. */ void protocol(int f, int p) { char pibuf[1024+1], fibuf[1024], *pbp = NULL, *fbp = NULL; int pcc = 0, fcc = 0; int cc, nfd, n; char cntl; /* * Must ignore SIGTTOU, otherwise we'll stop * when we try and set slave pty's window shape * (our controlling tty is the master pty). */ (void) signal(SIGTTOU, SIG_IGN); send(f, oobdata, 1, MSG_OOB); /* indicate new rlogin */ if (f > p) nfd = f + 1; else nfd = p + 1; if (nfd > FD_SETSIZE) { syslog(LOG_ERR, "select mask too small, increase FD_SETSIZE"); fatal(f, "internal error (select mask too small)", 0); } for (;;) { fd_set ibits, obits, ebits, *omask; FD_ZERO(&ebits); FD_ZERO(&ibits); FD_ZERO(&obits); omask = (fd_set *)NULL; if (fcc) { FD_SET(p, &obits); omask = &obits; } else FD_SET(f, &ibits); if (pcc >= 0) { if (pcc) { FD_SET(f, &obits); omask = &obits; } else FD_SET(p, &ibits); } FD_SET(p, &ebits); if ((n = select(nfd, &ibits, omask, &ebits, 0)) < 0) { if (errno == EINTR) continue; fatal(f, "select", 1); } if (n == 0) { /* shouldn't happen... */ sleep(5); continue; } #define pkcontrol(c) ((c)&(TIOCPKT_FLUSHWRITE|TIOCPKT_NOSTOP|TIOCPKT_DOSTOP)) if (FD_ISSET(p, &ebits)) { cc = read(p, &cntl, 1); if (cc == 1 && pkcontrol(cntl)) { cntl |= oobdata[0]; send(f, &cntl, 1, MSG_OOB); if (cntl & TIOCPKT_FLUSHWRITE) { pcc = 0; FD_CLR(p, &ibits); } } } if (FD_ISSET(f, &ibits)) { fcc = read(f, fibuf, sizeof(fibuf)); if (fcc < 0 && errno == EWOULDBLOCK) fcc = 0; else { char *cp; int left, n; if (fcc <= 0) break; fbp = fibuf; top: for (cp = fibuf; cp < fibuf+fcc-1; cp++) if (cp[0] == magic[0] && cp[1] == magic[1]) { left = fcc - (cp-fibuf); n = control(p, cp, left); if (n) { left -= n; if (left > 0) bcopy(cp+n, cp, left); fcc -= n; goto top; /* n^2 */ } } FD_SET(p, &obits); /* try write */ } } if (FD_ISSET(p, &obits) && fcc > 0) { cc = write(p, fbp, fcc); if (cc > 0) { fcc -= cc; fbp += cc; } } if (FD_ISSET(p, &ibits)) { pcc = read(p, pibuf, sizeof (pibuf)); pbp = pibuf; if (pcc < 0 && errno == EWOULDBLOCK) pcc = 0; else if (pcc <= 0) break; else if (pibuf[0] == 0) { pbp++, pcc--; FD_SET(f, &obits); /* try write */ } else { if (pkcontrol(pibuf[0])) { pibuf[0] |= oobdata[0]; send(f, &pibuf[0], 1, MSG_OOB); } pcc = 0; } } if ((FD_ISSET(f, &obits)) && pcc > 0) { cc = write(f, pbp, pcc); if (cc < 0 && errno == EWOULDBLOCK) { /* * This happens when we try write after read * from p, but some old kernels balk at large * writes even when select returns true. */ if (!FD_ISSET(p, &ibits)) sleep(5); continue; } if (cc > 0) { pcc -= cc; pbp += cc; } } } } void cleanup(int signo __unused) { shutdown(netf, SHUT_RDWR); exit(1); } void fatal(int f, char *msg, int syserr) { int len; char buf[BUFSIZ], *bp = buf; /* * Prepend binary one to message if we haven't sent * the magic null as confirmation. */ if (!confirmed) *bp++ = '\01'; /* error indicator */ if (syserr) len = snprintf(bp, sizeof(buf), "rlogind: %s: %s.\r\n", msg, strerror(errno)); else len = snprintf(bp, sizeof(buf), "rlogind: %s.\r\n", msg); if (len < 0) len = 0; (void) write(f, buf, bp + len - buf); exit(1); } int do_rlogin(union sockunion *dest) { getstr(rusername, sizeof(rusername), "remuser too long"); getstr(lusername, sizeof(lusername), "locuser too long"); getstr(term+ENVSIZE, sizeof(term)-ENVSIZE, "Terminal type too long"); pwd = getpwnam(lusername); if (pwd == NULL) return (-1); /* XXX why don't we syslog() failure? */ return (iruserok_sa(dest, dest->su_len, pwd->pw_uid == 0, rusername, lusername)); } void getstr(char *buf, int cnt, char *errmsg) { char c; do { if (read(STDIN_FILENO, &c, 1) != 1) exit(1); if (--cnt < 0) fatal(STDOUT_FILENO, errmsg, 0); *buf++ = c; } while (c != 0); } extern char **environ; void setup_term(int fd) { char *cp; char *speed; struct termios tt, def; cp = strchr(term + ENVSIZE, '/'); #ifndef notyet tcgetattr(fd, &tt); if (cp) { *cp++ = '\0'; speed = cp; cp = strchr(speed, '/'); if (cp) *cp++ = '\0'; cfsetspeed(&tt, atoi(speed)); } cfmakesane(&def); tt.c_iflag = def.c_iflag; tt.c_oflag = def.c_oflag; tt.c_lflag = def.c_lflag; tcsetattr(fd, TCSAFLUSH, &tt); #else if (cp) { *cp++ = '\0'; speed = cp; cp = strchr(speed, '/'); if (cp) *cp++ = '\0'; tcgetattr(fd, &tt); cfsetspeed(&tt, atoi(speed)); tcsetattr(fd, TCSAFLUSH, &tt); } #endif env[0] = term; env[1] = 0; environ = env; } void usage(void) { syslog(LOG_ERR, "usage: rlogind [-" ARGSTR "]"); } Index: head/libexec/rpc.rstatd/rpc.rstatd.8 =================================================================== --- head/libexec/rpc.rstatd/rpc.rstatd.8 (revision 262135) +++ head/libexec/rpc.rstatd/rpc.rstatd.8 (revision 262136) @@ -1,65 +1,61 @@ .\" -*- nroff -*- .\" .\" Copyright (c) 1985, 1991 The Regents of the University of California. .\" 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. -.\" 3. All advertising materials mentioning features or use of this software -.\" must display the following acknowledgement: -.\" This product includes software developed by the University of -.\" California, Berkeley and its contributors. -.\" 4. Neither the name of the University nor the names of its contributors +.\" 3. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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$ .\" .Dd June 7, 1993 .Dt RPC.RSTATD 8 .Os .Sh NAME .Nm rpc.rstatd .Nd kernel statistics server .Sh SYNOPSIS .Nm /usr/libexec/rpc.rstatd .Sh DESCRIPTION The .Nm utility is a server which returns performance statistics obtained from the kernel. These statistics are read using the .Xr rup 1 command. The .Nm daemon is normally invoked by .Xr inetd 8 . .Pp The .Nm utility uses an .Tn RPC protocol defined in .Pa /usr/include/rpcsvc/rstat.x . .Sh SEE ALSO .Xr rup 1 , .Xr inetd 8 Index: head/libexec/rpc.rstatd/rstatd.c =================================================================== --- head/libexec/rpc.rstatd/rstatd.c (revision 262135) +++ head/libexec/rpc.rstatd/rstatd.c (revision 262136) @@ -1,133 +1,129 @@ /*- * Copyright (c) 1993, John Brezak * 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #ifndef lint static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ #include #include #include #include #include extern void rstat_service(struct svc_req *, SVCXPRT *); int from_inetd = 1; /* started from inetd ? */ int closedown = 20; /* how long to wait before going dormant */ void cleanup(int sig __unused) { (void) rpcb_unset(RSTATPROG, RSTATVERS_TIME, NULL); (void) rpcb_unset(RSTATPROG, RSTATVERS_SWTCH, NULL); (void) rpcb_unset(RSTATPROG, RSTATVERS_ORIG, NULL); exit(0); } int main(int argc, char *argv[]) { SVCXPRT *transp; int ok; struct sockaddr_storage from; socklen_t fromlen; if (argc == 2) closedown = atoi(argv[1]); if (closedown <= 0) closedown = 20; /* * See if inetd started us */ fromlen = sizeof(from); if (getsockname(0, (struct sockaddr *)&from, &fromlen) < 0) { from_inetd = 0; } if (!from_inetd) { daemon(0, 0); (void)rpcb_unset(RSTATPROG, RSTATVERS_TIME, NULL); (void)rpcb_unset(RSTATPROG, RSTATVERS_SWTCH, NULL); (void)rpcb_unset(RSTATPROG, RSTATVERS_ORIG, NULL); (void) signal(SIGINT, cleanup); (void) signal(SIGTERM, cleanup); (void) signal(SIGHUP, cleanup); } openlog("rpc.rstatd", LOG_CONS|LOG_PID, LOG_DAEMON); if (from_inetd) { transp = svc_tli_create(0, NULL, NULL, 0, 0); if (transp == NULL) { syslog(LOG_ERR, "cannot create udp service."); exit(1); } ok = svc_reg(transp, RSTATPROG, RSTATVERS_TIME, rstat_service, NULL); } else ok = svc_create(rstat_service, RSTATPROG, RSTATVERS_TIME, "udp"); if (!ok) { syslog(LOG_ERR, "unable to register (RSTATPROG, RSTATVERS_TIME, %s)", (!from_inetd)?"udp":"(inetd)"); exit(1); } if (from_inetd) ok = svc_reg(transp, RSTATPROG, RSTATVERS_SWTCH, rstat_service, NULL); else ok = svc_create(rstat_service, RSTATPROG, RSTATVERS_SWTCH, "udp"); if (!ok) { syslog(LOG_ERR, "unable to register (RSTATPROG, RSTATVERS_SWTCH, %s)", (!from_inetd)?"udp":"(inetd)"); exit(1); } if (from_inetd) ok = svc_reg(transp, RSTATPROG, RSTATVERS_ORIG, rstat_service, NULL); else ok = svc_create(rstat_service, RSTATPROG, RSTATVERS_ORIG, "udp"); if (!ok) { syslog(LOG_ERR, "unable to register (RSTATPROG, RSTATVERS_ORIG, %s)", (!from_inetd)?"udp":"(inetd)"); exit(1); } svc_run(); syslog(LOG_ERR, "svc_run returned"); exit(1); } Index: head/libexec/rpc.rusersd/extern.h =================================================================== --- head/libexec/rpc.rusersd/extern.h (revision 262135) +++ head/libexec/rpc.rusersd/extern.h (revision 262136) @@ -1,38 +1,34 @@ /*- * Copyright (c) 1993, John Brezak * 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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$ */ extern int from_inetd; void rusers_service(struct svc_req *, SVCXPRT *); Index: head/libexec/rpc.rusersd/rpc.rusersd.8 =================================================================== --- head/libexec/rpc.rusersd/rpc.rusersd.8 (revision 262135) +++ head/libexec/rpc.rusersd/rpc.rusersd.8 (revision 262136) @@ -1,68 +1,64 @@ .\" -*- nroff -*- .\" .\" Copyright (c) 1985, 1991 The Regents of the University of California. .\" 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. -.\" 3. All advertising materials mentioning features or use of this software -.\" must display the following acknowledgement: -.\" This product includes software developed by the University of -.\" California, Berkeley and its contributors. -.\" 4. Neither the name of the University nor the names of its contributors +.\" 3. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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$ .\" .Dd June 7, 1993 .Dt RPC.RUSERSD 8 .Os .Sh NAME .Nm rpc.rusersd .Nd logged in users server .Sh SYNOPSIS .Nm /usr/libexec/rpc.rusersd .Sh DESCRIPTION The .Nm utility is a server which returns information about users currently logged in to the system. .Pp The currently logged in users are queried using the .Xr rusers 1 command. The .Nm daemon is normally invoked by .Xr inetd 8 . .Pp The .Nm utility uses an .Tn RPC protocol defined in .Pa /usr/include/rpcsvc/rnusers.x . .Sh SEE ALSO .Xr rusers 1 , .Xr w 1 , .Xr who 1 , .Xr inetd 8 Index: head/libexec/rpc.rusersd/rusers_proc.c =================================================================== --- head/libexec/rpc.rusersd/rusers_proc.c (revision 262135) +++ head/libexec/rpc.rusersd/rusers_proc.c (revision 262136) @@ -1,336 +1,332 @@ /*- * Copyright (c) 1993, John Brezak * 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #ifndef lint static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ #ifdef DEBUG #include #endif #include #include #include #include #include #include #include #ifdef XIDLE #include #include #include #endif #include #include "extern.h" #ifndef _PATH_DEV #define _PATH_DEV "/dev" #endif static utmpidle utmp_idle[MAXUSERS]; static utmp old_utmp[MAXUSERS]; static struct utmpx utmp_list[MAXUSERS]; #ifdef XIDLE static Display *dpy; static jmp_buf openAbort; static void abortOpen(void) { longjmp (openAbort, 1); } XqueryIdle(char *display) { int first_event, first_error; Time IdleTime; (void) signal (SIGALRM, abortOpen); (void) alarm ((unsigned) 10); if (!setjmp (openAbort)) { if (!(dpy= XOpenDisplay(display))) { syslog(LOG_ERR, "Cannot open display %s", display); return(-1); } if (XidleQueryExtension(dpy, &first_event, &first_error)) { if (!XGetIdleTime(dpy, &IdleTime)) { syslog(LOG_ERR, "%s: unable to get idle time", display); return(-1); } } else { syslog(LOG_ERR, "%s: Xidle extension not loaded", display); return(-1); } XCloseDisplay(dpy); } else { syslog(LOG_ERR, "%s: server grabbed for over 10 seconds", display); return(-1); } (void) signal (SIGALRM, SIG_DFL); (void) alarm ((unsigned) 0); IdleTime /= 1000; return((IdleTime + 30) / 60); } #endif static u_int getidle(const char *tty, const char *display __unused) { struct stat st; char ttyname[PATH_MAX]; time_t now; u_long idle; /* * If this is an X terminal or console, then try the * XIdle extension */ #ifdef XIDLE if (display && *display && (idle = XqueryIdle(display)) >= 0) return(idle); #endif idle = 0; if (*tty == 'X') { u_long kbd_idle, mouse_idle; #if !defined(__FreeBSD__) kbd_idle = getidle("kbd", NULL); #else kbd_idle = getidle("vga", NULL); #endif mouse_idle = getidle("mouse", NULL); idle = (kbd_idle < mouse_idle)?kbd_idle:mouse_idle; } else { sprintf(ttyname, "%s/%s", _PATH_DEV, tty); if (stat(ttyname, &st) < 0) { #ifdef DEBUG printf("%s: %s\n", ttyname, strerror(errno)); #endif return(-1); } time(&now); #ifdef DEBUG printf("%s: now=%d atime=%d\n", ttyname, now, st.st_atime); #endif idle = now - st.st_atime; idle = (idle + 30) / 60; /* secs->mins */ } return(idle); } static utmpidlearr * do_names_2(void) { static utmpidlearr ut; struct utmpx *usr; int nusers = 0; memset(&ut, 0, sizeof(ut)); ut.utmpidlearr_val = &utmp_idle[0]; setutxent(); while ((usr = getutxent()) != NULL && nusers < MAXUSERS) { if (usr->ut_type != USER_PROCESS) continue; memcpy(&utmp_list[nusers], usr, sizeof(*usr)); utmp_idle[nusers].ui_utmp.ut_time = usr->ut_tv.tv_sec; utmp_idle[nusers].ui_idle = getidle(usr->ut_line, usr->ut_host); utmp_idle[nusers].ui_utmp.ut_line = utmp_list[nusers].ut_line; utmp_idle[nusers].ui_utmp.ut_name = utmp_list[nusers].ut_user; utmp_idle[nusers].ui_utmp.ut_host = utmp_list[nusers].ut_host; nusers++; } endutxent(); ut.utmpidlearr_len = nusers; return(&ut); } static int * rusers_num(void *argp __unused, struct svc_req *rqstp __unused) { static int num_users = 0; struct utmpx *usr; setutxent(); while ((usr = getutxent()) != NULL) { if (usr->ut_type != USER_PROCESS) continue; num_users++; } endutxent(); return(&num_users); } static utmparr * do_names_1(void) { utmpidlearr *utidle; static utmparr ut; unsigned int i; bzero((char *)&ut, sizeof(ut)); utidle = do_names_2(); if (utidle) { ut.utmparr_len = utidle->utmpidlearr_len; ut.utmparr_val = &old_utmp[0]; for (i = 0; i < ut.utmparr_len; i++) bcopy(&utmp_idle[i].ui_utmp, &old_utmp[i], sizeof(old_utmp[0])); } return(&ut); } utmpidlearr * rusersproc_names_2_svc(void *argp __unused, struct svc_req *rqstp __unused) { return (do_names_2()); } utmpidlearr * rusersproc_allnames_2_svc(void *argp __unused, struct svc_req *rqstp __unused) { return (do_names_2()); } utmparr * rusersproc_names_1_svc(void *argp __unused, struct svc_req *rqstp __unused) { return (do_names_1()); } utmparr * rusersproc_allnames_1_svc(void *argp __unused, struct svc_req *rqstp __unused) { return (do_names_1()); } typedef void *(*rusersproc_t)(void *, struct svc_req *); void rusers_service(struct svc_req *rqstp, SVCXPRT *transp) { union { int fill; } argument; char *result; xdrproc_t xdr_argument, xdr_result; rusersproc_t local; switch (rqstp->rq_proc) { case NULLPROC: (void)svc_sendreply(transp, (xdrproc_t)xdr_void, NULL); goto leave; case RUSERSPROC_NUM: xdr_argument = (xdrproc_t)xdr_void; xdr_result = (xdrproc_t)xdr_int; local = (rusersproc_t)rusers_num; break; case RUSERSPROC_NAMES: xdr_argument = (xdrproc_t)xdr_void; xdr_result = (xdrproc_t)xdr_utmpidlearr; switch (rqstp->rq_vers) { case RUSERSVERS_ORIG: local = (rusersproc_t)rusersproc_names_1_svc; break; case RUSERSVERS_IDLE: local = (rusersproc_t)rusersproc_names_2_svc; break; default: svcerr_progvers(transp, RUSERSVERS_ORIG, RUSERSVERS_IDLE); goto leave; /*NOTREACHED*/ } break; case RUSERSPROC_ALLNAMES: xdr_argument = (xdrproc_t)xdr_void; xdr_result = (xdrproc_t)xdr_utmpidlearr; switch (rqstp->rq_vers) { case RUSERSVERS_ORIG: local = (rusersproc_t)rusersproc_allnames_1_svc; break; case RUSERSVERS_IDLE: local = (rusersproc_t)rusersproc_allnames_2_svc; break; default: svcerr_progvers(transp, RUSERSVERS_ORIG, RUSERSVERS_IDLE); goto leave; /*NOTREACHED*/ } break; default: svcerr_noproc(transp); goto leave; } bzero(&argument, sizeof(argument)); if (!svc_getargs(transp, (xdrproc_t)xdr_argument, &argument)) { svcerr_decode(transp); goto leave; } result = (*local)(&argument, rqstp); if (result != NULL && !svc_sendreply(transp, (xdrproc_t)xdr_result, result)) { svcerr_systemerr(transp); } if (!svc_freeargs(transp, (xdrproc_t)xdr_argument, &argument)) { syslog(LOG_ERR, "unable to free arguments"); exit(1); } leave: if (from_inetd) exit(0); } Index: head/libexec/rpc.rusersd/rusersd.c =================================================================== --- head/libexec/rpc.rusersd/rusersd.c (revision 262135) +++ head/libexec/rpc.rusersd/rusersd.c (revision 262136) @@ -1,116 +1,112 @@ /*- * Copyright (c) 1993, John Brezak * 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #ifndef lint static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ #include #include #include #include #include #include #include "extern.h" int from_inetd = 1; static void cleanup(int sig __unused) { (void) rpcb_unset(RUSERSPROG, RUSERSVERS_IDLE, NULL); (void) rpcb_unset(RUSERSPROG, RUSERSVERS_ORIG, NULL); exit(0); } int main(int argc __unused, char *argv[] __unused) { SVCXPRT *transp = NULL; /* Keep compiler happy. */ int ok; struct sockaddr_storage from; socklen_t fromlen; /* * See if inetd started us */ fromlen = sizeof(from); if (getsockname(0, (struct sockaddr *)&from, &fromlen) < 0) { from_inetd = 0; } if (!from_inetd) { daemon(0, 0); (void) rpcb_unset(RUSERSPROG, RUSERSVERS_IDLE, NULL); (void) rpcb_unset(RUSERSPROG, RUSERSVERS_ORIG, NULL); (void) signal(SIGINT, cleanup); (void) signal(SIGTERM, cleanup); (void) signal(SIGHUP, cleanup); } openlog("rpc.rusersd", LOG_CONS|LOG_PID, LOG_DAEMON); if (from_inetd) { transp = svc_tli_create(0, NULL, NULL, 0, 0); if (transp == NULL) { syslog(LOG_ERR, "cannot create udp service."); exit(1); } ok = svc_reg(transp, RUSERSPROG, RUSERSVERS_IDLE, rusers_service, NULL); } else ok = svc_create(rusers_service, RUSERSPROG, RUSERSVERS_IDLE, "udp"); if (!ok) { syslog(LOG_ERR, "unable to register (RUSERSPROG, RUSERSVERS_IDLE, %s)", (!from_inetd)?"udp":"(inetd)"); exit(1); } if (from_inetd) ok = svc_reg(transp, RUSERSPROG, RUSERSVERS_ORIG, rusers_service, NULL); else ok = svc_create(rusers_service, RUSERSPROG, RUSERSVERS_ORIG, "udp"); if (!ok) { syslog(LOG_ERR, "unable to register (RUSERSPROG, RUSERSVERS_ORIG, %s)", (!from_inetd)?"udp":"(inetd)"); exit(1); } svc_run(); syslog(LOG_ERR, "svc_run returned"); exit(1); } Index: head/libexec/rpc.rwalld/rpc.rwalld.8 =================================================================== --- head/libexec/rpc.rwalld/rpc.rwalld.8 (revision 262135) +++ head/libexec/rpc.rwalld/rpc.rwalld.8 (revision 262136) @@ -1,83 +1,79 @@ .\" -*- nroff -*- .\" .\" Copyright (c) 1985, 1991 The Regents of the University of California. .\" 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. -.\" 3. All advertising materials mentioning features or use of this software -.\" must display the following acknowledgement: -.\" This product includes software developed by the University of -.\" California, Berkeley and its contributors. -.\" 4. Neither the name of the University nor the names of its contributors +.\" 3. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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$ .\" .Dd June 7, 1993 .Dt RPC.RWALLD 8 .Os .Sh NAME .Nm rpc.rwalld .Nd write messages to users currently logged in server .Sh SYNOPSIS .Nm /usr/libexec/rpc.rwalld .Op Fl n .Sh DESCRIPTION The .Nm utility is a server which will send a message to users currently logged in to the system. This server invokes the .Xr wall 1 command to actually write the messages to the system. .Pp The following option is available: .Bl -tag -width indent .It Fl n Do not become a daemon. This option is only available when .Nm is not invoked by .Xr inetd 8 . .El .Pp Messages are sent to this server by the .Xr rwall 1 command. The .Nm daemon is normally invoked by .Xr inetd 8 . .Pp The .Nm utility uses an .Tn RPC protocol defined in .Pa /usr/include/rpcsvc/rwall.x . .Sh SEE ALSO .Xr rwall 1 , .Xr wall 1 , .Xr inetd 8 Index: head/libexec/rshd/rshd.8 =================================================================== --- head/libexec/rshd/rshd.8 (revision 262135) +++ head/libexec/rshd/rshd.8 (revision 262136) @@ -1,272 +1,268 @@ .\" Copyright (c) 1983, 1989, 1991, 1993 .\" The Regents of the University of California. 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. -.\" 3. All advertising materials mentioning features or use of this software -.\" must display the following acknowledgement: -.\" This product includes software developed by the University of -.\" California, Berkeley and its contributors. -.\" 4. Neither the name of the University nor the names of its contributors +.\" 3. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. .\" .\" @(#)rshd.8 8.1 (Berkeley) 6/4/93 .\" $FreeBSD$ .\" .Dd June 4, 1993 .Dt RSHD 8 .Os .Sh NAME .Nm rshd .Nd remote shell server .Sh SYNOPSIS .Nm .Op Fl aDLln .Sh DESCRIPTION The .Nm utility is the server for the .Xr rcmd 3 routine and, consequently, for the .Xr rsh 1 utility. The server provides remote execution facilities with authentication based on privileged port numbers from trusted hosts. .Pp The .Nm utility listens for service requests at the port indicated in the .Dq cmd service specification; see .Xr services 5 . When a service request is received the following protocol is initiated: .Bl -enum .It The server checks the client's source port. If the port is not in the range 512-1023, the server aborts the connection. .It The server reads characters from the socket up to a .Tn NUL (`\e0') byte. The resultant string is interpreted as an .Tn ASCII number, base 10. .It If the number received in step 2 is non-zero, it is interpreted as the port number of a secondary stream to be used for the .Em stderr . A second connection is then created to the specified port on the client's machine. The source port of this second connection is also in the range 512-1023. .It The server checks the client's source address and requests the corresponding host name (see .Xr gethostbyaddr 3 , .Xr hosts 5 and .Xr named 8 ) . If the hostname cannot be determined or the hostname and address do not match after verification, the dot-notation representation of the host address is used. .It A null terminated user name of at most 16 characters is retrieved on the initial socket. This user name is interpreted as the user identity on the .Em client Ns 's machine. .It A null terminated user name of at most 16 characters is retrieved on the initial socket. This user name is interpreted as a user identity to use on the .Em server Ns 's machine. .It A null terminated command to be passed to a shell is retrieved on the initial socket. The length of the command is limited by the upper bound on the size of the system's argument list. .It The .Nm utility then validates the user using .Xr ruserok 3 , which uses the file .Pa /etc/hosts.equiv and the .Pa .rhosts file found in the user's home directory. The .Fl l option prevents .Xr ruserok 3 from doing any validation based on the user's .Pa .rhosts file, unless the user is the superuser. .It A .Tn NUL byte is returned on the initial socket and the command line is passed to the normal login shell of the user. The shell inherits the network connections established by .Nm . .El .Pp The options are as follows: .Bl -tag -width indent .It Fl a This flag is ignored, and is present for compatibility purposes. .It Fl D Sets the TCP_NODELAY socket option, which improves the performance of small back-to-back writes at the expense of additional network traffic. .It Fl L Causes all successful accesses to be logged to .Xr syslogd 8 as .Li auth.info messages. .It Fl l Do not use the user's .Pa .rhosts file for authentication, unless the user is the superuser. .It Fl n Turn off transport level keepalive messages. This will prevent sessions from timing out if the client crashes or becomes unreachable. .El .Sh FILES .Bl -tag -width /var/run/nologin -compact .It Pa /etc/hosts .It Pa /etc/hosts.equiv .It Pa /etc/login.conf .It Ev $HOME Ns Pa /.rhosts .Pp .It Pa /etc/pam.conf .Nm uses .Pa /etc/pam.conf entries with service name .Dq rsh . Authentication modules requiring passwords (such as .Nm pam_unix ) are not supported. .El .Sh DIAGNOSTICS Except for the last one listed below, all diagnostic messages are returned on the initial socket, after which any network connections are closed. An error is indicated by a leading byte with a value of 1 (0 is returned in step 10 above upon successful completion of all the steps prior to the execution of the login shell). .Bl -tag -width indent .It Sy Locuser too long. The name of the user on the client's machine is longer than 16 characters. .It Sy Ruser too long. The name of the user on the remote machine is longer than 16 characters. .It Sy Command too long. The command line passed exceeds the size of the argument list (as configured into the system). .It Sy Login incorrect. No password file entry for the user name existed or the authentication procedure described above failed. .It Sy Remote directory. The .Xr chdir 2 function to the home directory failed. .It Sy Logins not available right now. The .Xr rsh 1 utility was attempted outside the allowed hours defined in .Pa /etc/login.conf for the local user's login class. .It Sy Can't make pipe. The pipe needed for the .Em stderr , was not created. .It Sy Can't fork; try again. A .Xr fork 2 by the server failed. .It Sy : ... The user's login shell could not be started. This message is returned on the connection associated with the .Em stderr , and is not preceded by a flag byte. .El .Sh SEE ALSO .Xr rlogin 1 , .Xr rsh 1 , .Xr gethostbyaddr 3 , .Xr rcmd 3 , .Xr ruserok 3 , .Xr hosts 5 , .Xr hosts.equiv 5 , .Xr login.conf 5 , .Xr services 5 , .Xr named 8 , .Xr rlogind 8 , .Xr syslogd 8 .Sh HISTORY IPv6 support was added by WIDE/KAME project. .Sh BUGS The authentication procedure used here assumes the integrity of each client machine and the connecting medium. This is insecure, but is useful in an .Dq open environment. .Pp A facility to allow all data exchanges to be encrypted should be present. .Pp Post-PAM, .Fx also needs the following patch applied besides properly configuring .Pa .rhosts : .Bd -literal -offset indent --- etc/pam.d/rsh.orig Wed Dec 17 14:36:20 2003 +++ etc/pam.d/rsh Wed Dec 17 14:30:43 2003 @@ -9 +9 @@ -auth required pam_rhosts.so no_warn +auth required pam_rhosts.so no_warn allow_root .Ed .Pp A more extensible protocol (such as Telnet) should be used. Index: head/libexec/rshd/rshd.c =================================================================== --- head/libexec/rshd/rshd.c (revision 262135) +++ head/libexec/rshd/rshd.c (revision 262136) @@ -1,593 +1,589 @@ /*- * Copyright (c) 1988, 1989, 1992, 1993, 1994 * The Regents of the University of California. All rights reserved. * Copyright (c) 2002 Networks Associates Technology, Inc. * All rights reserved. * * Portions of this software were developed for the FreeBSD Project by * ThinkSec AS and NAI Labs, the Security Research Division of Network * Associates, Inc. under DARPA/SPAWAR contract N66001-01-C-8035 * ("CBOSS"), as part of the DARPA CHATS research program. * * 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #ifndef lint static const char copyright[] = "@(#) Copyright (c) 1988, 1989, 1992, 1993, 1994\n\ The Regents of the University of California. All rights reserved.\n"; #endif /* not lint */ #ifndef lint #if 0 static const char sccsid[] = "@(#)rshd.c 8.2 (Berkeley) 4/6/94"; #endif #endif /* not lint */ #include __FBSDID("$FreeBSD$"); /* * remote shell server: * [port]\0 * ruser\0 * luser\0 * command\0 * data */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include static struct pam_conv pamc = { openpam_nullconv, NULL }; static pam_handle_t *pamh; static int pam_err; #define PAM_END { \ if ((pam_err = pam_setcred(pamh, PAM_DELETE_CRED)) != PAM_SUCCESS) \ syslog(LOG_ERR|LOG_AUTH, "pam_setcred(): %s", pam_strerror(pamh, pam_err)); \ if ((pam_err = pam_close_session(pamh,0)) != PAM_SUCCESS) \ syslog(LOG_ERR|LOG_AUTH, "pam_close_session(): %s", pam_strerror(pamh, pam_err)); \ if ((pam_err = pam_end(pamh, pam_err)) != PAM_SUCCESS) \ syslog(LOG_ERR|LOG_AUTH, "pam_end(): %s", pam_strerror(pamh, pam_err)); \ } int keepalive = 1; int log_success; /* If TRUE, log all successful accesses */ int sent_null; int no_delay; void doit(struct sockaddr *); static void rshd_errx(int, const char *, ...) __printf0like(2, 3); void getstr(char *, int, const char *); int local_domain(char *); char *topdomain(char *); void usage(void); char slash[] = "/"; char bshell[] = _PATH_BSHELL; #define OPTIONS "aDLln" int main(int argc, char *argv[]) { extern int __check_rhosts_file; struct linger linger; socklen_t fromlen; int ch, on = 1; struct sockaddr_storage from; openlog("rshd", LOG_PID | LOG_ODELAY, LOG_DAEMON); opterr = 0; while ((ch = getopt(argc, argv, OPTIONS)) != -1) switch (ch) { case 'a': /* ignored for compatibility */ break; case 'l': __check_rhosts_file = 0; break; case 'n': keepalive = 0; break; case 'D': no_delay = 1; break; case 'L': log_success = 1; break; case '?': default: usage(); break; } argc -= optind; argv += optind; fromlen = sizeof (from); if (getpeername(0, (struct sockaddr *)&from, &fromlen) < 0) { syslog(LOG_ERR, "getpeername: %m"); exit(1); } if (keepalive && setsockopt(0, SOL_SOCKET, SO_KEEPALIVE, (char *)&on, sizeof(on)) < 0) syslog(LOG_WARNING, "setsockopt (SO_KEEPALIVE): %m"); linger.l_onoff = 1; linger.l_linger = 60; /* XXX */ if (setsockopt(0, SOL_SOCKET, SO_LINGER, (char *)&linger, sizeof (linger)) < 0) syslog(LOG_WARNING, "setsockopt (SO_LINGER): %m"); if (no_delay && setsockopt(0, IPPROTO_TCP, TCP_NODELAY, &on, sizeof(on)) < 0) syslog(LOG_WARNING, "setsockopt (TCP_NODELAY): %m"); doit((struct sockaddr *)&from); /* NOTREACHED */ return(0); } extern char **environ; void doit(struct sockaddr *fromp) { extern char *__rcmd_errstr; /* syslog hook from libc/net/rcmd.c. */ struct passwd *pwd; u_short port; fd_set ready, readfrom; int cc, fd, nfd, pv[2], pid, s; int one = 1; const char *cp, *errorstr; char sig, buf[BUFSIZ]; char *cmdbuf, luser[16], ruser[16]; char rhost[2 * MAXHOSTNAMELEN + 1]; char numericname[INET6_ADDRSTRLEN]; int af, srcport; int maxcmdlen; login_cap_t *lc; maxcmdlen = (int)sysconf(_SC_ARG_MAX); if (maxcmdlen <= 0 || (cmdbuf = malloc(maxcmdlen)) == NULL) exit(1); (void) signal(SIGINT, SIG_DFL); (void) signal(SIGQUIT, SIG_DFL); (void) signal(SIGTERM, SIG_DFL); af = fromp->sa_family; srcport = ntohs(*((in_port_t *)&fromp->sa_data)); if (af == AF_INET) { inet_ntop(af, &((struct sockaddr_in *)fromp)->sin_addr, numericname, sizeof numericname); } else if (af == AF_INET6) { inet_ntop(af, &((struct sockaddr_in6 *)fromp)->sin6_addr, numericname, sizeof numericname); } else { syslog(LOG_ERR, "malformed \"from\" address (af %d)", af); exit(1); } #ifdef IP_OPTIONS if (af == AF_INET) { u_char optbuf[BUFSIZ/3]; socklen_t optsize = sizeof(optbuf), ipproto, i; struct protoent *ip; if ((ip = getprotobyname("ip")) != NULL) ipproto = ip->p_proto; else ipproto = IPPROTO_IP; if (!getsockopt(0, ipproto, IP_OPTIONS, optbuf, &optsize) && optsize != 0) { for (i = 0; i < optsize; ) { u_char c = optbuf[i]; if (c == IPOPT_LSRR || c == IPOPT_SSRR) { syslog(LOG_NOTICE, "connection refused from %s with IP option %s", numericname, c == IPOPT_LSRR ? "LSRR" : "SSRR"); exit(1); } if (c == IPOPT_EOL) break; i += (c == IPOPT_NOP) ? 1 : optbuf[i+1]; } } } #endif if (srcport >= IPPORT_RESERVED || srcport < IPPORT_RESERVED/2) { syslog(LOG_NOTICE|LOG_AUTH, "connection from %s on illegal port %u", numericname, srcport); exit(1); } (void) alarm(60); port = 0; s = 0; /* not set or used if port == 0 */ for (;;) { char c; if ((cc = read(STDIN_FILENO, &c, 1)) != 1) { if (cc < 0) syslog(LOG_NOTICE, "read: %m"); shutdown(0, SHUT_RDWR); exit(1); } if (c == 0) break; port = port * 10 + c - '0'; } (void) alarm(0); if (port != 0) { int lport = IPPORT_RESERVED - 1; s = rresvport_af(&lport, af); if (s < 0) { syslog(LOG_ERR, "can't get stderr port: %m"); exit(1); } if (port >= IPPORT_RESERVED || port < IPPORT_RESERVED/2) { syslog(LOG_NOTICE|LOG_AUTH, "2nd socket from %s on unreserved port %u", numericname, port); exit(1); } *((in_port_t *)&fromp->sa_data) = htons(port); if (connect(s, fromp, fromp->sa_len) < 0) { syslog(LOG_INFO, "connect second port %d: %m", port); exit(1); } } errorstr = NULL; realhostname_sa(rhost, sizeof(rhost) - 1, fromp, fromp->sa_len); rhost[sizeof(rhost) - 1] = '\0'; /* XXX truncation! */ (void) alarm(60); getstr(ruser, sizeof(ruser), "ruser"); getstr(luser, sizeof(luser), "luser"); getstr(cmdbuf, maxcmdlen, "command"); (void) alarm(0); pam_err = pam_start("rsh", luser, &pamc, &pamh); if (pam_err != PAM_SUCCESS) { syslog(LOG_ERR|LOG_AUTH, "pam_start(): %s", pam_strerror(pamh, pam_err)); rshd_errx(1, "Login incorrect."); } if ((pam_err = pam_set_item(pamh, PAM_RUSER, ruser)) != PAM_SUCCESS || (pam_err = pam_set_item(pamh, PAM_RHOST, rhost)) != PAM_SUCCESS) { syslog(LOG_ERR|LOG_AUTH, "pam_set_item(): %s", pam_strerror(pamh, pam_err)); rshd_errx(1, "Login incorrect."); } pam_err = pam_authenticate(pamh, 0); if (pam_err == PAM_SUCCESS) { if ((pam_err = pam_get_user(pamh, &cp, NULL)) == PAM_SUCCESS) { strncpy(luser, cp, sizeof(luser)); luser[sizeof(luser) - 1] = '\0'; /* XXX truncation! */ } pam_err = pam_acct_mgmt(pamh, 0); } if (pam_err != PAM_SUCCESS) { syslog(LOG_INFO|LOG_AUTH, "%s@%s as %s: permission denied (%s). cmd='%.80s'", ruser, rhost, luser, pam_strerror(pamh, pam_err), cmdbuf); rshd_errx(1, "Login incorrect."); } setpwent(); pwd = getpwnam(luser); if (pwd == NULL) { syslog(LOG_INFO|LOG_AUTH, "%s@%s as %s: unknown login. cmd='%.80s'", ruser, rhost, luser, cmdbuf); if (errorstr == NULL) errorstr = "Login incorrect."; rshd_errx(1, errorstr, rhost); } lc = login_getpwclass(pwd); if (pwd->pw_uid) auth_checknologin(lc); if (chdir(pwd->pw_dir) < 0) { if (chdir("/") < 0 || login_getcapbool(lc, "requirehome", !!pwd->pw_uid)) { syslog(LOG_INFO|LOG_AUTH, "%s@%s as %s: no home directory. cmd='%.80s'", ruser, rhost, luser, cmdbuf); rshd_errx(0, "No remote home directory."); } pwd->pw_dir = slash; } if (lc != NULL && fromp->sa_family == AF_INET) { /*XXX*/ char remote_ip[MAXHOSTNAMELEN]; strncpy(remote_ip, numericname, sizeof(remote_ip) - 1); remote_ip[sizeof(remote_ip) - 1] = 0; /* XXX truncation! */ if (!auth_hostok(lc, rhost, remote_ip)) { syslog(LOG_INFO|LOG_AUTH, "%s@%s as %s: permission denied (%s). cmd='%.80s'", ruser, rhost, luser, __rcmd_errstr, cmdbuf); rshd_errx(1, "Login incorrect."); } if (!auth_timeok(lc, time(NULL))) rshd_errx(1, "Logins not available right now"); } /* * PAM modules might add supplementary groups in * pam_setcred(), so initialize them first. * But we need to open the session as root. */ if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETGROUP) != 0) { syslog(LOG_ERR, "setusercontext: %m"); exit(1); } if ((pam_err = pam_open_session(pamh, 0)) != PAM_SUCCESS) { syslog(LOG_ERR, "pam_open_session: %s", pam_strerror(pamh, pam_err)); } else if ((pam_err = pam_setcred(pamh, PAM_ESTABLISH_CRED)) != PAM_SUCCESS) { syslog(LOG_ERR, "pam_setcred: %s", pam_strerror(pamh, pam_err)); } (void) write(STDERR_FILENO, "\0", 1); sent_null = 1; if (port) { if (pipe(pv) < 0) rshd_errx(1, "Can't make pipe."); pid = fork(); if (pid == -1) rshd_errx(1, "Can't fork; try again."); if (pid) { (void) close(0); (void) close(1); (void) close(2); (void) close(pv[1]); FD_ZERO(&readfrom); FD_SET(s, &readfrom); FD_SET(pv[0], &readfrom); if (pv[0] > s) nfd = pv[0]; else nfd = s; ioctl(pv[0], FIONBIO, (char *)&one); /* should set s nbio! */ nfd++; do { ready = readfrom; if (select(nfd, &ready, (fd_set *)0, (fd_set *)0, (struct timeval *)0) < 0) break; if (FD_ISSET(s, &ready)) { int ret; ret = read(s, &sig, 1); if (ret <= 0) FD_CLR(s, &readfrom); else killpg(pid, sig); } if (FD_ISSET(pv[0], &ready)) { errno = 0; cc = read(pv[0], buf, sizeof(buf)); if (cc <= 0) { shutdown(s, SHUT_RDWR); FD_CLR(pv[0], &readfrom); } else { (void)write(s, buf, cc); } } } while (FD_ISSET(s, &readfrom) || FD_ISSET(pv[0], &readfrom)); PAM_END; exit(0); } (void) close(s); (void) close(pv[0]); dup2(pv[1], 2); close(pv[1]); } else { pid = fork(); if (pid == -1) rshd_errx(1, "Can't fork; try again."); if (pid) { /* Parent. */ while (wait(NULL) > 0 || errno == EINTR) /* nothing */ ; PAM_END; exit(0); } } for (fd = getdtablesize(); fd > 2; fd--) (void) close(fd); if (setsid() == -1) syslog(LOG_ERR, "setsid() failed: %m"); if (setlogin(pwd->pw_name) < 0) syslog(LOG_ERR, "setlogin() failed: %m"); if (*pwd->pw_shell == '\0') pwd->pw_shell = bshell; (void) pam_setenv(pamh, "HOME", pwd->pw_dir, 1); (void) pam_setenv(pamh, "SHELL", pwd->pw_shell, 1); (void) pam_setenv(pamh, "USER", pwd->pw_name, 1); (void) pam_setenv(pamh, "PATH", _PATH_DEFPATH, 1); environ = pam_getenvlist(pamh); (void) pam_end(pamh, pam_err); cp = strrchr(pwd->pw_shell, '/'); if (cp) cp++; else cp = pwd->pw_shell; if (setusercontext(lc, pwd, pwd->pw_uid, LOGIN_SETALL & ~LOGIN_SETGROUP) < 0) { syslog(LOG_ERR, "setusercontext(): %m"); exit(1); } login_close(lc); endpwent(); if (log_success || pwd->pw_uid == 0) { syslog(LOG_INFO|LOG_AUTH, "%s@%s as %s: cmd='%.80s'", ruser, rhost, luser, cmdbuf); } execl(pwd->pw_shell, cp, "-c", cmdbuf, (char *)NULL); err(1, "%s", pwd->pw_shell); exit(1); } /* * Report error to client. Note: can't be used until second socket has * connected to client, or older clients will hang waiting for that * connection first. */ static void rshd_errx(int errcode, const char *fmt, ...) { va_list ap; va_start(ap, fmt); if (sent_null == 0) write(STDERR_FILENO, "\1", 1); verrx(errcode, fmt, ap); /* NOTREACHED */ } void getstr(char *buf, int cnt, const char *error) { char c; do { if (read(STDIN_FILENO, &c, 1) != 1) exit(1); *buf++ = c; if (--cnt == 0) rshd_errx(1, "%s too long", error); } while (c != 0); } /* * Check whether host h is in our local domain, * defined as sharing the last two components of the domain part, * or the entire domain part if the local domain has only one component. * If either name is unqualified (contains no '.'), * assume that the host is local, as it will be * interpreted as such. */ int local_domain(char *h) { char localhost[MAXHOSTNAMELEN]; char *p1, *p2; localhost[0] = 0; (void) gethostname(localhost, sizeof(localhost) - 1); localhost[sizeof(localhost) - 1] = '\0'; /* XXX truncation! */ p1 = topdomain(localhost); p2 = topdomain(h); if (p1 == NULL || p2 == NULL || !strcasecmp(p1, p2)) return (1); return (0); } char * topdomain(char *h) { char *p, *maybe = NULL; int dots = 0; for (p = h + strlen(h); p >= h; p--) { if (*p == '.') { if (++dots == 2) return (p); maybe = p; } } return (maybe); } void usage(void) { syslog(LOG_ERR, "usage: rshd [-%s]", OPTIONS); exit(2); } Index: head/libexec/rtld-elf/malloc.c =================================================================== --- head/libexec/rtld-elf/malloc.c (revision 262135) +++ head/libexec/rtld-elf/malloc.c (revision 262136) @@ -1,506 +1,502 @@ /*- * Copyright (c) 1983 Regents of the University of California. * 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #if defined(LIBC_SCCS) && !defined(lint) /*static char *sccsid = "from: @(#)malloc.c 5.11 (Berkeley) 2/23/91";*/ static char *rcsid = "$FreeBSD$"; #endif /* LIBC_SCCS and not lint */ /* * malloc.c (Caltech) 2/21/82 * Chris Kingsley, kingsley@cit-20. * * This is a very fast storage allocator. It allocates blocks of a small * number of different sizes, and keeps free lists of each size. Blocks that * don't exactly fit are passed up to the next larger size. In this * implementation, the available sizes are 2^n-4 (or 2^n-10) bytes long. * This is designed for use in a virtual memory environment. */ #include #include #include #include #include #include #include #include #include #include #include #include "rtld_printf.h" static void morecore(); static int findbucket(); /* * Pre-allocate mmap'ed pages */ #define NPOOLPAGES (32*1024/pagesz) static caddr_t pagepool_start, pagepool_end; static int morepages(); /* * The overhead on a block is at least 4 bytes. When free, this space * contains a pointer to the next free block, and the bottom two bits must * be zero. When in use, the first byte is set to MAGIC, and the second * byte is the size index. The remaining bytes are for alignment. * If range checking is enabled then a second word holds the size of the * requested block, less 1, rounded up to a multiple of sizeof(RMAGIC). * The order of elements is critical: ov_magic must overlay the low order * bits of ov_next, and ov_magic can not be a valid ov_next bit pattern. */ union overhead { union overhead *ov_next; /* when free */ struct { u_char ovu_magic; /* magic number */ u_char ovu_index; /* bucket # */ #ifdef RCHECK u_short ovu_rmagic; /* range magic number */ u_int ovu_size; /* actual block size */ #endif } ovu; #define ov_magic ovu.ovu_magic #define ov_index ovu.ovu_index #define ov_rmagic ovu.ovu_rmagic #define ov_size ovu.ovu_size }; #define MAGIC 0xef /* magic # on accounting info */ #define RMAGIC 0x5555 /* magic # on range info */ #ifdef RCHECK #define RSLOP sizeof (u_short) #else #define RSLOP 0 #endif /* * nextf[i] is the pointer to the next free block of size 2^(i+3). The * smallest allocatable block is 8 bytes. The overhead information * precedes the data area returned to the user. */ #define NBUCKETS 30 static union overhead *nextf[NBUCKETS]; static int pagesz; /* page size */ static int pagebucket; /* page size bucket */ #ifdef MSTATS /* * nmalloc[i] is the difference between the number of mallocs and frees * for a given block size. */ static u_int nmalloc[NBUCKETS]; #include #endif #if defined(MALLOC_DEBUG) || defined(RCHECK) #define ASSERT(p) if (!(p)) botch("p") #include static void botch(s) char *s; { fprintf(stderr, "\r\nassertion botched: %s\r\n", s); (void) fflush(stderr); /* just in case user buffered it */ abort(); } #else #define ASSERT(p) #endif /* Debugging stuff */ #define TRACE() rtld_printf("TRACE %s:%d\n", __FILE__, __LINE__) extern int pagesize; static int rtld_getpagesize(void) { int mib[2]; size_t size; if (pagesize != 0) return (pagesize); mib[0] = CTL_HW; mib[1] = HW_PAGESIZE; size = sizeof(pagesize); if (sysctl(mib, 2, &pagesize, &size, NULL, 0) == -1) return (-1); return (pagesize); } void * malloc(nbytes) size_t nbytes; { register union overhead *op; register int bucket; register long n; register unsigned amt; /* * First time malloc is called, setup page size and * align break pointer so all data will be page aligned. */ if (pagesz == 0) { pagesz = n = rtld_getpagesize(); if (morepages(NPOOLPAGES) == 0) return NULL; op = (union overhead *)(pagepool_start); n = n - sizeof (*op) - ((long)op & (n - 1)); if (n < 0) n += pagesz; if (n) { pagepool_start += n; } bucket = 0; amt = 8; while ((unsigned)pagesz > amt) { amt <<= 1; bucket++; } pagebucket = bucket; } /* * Convert amount of memory requested into closest block size * stored in hash buckets which satisfies request. * Account for space used per block for accounting. */ if (nbytes <= (unsigned long)(n = pagesz - sizeof (*op) - RSLOP)) { #ifndef RCHECK amt = 8; /* size of first bucket */ bucket = 0; #else amt = 16; /* size of first bucket */ bucket = 1; #endif n = -(sizeof (*op) + RSLOP); } else { amt = pagesz; bucket = pagebucket; } while (nbytes > amt + n) { amt <<= 1; if (amt == 0) return (NULL); bucket++; } /* * If nothing in hash bucket right now, * request more memory from the system. */ if ((op = nextf[bucket]) == NULL) { morecore(bucket); if ((op = nextf[bucket]) == NULL) return (NULL); } /* remove from linked list */ nextf[bucket] = op->ov_next; op->ov_magic = MAGIC; op->ov_index = bucket; #ifdef MSTATS nmalloc[bucket]++; #endif #ifdef RCHECK /* * Record allocated size of block and * bound space with magic numbers. */ op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1); op->ov_rmagic = RMAGIC; *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC; #endif return ((char *)(op + 1)); } void * calloc(size_t num, size_t size) { void *ret; if (size != 0 && (num * size) / size != num) { /* size_t overflow. */ return (NULL); } if ((ret = malloc(num * size)) != NULL) memset(ret, 0, num * size); return (ret); } /* * Allocate more memory to the indicated bucket. */ static void morecore(bucket) int bucket; { register union overhead *op; register int sz; /* size of desired block */ int amt; /* amount to allocate */ int nblks; /* how many blocks we get */ /* * sbrk_size <= 0 only for big, FLUFFY, requests (about * 2^30 bytes on a VAX, I think) or for a negative arg. */ sz = 1 << (bucket + 3); #ifdef MALLOC_DEBUG ASSERT(sz > 0); #else if (sz <= 0) return; #endif if (sz < pagesz) { amt = pagesz; nblks = amt / sz; } else { amt = sz + pagesz; nblks = 1; } if (amt > pagepool_end - pagepool_start) if (morepages(amt/pagesz + NPOOLPAGES) == 0) return; op = (union overhead *)pagepool_start; pagepool_start += amt; /* * Add new memory allocated to that on * free list for this hash bucket. */ nextf[bucket] = op; while (--nblks > 0) { op->ov_next = (union overhead *)((caddr_t)op + sz); op = (union overhead *)((caddr_t)op + sz); } } void free(cp) void *cp; { register int size; register union overhead *op; if (cp == NULL) return; op = (union overhead *)((caddr_t)cp - sizeof (union overhead)); #ifdef MALLOC_DEBUG ASSERT(op->ov_magic == MAGIC); /* make sure it was in use */ #else if (op->ov_magic != MAGIC) return; /* sanity */ #endif #ifdef RCHECK ASSERT(op->ov_rmagic == RMAGIC); ASSERT(*(u_short *)((caddr_t)(op + 1) + op->ov_size) == RMAGIC); #endif size = op->ov_index; ASSERT(size < NBUCKETS); op->ov_next = nextf[size]; /* also clobbers ov_magic */ nextf[size] = op; #ifdef MSTATS nmalloc[size]--; #endif } /* * When a program attempts "storage compaction" as mentioned in the * old malloc man page, it realloc's an already freed block. Usually * this is the last block it freed; occasionally it might be farther * back. We have to search all the free lists for the block in order * to determine its bucket: 1st we make one pass thru the lists * checking only the first block in each; if that fails we search * ``realloc_srchlen'' blocks in each list for a match (the variable * is extern so the caller can modify it). If that fails we just copy * however many bytes was given to realloc() and hope it's not huge. */ int realloc_srchlen = 4; /* 4 should be plenty, -1 =>'s whole list */ void * realloc(cp, nbytes) void *cp; size_t nbytes; { register u_int onb; register int i; union overhead *op; char *res; int was_alloced = 0; if (cp == NULL) return (malloc(nbytes)); op = (union overhead *)((caddr_t)cp - sizeof (union overhead)); if (op->ov_magic == MAGIC) { was_alloced++; i = op->ov_index; } else { /* * Already free, doing "compaction". * * Search for the old block of memory on the * free list. First, check the most common * case (last element free'd), then (this failing) * the last ``realloc_srchlen'' items free'd. * If all lookups fail, then assume the size of * the memory block being realloc'd is the * largest possible (so that all "nbytes" of new * memory are copied into). Note that this could cause * a memory fault if the old area was tiny, and the moon * is gibbous. However, that is very unlikely. */ if ((i = findbucket(op, 1)) < 0 && (i = findbucket(op, realloc_srchlen)) < 0) i = NBUCKETS; } onb = 1 << (i + 3); if (onb < (u_int)pagesz) onb -= sizeof (*op) + RSLOP; else onb += pagesz - sizeof (*op) - RSLOP; /* avoid the copy if same size block */ if (was_alloced) { if (i) { i = 1 << (i + 2); if (i < pagesz) i -= sizeof (*op) + RSLOP; else i += pagesz - sizeof (*op) - RSLOP; } if (nbytes <= onb && nbytes > (size_t)i) { #ifdef RCHECK op->ov_size = (nbytes + RSLOP - 1) & ~(RSLOP - 1); *(u_short *)((caddr_t)(op + 1) + op->ov_size) = RMAGIC; #endif return(cp); } else free(cp); } if ((res = malloc(nbytes)) == NULL) return (NULL); if (cp != res) /* common optimization if "compacting" */ bcopy(cp, res, (nbytes < onb) ? nbytes : onb); return (res); } /* * Search ``srchlen'' elements of each free list for a block whose * header starts at ``freep''. If srchlen is -1 search the whole list. * Return bucket number, or -1 if not found. */ static int findbucket(freep, srchlen) union overhead *freep; int srchlen; { register union overhead *p; register int i, j; for (i = 0; i < NBUCKETS; i++) { j = 0; for (p = nextf[i]; p && j != srchlen; p = p->ov_next) { if (p == freep) return (i); j++; } } return (-1); } #ifdef MSTATS /* * mstats - print out statistics about malloc * * Prints two lines of numbers, one showing the length of the free list * for each size category, the second showing the number of mallocs - * frees for each size category. */ mstats(s) char *s; { register int i, j; register union overhead *p; int totfree = 0, totused = 0; fprintf(stderr, "Memory allocation statistics %s\nfree:\t", s); for (i = 0; i < NBUCKETS; i++) { for (j = 0, p = nextf[i]; p; p = p->ov_next, j++) ; fprintf(stderr, " %d", j); totfree += j * (1 << (i + 3)); } fprintf(stderr, "\nused:\t"); for (i = 0; i < NBUCKETS; i++) { fprintf(stderr, " %d", nmalloc[i]); totused += nmalloc[i] * (1 << (i + 3)); } fprintf(stderr, "\n\tTotal in use: %d, total free: %d\n", totused, totfree); } #endif static int morepages(n) int n; { int fd = -1; int offset; if (pagepool_end - pagepool_start > pagesz) { caddr_t addr = (caddr_t) (((long)pagepool_start + pagesz - 1) & ~(pagesz - 1)); if (munmap(addr, pagepool_end - addr) != 0) rtld_fdprintf(STDERR_FILENO, "morepages: munmap %p", addr); } offset = (long)pagepool_start - ((long)pagepool_start & ~(pagesz - 1)); if ((pagepool_start = mmap(0, n * pagesz, PROT_READ|PROT_WRITE, MAP_ANON|MAP_COPY, fd, 0)) == (caddr_t)-1) { rtld_printf("Cannot map anonymous memory\n"); return 0; } pagepool_end = pagepool_start + n * pagesz; pagepool_start += offset; return n; } Index: head/libexec/talkd/announce.c =================================================================== --- head/libexec/talkd/announce.c (revision 262135) +++ head/libexec/talkd/announce.c (revision 262136) @@ -1,169 +1,165 @@ /* * Copyright (c) 1983, 1993 * The Regents of the University of California. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #ifndef lint #if 0 static char sccsid[] = "@(#)announce.c 8.3 (Berkeley) 4/28/95"; #endif static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "ttymsg.h" #include "extern.h" /* * Announce an invitation to talk. */ /* * See if the user is accepting messages. If so, announce that * a talk is requested. */ int announce(CTL_MSG *request, const char *remote_machine) { char full_tty[32]; struct stat stbuf; (void)snprintf(full_tty, sizeof(full_tty), "%s%s", _PATH_DEV, request->r_tty); if (stat(full_tty, &stbuf) < 0 || (stbuf.st_mode&020) == 0) return (PERMISSION_DENIED); return (print_mesg(request->r_tty, request, remote_machine)); } #define max(a,b) ( (a) > (b) ? (a) : (b) ) #define N_LINES 5 #define N_CHARS 256 /* * Build a block of characters containing the message. * It is sent blank filled and in a single block to * try to keep the message in one piece if the recipient * in vi at the time */ int print_mesg(const char *tty, CTL_MSG *request, const char *remote_machine) { struct timeval now; time_t clock_sec; struct tm *localclock; struct iovec iovec; char line_buf[N_LINES][N_CHARS]; int sizes[N_LINES]; char big_buf[N_LINES*N_CHARS]; char *bptr, *lptr, *vis_user; int i, j, max_size; i = 0; max_size = 0; gettimeofday(&now, NULL); clock_sec = now.tv_sec; localclock = localtime(&clock_sec); (void)snprintf(line_buf[i], N_CHARS, " "); sizes[i] = strlen(line_buf[i]); max_size = max(max_size, sizes[i]); i++; (void)snprintf(line_buf[i], N_CHARS, "Message from Talk_Daemon@%s at %d:%02d on %d/%.2d/%.2d ...", hostname, localclock->tm_hour , localclock->tm_min, localclock->tm_year + 1900, localclock->tm_mon + 1, localclock->tm_mday); sizes[i] = strlen(line_buf[i]); max_size = max(max_size, sizes[i]); i++; vis_user = malloc(strlen(request->l_name) * 4 + 1); strvis(vis_user, request->l_name, VIS_CSTYLE); (void)snprintf(line_buf[i], N_CHARS, "talk: connection requested by %s@%s", vis_user, remote_machine); sizes[i] = strlen(line_buf[i]); max_size = max(max_size, sizes[i]); i++; (void)snprintf(line_buf[i], N_CHARS, "talk: respond with: talk %s@%s", vis_user, remote_machine); sizes[i] = strlen(line_buf[i]); max_size = max(max_size, sizes[i]); i++; (void)snprintf(line_buf[i], N_CHARS, " "); sizes[i] = strlen(line_buf[i]); max_size = max(max_size, sizes[i]); i++; bptr = big_buf; *bptr++ = '\007'; /* send something to wake them up */ *bptr++ = '\r'; /* add a \r in case of raw mode */ *bptr++ = '\n'; for (i = 0; i < N_LINES; i++) { /* copy the line into the big buffer */ lptr = line_buf[i]; while (*lptr != '\0') *(bptr++) = *(lptr++); /* pad out the rest of the lines with blanks */ for (j = sizes[i]; j < max_size + 2; j++) *(bptr++) = ' '; *(bptr++) = '\r'; /* add a \r in case of raw mode */ *(bptr++) = '\n'; } *bptr = '\0'; iovec.iov_base = big_buf; iovec.iov_len = bptr - big_buf; /* * we choose a timeout of RING_WAIT-5 seconds so that we don't * stack up processes trying to write messages to a tty * that is permanently blocked. */ if (ttymsg(&iovec, 1, tty, RING_WAIT - 5) != NULL) return (FAILED); return (SUCCESS); } Index: head/libexec/talkd/print.c =================================================================== --- head/libexec/talkd/print.c (revision 262135) +++ head/libexec/talkd/print.c (revision 262136) @@ -1,93 +1,89 @@ /* * Copyright (c) 1983, 1993 * The Regents of the University of California. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #ifndef lint #if 0 static char sccsid[] = "@(#)print.c 8.1 (Berkeley) 6/4/93"; #endif static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ /* debug print routines */ #include #include #include #include #include #include #include "extern.h" static const char *types[] = { "leave_invite", "look_up", "delete", "announce" }; #define NTYPES (sizeof (types) / sizeof (types[0])) static const char *answers[] = { "success", "not_here", "failed", "machine_unknown", "permission_denied", "unknown_request", "badversion", "badaddr", "badctladdr" }; #define NANSWERS (sizeof (answers) / sizeof (answers[0])) void print_request(const char *cp, CTL_MSG *mp) { const char *tp; char tbuf[80]; if (mp->type > NTYPES) { (void)snprintf(tbuf, sizeof(tbuf), "type %d", mp->type); tp = tbuf; } else tp = types[mp->type]; syslog(LOG_DEBUG, "%s: %s: id %lu, l_user %s, r_user %s, r_tty %s", cp, tp, (long)mp->id_num, mp->l_name, mp->r_name, mp->r_tty); } void print_response(const char *cp, CTL_RESPONSE *rp) { const char *tp, *ap; char tbuf[80], abuf[80]; if (rp->type > NTYPES) { (void)snprintf(tbuf, sizeof(tbuf), "type %d", rp->type); tp = tbuf; } else tp = types[rp->type]; if (rp->answer > NANSWERS) { (void)snprintf(abuf, sizeof(abuf), "answer %d", rp->answer); ap = abuf; } else ap = answers[rp->answer]; syslog(LOG_DEBUG, "%s: %s: %s, id %d", cp, tp, ap, ntohl(rp->id_num)); } Index: head/libexec/talkd/process.c =================================================================== --- head/libexec/talkd/process.c (revision 262135) +++ head/libexec/talkd/process.c (revision 262136) @@ -1,225 +1,221 @@ /* * Copyright (c) 1983, 1993 * The Regents of the University of California. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #ifndef lint #if 0 static char sccsid[] = "@(#)process.c 8.2 (Berkeley) 11/16/93"; #endif static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ /* * process.c handles the requests, which can be of three types: * ANNOUNCE - announce to a user that a talk is wanted * LEAVE_INVITE - insert the request into the table * LOOK_UP - look up to see if a request is waiting in * in the table for the local user * DELETE - delete invitation */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include "extern.h" void process_request(CTL_MSG *mp, CTL_RESPONSE *rp) { CTL_MSG *ptr; char *s; rp->vers = TALK_VERSION; rp->type = mp->type; rp->id_num = htonl(0); if (mp->vers != TALK_VERSION) { syslog(LOG_WARNING, "bad protocol version %d", mp->vers); rp->answer = BADVERSION; return; } mp->id_num = ntohl(mp->id_num); mp->addr.sa_family = ntohs(mp->addr.sa_family); if (mp->addr.sa_family != AF_INET) { syslog(LOG_WARNING, "bad address, family %d", mp->addr.sa_family); rp->answer = BADADDR; return; } mp->ctl_addr.sa_family = ntohs(mp->ctl_addr.sa_family); if (mp->ctl_addr.sa_family != AF_INET) { syslog(LOG_WARNING, "bad control address, family %d", mp->ctl_addr.sa_family); rp->answer = BADCTLADDR; return; } for (s = mp->l_name; *s; s++) if (!isprint(*s)) { syslog(LOG_NOTICE, "illegal user name. Aborting"); rp->answer = FAILED; return; } mp->pid = ntohl(mp->pid); if (debug) print_request("process_request", mp); switch (mp->type) { case ANNOUNCE: do_announce(mp, rp); break; case LEAVE_INVITE: ptr = find_request(mp); if (ptr != (CTL_MSG *)0) { rp->id_num = htonl(ptr->id_num); rp->answer = SUCCESS; } else insert_table(mp, rp); break; case LOOK_UP: ptr = find_match(mp); if (ptr != (CTL_MSG *)0) { rp->id_num = htonl(ptr->id_num); rp->addr = ptr->addr; rp->addr.sa_family = htons(ptr->addr.sa_family); rp->answer = SUCCESS; } else rp->answer = NOT_HERE; break; case DELETE: rp->answer = delete_invite(mp->id_num); break; default: rp->answer = UNKNOWN_REQUEST; break; } if (debug) print_response("process_request", rp); } void do_announce(CTL_MSG *mp, CTL_RESPONSE *rp) { struct hostent *hp; CTL_MSG *ptr; int result; /* see if the user is logged */ result = find_user(mp->r_name, mp->r_tty); if (result != SUCCESS) { rp->answer = result; return; } #define satosin(sa) ((struct sockaddr_in *)(void *)(sa)) hp = gethostbyaddr(&satosin(&mp->ctl_addr)->sin_addr, sizeof (struct in_addr), AF_INET); if (hp == (struct hostent *)0) { rp->answer = MACHINE_UNKNOWN; return; } ptr = find_request(mp); if (ptr == (CTL_MSG *) 0) { insert_table(mp, rp); rp->answer = announce(mp, hp->h_name); return; } if (mp->id_num > ptr->id_num) { /* * This is an explicit re-announce, so update the id_num * field to avoid duplicates and re-announce the talk. */ ptr->id_num = new_id(); rp->id_num = htonl(ptr->id_num); rp->answer = announce(mp, hp->h_name); } else { /* a duplicated request, so ignore it */ rp->id_num = htonl(ptr->id_num); rp->answer = SUCCESS; } } /* * Search utmp for the local user */ int find_user(const char *name, char *tty) { struct utmpx *ut; int status; struct stat statb; time_t best = 0; char ftty[sizeof(_PATH_DEV) - 1 + sizeof(ut->ut_line)]; setutxent(); status = NOT_HERE; (void) strcpy(ftty, _PATH_DEV); while ((ut = getutxent()) != NULL) if (ut->ut_type == USER_PROCESS && strcmp(ut->ut_user, name) == 0) { if (*tty == '\0' || best != 0) { if (best == 0) status = PERMISSION_DENIED; /* no particular tty was requested */ (void) strcpy(ftty + sizeof(_PATH_DEV) - 1, ut->ut_line); if (stat(ftty, &statb) == 0) { if (!(statb.st_mode & 020)) continue; if (statb.st_atime > best) { best = statb.st_atime; (void) strcpy(tty, ut->ut_line); status = SUCCESS; continue; } } } if (strcmp(ut->ut_line, tty) == 0) { status = SUCCESS; break; } } endutxent(); return (status); } Index: head/libexec/talkd/table.c =================================================================== --- head/libexec/talkd/table.c (revision 262135) +++ head/libexec/talkd/table.c (revision 262136) @@ -1,236 +1,232 @@ /* * Copyright (c) 1983, 1993 * The Regents of the University of California. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #ifndef lint #if 0 static char sccsid[] = "@(#)table.c 8.1 (Berkeley) 6/4/93"; #endif static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ /* * Routines to handle insertion, deletion, etc on the table * of requests kept by the daemon. Nothing fancy here, linear * search on a double-linked list. A time is kept with each * entry so that overly old invitations can be eliminated. * * Consider this a mis-guided attempt at modularity */ #include #include #include #include #include #include #include #include #include #include #include "extern.h" #define MAX_ID 16000 /* << 2^15 so I don't have sign troubles */ #define NIL ((TABLE_ENTRY *)0) static struct timeval tp; typedef struct table_entry TABLE_ENTRY; struct table_entry { CTL_MSG request; long time; TABLE_ENTRY *next; TABLE_ENTRY *last; }; static void delete(TABLE_ENTRY *); static TABLE_ENTRY *table = NIL; /* * Look in the table for an invitation that matches the current * request looking for an invitation */ CTL_MSG * find_match(CTL_MSG *request) { TABLE_ENTRY *ptr; time_t current_time; gettimeofday(&tp, NULL); current_time = tp.tv_sec; if (debug) print_request("find_match", request); for (ptr = table; ptr != NIL; ptr = ptr->next) { if ((ptr->time - current_time) > MAX_LIFE) { /* the entry is too old */ if (debug) print_request("deleting expired entry", &ptr->request); delete(ptr); continue; } if (debug) print_request("", &ptr->request); if (strcmp(request->l_name, ptr->request.r_name) == 0 && strcmp(request->r_name, ptr->request.l_name) == 0 && ptr->request.type == LEAVE_INVITE) return (&ptr->request); } return ((CTL_MSG *)0); } /* * Look for an identical request, as opposed to a complimentary * one as find_match does */ CTL_MSG * find_request(CTL_MSG *request) { TABLE_ENTRY *ptr; time_t current_time; gettimeofday(&tp, NULL); current_time = tp.tv_sec; /* * See if this is a repeated message, and check for * out of date entries in the table while we are it. */ if (debug) print_request("find_request", request); for (ptr = table; ptr != NIL; ptr = ptr->next) { if ((ptr->time - current_time) > MAX_LIFE) { /* the entry is too old */ if (debug) print_request("deleting expired entry", &ptr->request); delete(ptr); continue; } if (debug) print_request("", &ptr->request); if (strcmp(request->r_name, ptr->request.r_name) == 0 && strcmp(request->l_name, ptr->request.l_name) == 0 && request->type == ptr->request.type && request->pid == ptr->request.pid) { /* update the time if we 'touch' it */ ptr->time = current_time; return (&ptr->request); } } return ((CTL_MSG *)0); } void insert_table(CTL_MSG *request, CTL_RESPONSE *response) { TABLE_ENTRY *ptr; time_t current_time; gettimeofday(&tp, NULL); current_time = tp.tv_sec; request->id_num = new_id(); response->id_num = htonl(request->id_num); /* insert a new entry into the top of the list */ ptr = (TABLE_ENTRY *)malloc(sizeof(TABLE_ENTRY)); if (ptr == NIL) { syslog(LOG_ERR, "insert_table: Out of memory"); _exit(1); } ptr->time = current_time; ptr->request = *request; ptr->next = table; if (ptr->next != NIL) ptr->next->last = ptr; ptr->last = NIL; table = ptr; } /* * Generate a unique non-zero sequence number */ int new_id(void) { static int current_id = 0; current_id = (current_id + 1) % MAX_ID; /* 0 is reserved, helps to pick up bugs */ if (current_id == 0) current_id = 1; return (current_id); } /* * Delete the invitation with id 'id_num' */ int delete_invite(u_int32_t id_num) { TABLE_ENTRY *ptr; ptr = table; if (debug) syslog(LOG_DEBUG, "delete_invite(%d)", id_num); for (ptr = table; ptr != NIL; ptr = ptr->next) { if (ptr->request.id_num == id_num) break; if (debug) print_request("", &ptr->request); } if (ptr != NIL) { delete(ptr); return (SUCCESS); } return (NOT_HERE); } /* * Classic delete from a double-linked list */ static void delete(TABLE_ENTRY *ptr) { if (debug) print_request("delete", &ptr->request); if (table == ptr) table = ptr->next; else if (ptr->last != NIL) ptr->last->next = ptr->next; if (ptr->next != NIL) ptr->next->last = ptr->last; free((char *)ptr); } Index: head/libexec/talkd/talkd.8 =================================================================== --- head/libexec/talkd/talkd.8 (revision 262135) +++ head/libexec/talkd/talkd.8 (revision 262136) @@ -1,80 +1,76 @@ .\" Copyright (c) 1983, 1991, 1993 .\" The Regents of the University of California. 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. -.\" 3. All advertising materials mentioning features or use of this software -.\" must display the following acknowledgement: -.\" This product includes software developed by the University of -.\" California, Berkeley and its contributors. -.\" 4. Neither the name of the University nor the names of its contributors +.\" 3. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. .\" .\" @(#)talkd.8 8.2 (Berkeley) 12/11/93 .\" $FreeBSD$ .\" .Dd December 11, 1993 .Dt TALKD 8 .Os .Sh NAME .Nm talkd .Nd remote user communication server .Sh SYNOPSIS .Nm .Sh DESCRIPTION The .Nm utility is the server that notifies a user that someone else wants to initiate a conversation. It acts as a repository of invitations, responding to requests by clients wishing to rendezvous to hold a conversation. In normal operation, a client, the caller, initiates a rendezvous by sending a .Tn CTL_MSG to the server of type .Tn LOOK_UP (see .In protocols/talkd.h ) . This causes the server to search its invitation tables to check if an invitation currently exists for the caller (to speak to the callee specified in the message). .Pp If the lookup fails, the caller then sends an .Tn ANNOUNCE message causing the server to broadcast an announcement on the callee's login ports requesting contact. .Pp When the callee responds, the local server uses the recorded invitation to respond with the appropriate rendezvous address and the caller and callee client programs establish a stream connection through which the conversation takes place. .Sh SEE ALSO .Xr talk 1 , .Xr write 1 .Sh HISTORY The .Nm utility appeared in .Bx 4.3 . Index: head/libexec/talkd/talkd.c =================================================================== --- head/libexec/talkd/talkd.c (revision 262135) +++ head/libexec/talkd/talkd.c (revision 262136) @@ -1,140 +1,136 @@ /* * Copyright (c) 1983, 1993 * The Regents of the University of California. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #ifndef lint static const char copyright[] = "@(#) Copyright (c) 1983, 1993\n\ The Regents of the University of California. All rights reserved.\n"; #endif /* not lint */ #ifndef lint #if 0 static char sccsid[] = "@(#)talkd.c 8.1 (Berkeley) 6/4/93"; #endif static const char rcsid[] = "$FreeBSD$"; #endif /* not lint */ /* * The top level of the daemon, the format is heavily borrowed * from rwhod.c. Basically: find out who and where you are; * disconnect all descriptors and ttys, and then endless * loop on waiting for and processing requests */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "extern.h" static CTL_MSG request; static CTL_RESPONSE response; int debug = 0; static long lastmsgtime; char hostname[MAXHOSTNAMELEN]; #define TIMEOUT 30 #define MAXIDLE 120 int main(int argc, char *argv[]) { register CTL_MSG *mp = &request; int cc; struct sockaddr ctl_addr; #ifdef NOTDEF /* * removed so ntalkd can run in tty sandbox */ if (getuid()) errx(1, "getuid: not super-user"); #endif openlog("talkd", LOG_PID, LOG_DAEMON); if (gethostname(hostname, sizeof(hostname) - 1) < 0) { syslog(LOG_ERR, "gethostname: %m"); _exit(1); } hostname[sizeof(hostname) - 1] = '\0'; if (chdir(_PATH_DEV) < 0) { syslog(LOG_ERR, "chdir: %s: %m", _PATH_DEV); _exit(1); } if (argc > 1 && strcmp(argv[1], "-d") == 0) debug = 1; signal(SIGALRM, timeout); alarm(TIMEOUT); for (;;) { cc = recv(0, (char *)mp, sizeof(*mp), 0); if (cc != sizeof (*mp)) { if (cc < 0 && errno != EINTR) syslog(LOG_WARNING, "recv: %m"); continue; } lastmsgtime = time(0); (void)memcpy(&ctl_addr, &mp->ctl_addr, sizeof(ctl_addr)); ctl_addr.sa_family = ntohs(mp->ctl_addr.sa_family); ctl_addr.sa_len = sizeof(ctl_addr); process_request(mp, &response); /* can block here, is this what I want? */ cc = sendto(STDIN_FILENO, (char *)&response, sizeof(response), 0, &ctl_addr, sizeof(ctl_addr)); if (cc != sizeof (response)) syslog(LOG_WARNING, "sendto: %m"); } } void timeout(int sig __unused) { int save_errno = errno; if (time(0) - lastmsgtime >= MAXIDLE) _exit(0); alarm(TIMEOUT); errno = save_errno; } Index: head/libexec/tftpd/tftpd.8 =================================================================== --- head/libexec/tftpd/tftpd.8 (revision 262135) +++ head/libexec/tftpd/tftpd.8 (revision 262136) @@ -1,310 +1,306 @@ .\" Copyright (c) 1983, 1991, 1993 .\" The Regents of the University of California. 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. -.\" 3. All advertising materials mentioning features or use of this software -.\" must display the following acknowledgement: -.\" This product includes software developed by the University of -.\" California, Berkeley and its contributors. -.\" 4. Neither the name of the University nor the names of its contributors +.\" 3. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. .\" .\" @(#)tftpd.8 8.1 (Berkeley) 6/4/93 .\" $FreeBSD$ .\" .Dd June 22, 2011 .Dt TFTPD 8 .Os .Sh NAME .Nm tftpd .Nd Internet Trivial File Transfer Protocol server .Sh SYNOPSIS .Nm tftpd .Op Fl cdClnow .Op Fl F Ar strftime-format .Op Fl s Ar directory .Op Fl u Ar user .Op Fl U Ar umask .Op Ar directory ... .Sh DESCRIPTION The .Nm utility is a server which supports the Internet Trivial File Transfer Protocol .Pq Tn RFC 1350 . The .Tn TFTP server operates at the port indicated in the .Ql tftp service description; see .Xr services 5 . The server is normally started by .Xr inetd 8 . .Pp The use of .Xr tftp 1 does not require an account or password on the remote system. Due to the lack of authentication information, .Nm will allow only publicly readable files to be accessed. Files containing the string .Dq Li "/../" or starting with .Dq Li "../" are not allowed. Files may be written only if they already exist and are publicly writable. Note that this extends the concept of .Dq public to include all users on all hosts that can be reached through the network; this may not be appropriate on all systems, and its implications should be considered before enabling tftp service. The server should have the user ID with the lowest possible privilege. .Pp Access to files may be restricted by invoking .Nm with a list of directories by including up to 20 pathnames as server program arguments in .Xr inetd.conf 5 . In this case access is restricted to files whose names are prefixed by the one of the given directories. The given directories are also treated as a search path for relative filename requests. .Pp The .Fl s option provides additional security by changing the root directory of .Nm , thereby prohibiting accesses to outside of the specified .Ar directory . Because .Xr chroot 2 requires super-user privileges, .Nm must be run as .Li root . However, after performing the .Xr chroot 2 call, .Nm will set its user ID to that of the specified .Ar user , or .Dq Li nobody if no .Fl u option is specified. .Pp The options are: .Bl -tag -width Ds .It Fl c Changes the default root directory of a connecting host via .Xr chroot 2 based on the connecting IP address. This prevents multiple clients from writing to the same file at the same time. If the directory does not exist, the client connection is refused. The .Fl s option is required for .Fl c and the specified .Ar directory is used as a base. .It Fl C Operates the same as .Fl c except it falls back to .Ar directory specified via .Fl s if a directory does not exist for the client's IP. .It Fl F Use this .Xr strftime 3 compatible format string for the creation of the suffix if .Fl W is specified. By default the string "%Y%m%d" is used. .It Fl d, d Ar [value] Enables debug output. If .Ar value is not specified, then the debug level is increased by one for each instance of .Fl d which is specified. .Pp If .Ar value is specified, then the debug level is set to .Ar value . The debug level is a bitmask implemented in .Pa src/libexec/tftpd/tftp-utils.h . Valid values are 0 (DEBUG_NONE), 1 (DEBUG_PACKETS), 2, (DEBUG_SIMPLE), 4 (DEBUG_OPTIONS), and 8 (DEBUG_ACCESS). Multiple debug values can be combined in the bitmask by logically OR'ing the values. For example, specifying .Fl d .Ar 15 will enable all the debug values. .It Fl l Log all requests using .Xr syslog 3 with the facility of .Dv LOG_FTP . .Sy Note : Logging of .Dv LOG_FTP messages must also be enabled in the syslog configuration file, .Xr syslog.conf 5 . .It Fl n Suppress negative acknowledgement of requests for nonexistent relative filenames. .It Fl o Disable support for RFC2347 style TFTP Options. .It Fl s Ar directory Cause .Nm to change its root directory to .Ar directory . After doing that but before accepting commands, .Nm will switch credentials to an unprivileged user. .It Fl u Ar user Switch credentials to .Ar user (default .Dq Li nobody ) when the .Fl s option is used. The user must be specified by name, not a numeric UID. .It Fl U Ar umask Set the .Ar umask for newly created files. The default is 022 .Pq Dv S_IWGRP | S_IWOTH . .It Fl w Allow write requests to create new files. By default .Nm requires that the file specified in a write request exist. Note that this only works in directories writable by the user specified with .Fl u option .It Fl W As .Fl w but append a YYYYMMDD.nn sequence number to the end of the filename. Note that the string YYYYMMDD can be changed with the .Fl F option. .El .Sh SEE ALSO .Xr tftp 1 , .Xr chroot 2 , .Xr syslog 3 , .Xr inetd.conf 5 , .Xr services 5 , .Xr syslog.conf 5 , .Xr inetd 8 .Pp The following RFC's are supported: .Rs .%T RFC 1350: The TFTP Protocol (Revision 2) .Re .Rs .%T RFC 2347: TFTP Option Extension .Re .Rs .%T RFC 2348: TFTP Blocksize Option .Re .Rs .%T RFC 2349: TFTP Timeout Interval and Transfer Size Options .Re .Pp The non-standard .Cm rollover and .Cm blksize2 TFTP options are mentioned here: .Rs .%T Extending TFTP .%U http://www.compuphase.com/tftp.htm .Re .Sh HISTORY The .Nm utility appeared in .Bx 4.2 ; the .Fl s option was introduced in .Fx 2.2 , the .Fl u option was introduced in .Fx 4.2 , the .Fl c option was introduced in .Fx 4.3 , and the .Fl F and .Fl W options were introduced in .Fx 7.4 . .Pp Support for Timeout Interval and Transfer Size Options (RFC2349) was introduced in .Fx 5.0 , support for the TFTP Blocksize Option (RFC2348) and the blksize2 option was introduced in .Fx 7.4 . .Pp Edwin Groothuis performed a major rewrite of the .Nm and .Xr tftp 1 code to support RFC2348. .Sh NOTES Files larger than 33,553,919 octets (65535 blocks, last one <512 octets) cannot be correctly transferred without client and server supporting blocksize negotiation (RFCs 2347 and 2348), or the non-standard TFTP rollover option. As a kludge, .Nm accepts a sequence of block number which wrap to zero after 65535, even if the rollover option is not specified. .Pp Many tftp clients will not transfer files over 16,776,703 octets (32767 blocks), as they incorrectly count the block number using a signed rather than unsigned 16-bit integer. Index: head/libexec/tftpd/tftpd.c =================================================================== --- head/libexec/tftpd/tftpd.c (revision 262135) +++ head/libexec/tftpd/tftpd.c (revision 262136) @@ -1,841 +1,837 @@ /* * Copyright (c) 1983, 1993 * The Regents of the University of California. 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. - * 3. All advertising materials mentioning features or use of this software - * must display the following acknowledgement: - * This product includes software developed by the University of - * California, Berkeley and its contributors. - * 4. Neither the name of the University nor the names of its contributors + * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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. */ #ifndef lint static const char copyright[] = "@(#) Copyright (c) 1983, 1993\n\ The Regents of the University of California. All rights reserved.\n"; #endif /* not lint */ #ifndef lint #if 0 static char sccsid[] = "@(#)tftpd.c 8.1 (Berkeley) 6/4/93"; #endif #endif /* not lint */ #include __FBSDID("$FreeBSD$"); /* * Trivial file transfer protocol server. * * This version includes many modifications by Jim Guyton * . */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "tftp-file.h" #include "tftp-io.h" #include "tftp-utils.h" #include "tftp-transfer.h" #include "tftp-options.h" static void tftp_wrq(int peer, char *, ssize_t); static void tftp_rrq(int peer, char *, ssize_t); /* * Null-terminated directory prefix list for absolute pathname requests and * search list for relative pathname requests. * * MAXDIRS should be at least as large as the number of arguments that * inetd allows (currently 20). */ #define MAXDIRS 20 static struct dirlist { const char *name; int len; } dirs[MAXDIRS+1]; static int suppress_naks; static int logging; static int ipchroot; static int create_new = 0; static const char *newfile_format = "%Y%m%d"; static int increase_name = 0; static mode_t mask = S_IWGRP | S_IWOTH; struct formats; static void tftp_recvfile(int peer, const char *mode); static void tftp_xmitfile(int peer, const char *mode); static int validate_access(int peer, char **, int); static char peername[NI_MAXHOST]; static FILE *file; static struct formats { const char *f_mode; int f_convert; } formats[] = { { "netascii", 1 }, { "octet", 0 }, { NULL, 0 } }; int main(int argc, char *argv[]) { struct tftphdr *tp; int peer; socklen_t peerlen, len; ssize_t n; int ch; char *chroot_dir = NULL; struct passwd *nobody; const char *chuser = "nobody"; char recvbuffer[MAXPKTSIZE]; int allow_ro = 1, allow_wo = 1; tzset(); /* syslog in localtime */ acting_as_client = 0; tftp_openlog("tftpd", LOG_PID | LOG_NDELAY, LOG_FTP); while ((ch = getopt(argc, argv, "cCd:F:lnoOp:s:u:U:wW")) != -1) { switch (ch) { case 'c': ipchroot = 1; break; case 'C': ipchroot = 2; break; case 'd': if (atoi(optarg) != 0) debug += atoi(optarg); else debug |= debug_finds(optarg); break; case 'F': newfile_format = optarg; break; case 'l': logging = 1; break; case 'n': suppress_naks = 1; break; case 'o': options_rfc_enabled = 0; break; case 'O': options_extra_enabled = 0; break; case 'p': packetdroppercentage = atoi(optarg); tftp_log(LOG_INFO, "Randomly dropping %d out of 100 packets", packetdroppercentage); break; case 's': chroot_dir = optarg; break; case 'u': chuser = optarg; break; case 'U': mask = strtol(optarg, NULL, 0); break; case 'w': create_new = 1; break; case 'W': create_new = 1; increase_name = 1; break; default: tftp_log(LOG_WARNING, "ignoring unknown option -%c", ch); } } if (optind < argc) { struct dirlist *dirp; /* Get list of directory prefixes. Skip relative pathnames. */ for (dirp = dirs; optind < argc && dirp < &dirs[MAXDIRS]; optind++) { if (argv[optind][0] == '/') { dirp->name = argv[optind]; dirp->len = strlen(dirp->name); dirp++; } } } else if (chroot_dir) { dirs->name = "/"; dirs->len = 1; } if (ipchroot > 0 && chroot_dir == NULL) { tftp_log(LOG_ERR, "-c requires -s"); exit(1); } umask(mask); { int on = 1; if (ioctl(0, FIONBIO, &on) < 0) { tftp_log(LOG_ERR, "ioctl(FIONBIO): %s", strerror(errno)); exit(1); } } /* Find out who we are talking to and what we are going to do */ peerlen = sizeof(peer_sock); n = recvfrom(0, recvbuffer, MAXPKTSIZE, 0, (struct sockaddr *)&peer_sock, &peerlen); if (n < 0) { tftp_log(LOG_ERR, "recvfrom: %s", strerror(errno)); exit(1); } getnameinfo((struct sockaddr *)&peer_sock, peer_sock.ss_len, peername, sizeof(peername), NULL, 0, NI_NUMERICHOST); /* * Now that we have read the message out of the UDP * socket, we fork and exit. Thus, inetd will go back * to listening to the tftp port, and the next request * to come in will start up a new instance of tftpd. * * We do this so that inetd can run tftpd in "wait" mode. * The problem with tftpd running in "nowait" mode is that * inetd may get one or more successful "selects" on the * tftp port before we do our receive, so more than one * instance of tftpd may be started up. Worse, if tftpd * break before doing the above "recvfrom", inetd would * spawn endless instances, clogging the system. */ { int i, pid; for (i = 1; i < 20; i++) { pid = fork(); if (pid < 0) { sleep(i); /* * flush out to most recently sent request. * * This may drop some request, but those * will be resent by the clients when * they timeout. The positive effect of * this flush is to (try to) prevent more * than one tftpd being started up to service * a single request from a single client. */ peerlen = sizeof peer_sock; i = recvfrom(0, recvbuffer, MAXPKTSIZE, 0, (struct sockaddr *)&peer_sock, &peerlen); if (i > 0) { n = i; } } else { break; } } if (pid < 0) { tftp_log(LOG_ERR, "fork: %s", strerror(errno)); exit(1); } else if (pid != 0) { exit(0); } } /* * See if the client is allowed to talk to me. * (This needs to be done before the chroot()) */ { struct request_info req; request_init(&req, RQ_CLIENT_ADDR, peername, 0); request_set(&req, RQ_DAEMON, "tftpd", 0); if (hosts_access(&req) == 0) { if (debug&DEBUG_ACCESS) tftp_log(LOG_WARNING, "Access denied by 'tftpd' entry " "in /etc/hosts.allow"); /* * Full access might be disabled, but maybe the * client is allowed to do read-only access. */ request_set(&req, RQ_DAEMON, "tftpd-ro", 0); allow_ro = hosts_access(&req); request_set(&req, RQ_DAEMON, "tftpd-wo", 0); allow_wo = hosts_access(&req); if (allow_ro == 0 && allow_wo == 0) { tftp_log(LOG_WARNING, "Unauthorized access from %s", peername); exit(1); } if (debug&DEBUG_ACCESS) { if (allow_ro) tftp_log(LOG_WARNING, "But allowed readonly access " "via 'tftpd-ro' entry"); if (allow_wo) tftp_log(LOG_WARNING, "But allowed writeonly access " "via 'tftpd-wo' entry"); } } else if (debug&DEBUG_ACCESS) tftp_log(LOG_WARNING, "Full access allowed" "in /etc/hosts.allow"); } /* * Since we exit here, we should do that only after the above * recvfrom to keep inetd from constantly forking should there * be a problem. See the above comment about system clogging. */ if (chroot_dir) { if (ipchroot > 0) { char *tempchroot; struct stat sb; int statret; struct sockaddr_storage ss; char hbuf[NI_MAXHOST]; statret = -1; memcpy(&ss, &peer_sock, peer_sock.ss_len); unmappedaddr((struct sockaddr_in6 *)&ss); getnameinfo((struct sockaddr *)&ss, ss.ss_len, hbuf, sizeof(hbuf), NULL, 0, NI_NUMERICHOST); asprintf(&tempchroot, "%s/%s", chroot_dir, hbuf); if (ipchroot == 2) statret = stat(tempchroot, &sb); if (ipchroot == 1 || (statret == 0 && (sb.st_mode & S_IFDIR))) chroot_dir = tempchroot; } /* Must get this before chroot because /etc might go away */ if ((nobody = getpwnam(chuser)) == NULL) { tftp_log(LOG_ERR, "%s: no such user", chuser); exit(1); } if (chroot(chroot_dir)) { tftp_log(LOG_ERR, "chroot: %s: %s", chroot_dir, strerror(errno)); exit(1); } chdir("/"); setgroups(1, &nobody->pw_gid); if (setuid(nobody->pw_uid) != 0) { tftp_log(LOG_ERR, "setuid failed"); exit(1); } } len = sizeof(me_sock); if (getsockname(0, (struct sockaddr *)&me_sock, &len) == 0) { switch (me_sock.ss_family) { case AF_INET: ((struct sockaddr_in *)&me_sock)->sin_port = 0; break; case AF_INET6: ((struct sockaddr_in6 *)&me_sock)->sin6_port = 0; break; default: /* unsupported */ break; } } else { memset(&me_sock, 0, sizeof(me_sock)); me_sock.ss_family = peer_sock.ss_family; me_sock.ss_len = peer_sock.ss_len; } close(0); close(1); peer = socket(peer_sock.ss_family, SOCK_DGRAM, 0); if (peer < 0) { tftp_log(LOG_ERR, "socket: %s", strerror(errno)); exit(1); } if (bind(peer, (struct sockaddr *)&me_sock, me_sock.ss_len) < 0) { tftp_log(LOG_ERR, "bind: %s", strerror(errno)); exit(1); } tp = (struct tftphdr *)recvbuffer; tp->th_opcode = ntohs(tp->th_opcode); if (tp->th_opcode == RRQ) { if (allow_ro) tftp_rrq(peer, tp->th_stuff, n - 1); else { tftp_log(LOG_WARNING, "%s read access denied", peername); exit(1); } } if (tp->th_opcode == WRQ) { if (allow_wo) tftp_wrq(peer, tp->th_stuff, n - 1); else { tftp_log(LOG_WARNING, "%s write access denied", peername); exit(1); } } exit(1); } static void reduce_path(char *fn) { char *slash, *ptr; /* Reduce all "/+./" to "/" (just in case we've got "/./../" later */ while ((slash = strstr(fn, "/./")) != NULL) { for (ptr = slash; ptr > fn && ptr[-1] == '/'; ptr--) ; slash += 2; while (*slash) *++ptr = *++slash; } /* Now reduce all "/something/+../" to "/" */ while ((slash = strstr(fn, "/../")) != NULL) { if (slash == fn) break; for (ptr = slash; ptr > fn && ptr[-1] == '/'; ptr--) ; for (ptr--; ptr >= fn; ptr--) if (*ptr == '/') break; if (ptr < fn) break; slash += 3; while (*slash) *++ptr = *++slash; } } static char * parse_header(int peer, char *recvbuffer, ssize_t size, char **filename, char **mode) { char *cp; int i; struct formats *pf; *mode = NULL; cp = recvbuffer; i = get_field(peer, recvbuffer, size); if (i >= PATH_MAX) { tftp_log(LOG_ERR, "Bad option - filename too long"); send_error(peer, EBADOP); exit(1); } *filename = recvbuffer; tftp_log(LOG_INFO, "Filename: '%s'", *filename); cp += i; i = get_field(peer, cp, size); *mode = cp; cp += i; /* Find the file transfer mode */ for (cp = *mode; *cp; cp++) if (isupper(*cp)) *cp = tolower(*cp); for (pf = formats; pf->f_mode; pf++) if (strcmp(pf->f_mode, *mode) == 0) break; if (pf->f_mode == NULL) { tftp_log(LOG_ERR, "Bad option - Unknown transfer mode (%s)", *mode); send_error(peer, EBADOP); exit(1); } tftp_log(LOG_INFO, "Mode: '%s'", *mode); return (cp + 1); } /* * WRQ - receive a file from the client */ void tftp_wrq(int peer, char *recvbuffer, ssize_t size) { char *cp; int has_options = 0, ecode; char *filename, *mode; char fnbuf[PATH_MAX]; cp = parse_header(peer, recvbuffer, size, &filename, &mode); size -= (cp - recvbuffer) + 1; strcpy(fnbuf, filename); reduce_path(fnbuf); filename = fnbuf; if (size > 0) { if (options_rfc_enabled) has_options = !parse_options(peer, cp, size); else tftp_log(LOG_INFO, "Options found but not enabled"); } ecode = validate_access(peer, &filename, WRQ); if (ecode == 0) { if (has_options) send_oack(peer); else send_ack(peer, 0); } if (logging) { tftp_log(LOG_INFO, "%s: write request for %s: %s", peername, filename, errtomsg(ecode)); } tftp_recvfile(peer, mode); exit(0); } /* * RRQ - send a file to the client */ void tftp_rrq(int peer, char *recvbuffer, ssize_t size) { char *cp; int has_options = 0, ecode; char *filename, *mode; char fnbuf[PATH_MAX]; cp = parse_header(peer, recvbuffer, size, &filename, &mode); size -= (cp - recvbuffer) + 1; strcpy(fnbuf, filename); reduce_path(fnbuf); filename = fnbuf; if (size > 0) { if (options_rfc_enabled) has_options = !parse_options(peer, cp, size); else tftp_log(LOG_INFO, "Options found but not enabled"); } ecode = validate_access(peer, &filename, RRQ); if (ecode == 0) { if (has_options) { int n; char lrecvbuffer[MAXPKTSIZE]; struct tftphdr *rp = (struct tftphdr *)lrecvbuffer; send_oack(peer); n = receive_packet(peer, lrecvbuffer, MAXPKTSIZE, NULL, timeoutpacket); if (n < 0) { if (debug&DEBUG_SIMPLE) tftp_log(LOG_DEBUG, "Aborting: %s", rp_strerror(n)); return; } if (rp->th_opcode != ACK) { if (debug&DEBUG_SIMPLE) tftp_log(LOG_DEBUG, "Expected ACK, got %s on OACK", packettype(rp->th_opcode)); return; } } } if (logging) tftp_log(LOG_INFO, "%s: read request for %s: %s", peername, filename, errtomsg(ecode)); if (ecode) { /* * Avoid storms of naks to a RRQ broadcast for a relative * bootfile pathname from a diskless Sun. */ if (suppress_naks && *filename != '/' && ecode == ENOTFOUND) exit(0); send_error(peer, ecode); exit(1); } tftp_xmitfile(peer, mode); } /* * Find the next value for YYYYMMDD.nn when the file to be written should * be unique. Due to the limitations of nn, we will fail if nn reaches 100. * Besides, that is four updates per hour on a file, which is kind of * execessive anyway. */ static int find_next_name(char *filename, int *fd) { int i; time_t tval; size_t len; struct tm lt; char yyyymmdd[MAXPATHLEN]; char newname[MAXPATHLEN]; /* Create the YYYYMMDD part of the filename */ time(&tval); lt = *localtime(&tval); len = strftime(yyyymmdd, sizeof(yyyymmdd), newfile_format, <); if (len == 0) { syslog(LOG_WARNING, "Filename suffix too long (%d characters maximum)", MAXPATHLEN); return (EACCESS); } /* Make sure the new filename is not too long */ if (strlen(filename) > MAXPATHLEN - len - 5) { syslog(LOG_WARNING, "Filename too long (%zd characters, %zd maximum)", strlen(filename), MAXPATHLEN - len - 5); return (EACCESS); } /* Find the first file which doesn't exist */ for (i = 0; i < 100; i++) { sprintf(newname, "%s.%s.%02d", filename, yyyymmdd, i); *fd = open(newname, O_WRONLY | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH); if (*fd > 0) return 0; } return (EEXIST); } /* * Validate file access. Since we * have no uid or gid, for now require * file to exist and be publicly * readable/writable. * If we were invoked with arguments * from inetd then the file must also be * in one of the given directory prefixes. * Note also, full path name must be * given as we have no login directory. */ int validate_access(int peer, char **filep, int mode) { struct stat stbuf; int fd; int error; struct dirlist *dirp; static char pathname[MAXPATHLEN]; char *filename = *filep; /* * Prevent tricksters from getting around the directory restrictions */ if (strstr(filename, "/../")) return (EACCESS); if (*filename == '/') { /* * Allow the request if it's in one of the approved locations. * Special case: check the null prefix ("/") by looking * for length = 1 and relying on the arg. processing that * it's a /. */ for (dirp = dirs; dirp->name != NULL; dirp++) { if (dirp->len == 1 || (!strncmp(filename, dirp->name, dirp->len) && filename[dirp->len] == '/')) break; } /* If directory list is empty, allow access to any file */ if (dirp->name == NULL && dirp != dirs) return (EACCESS); if (stat(filename, &stbuf) < 0) return (errno == ENOENT ? ENOTFOUND : EACCESS); if ((stbuf.st_mode & S_IFMT) != S_IFREG) return (ENOTFOUND); if (mode == RRQ) { if ((stbuf.st_mode & S_IROTH) == 0) return (EACCESS); } else { if ((stbuf.st_mode & S_IWOTH) == 0) return (EACCESS); } } else { int err; /* * Relative file name: search the approved locations for it. * Don't allow write requests that avoid directory * restrictions. */ if (!strncmp(filename, "../", 3)) return (EACCESS); /* * If the file exists in one of the directories and isn't * readable, continue looking. However, change the error code * to give an indication that the file exists. */ err = ENOTFOUND; for (dirp = dirs; dirp->name != NULL; dirp++) { snprintf(pathname, sizeof(pathname), "%s/%s", dirp->name, filename); if (stat(pathname, &stbuf) == 0 && (stbuf.st_mode & S_IFMT) == S_IFREG) { if ((stbuf.st_mode & S_IROTH) != 0) { break; } err = EACCESS; } } if (dirp->name != NULL) *filep = filename = pathname; else if (mode == RRQ) return (err); } /* * This option is handled here because it (might) require(s) the * size of the file. */ option_tsize(peer, NULL, mode, &stbuf); if (mode == RRQ) fd = open(filename, O_RDONLY); else { if (create_new) { if (increase_name) { error = find_next_name(filename, &fd); if (error > 0) return (error + 100); } else fd = open(filename, O_WRONLY | O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH ); } else fd = open(filename, O_WRONLY | O_TRUNC); } if (fd < 0) return (errno + 100); file = fdopen(fd, (mode == RRQ)? "r":"w"); if (file == NULL) { close(fd); return (errno + 100); } return (0); } static void tftp_xmitfile(int peer, const char *mode) { uint16_t block; time_t now; struct tftp_stats ts; now = time(NULL); if (debug&DEBUG_SIMPLE) tftp_log(LOG_DEBUG, "Transmitting file"); read_init(0, file, mode); block = 1; tftp_send(peer, &block, &ts); read_close(); if (debug&DEBUG_SIMPLE) tftp_log(LOG_INFO, "Sent %jd bytes in %jd seconds", (intmax_t)ts.amount, (intmax_t)time(NULL) - now); } static void tftp_recvfile(int peer, const char *mode) { uint16_t block; struct timeval now1, now2; struct tftp_stats ts; gettimeofday(&now1, NULL); if (debug&DEBUG_SIMPLE) tftp_log(LOG_DEBUG, "Receiving file"); write_init(0, file, mode); block = 0; tftp_receive(peer, &block, &ts, NULL, 0); write_close(); gettimeofday(&now2, NULL); if (debug&DEBUG_SIMPLE) { double f; if (now1.tv_usec > now2.tv_usec) { now2.tv_usec += 1000000; now2.tv_sec--; } f = now2.tv_sec - now1.tv_sec + (now2.tv_usec - now1.tv_usec) / 100000.0; tftp_log(LOG_INFO, "Download of %jd bytes in %d blocks completed after %0.1f seconds\n", (intmax_t)ts.amount, block, f); } return; }