1 /* $NetBSD: util.c,v 1.21 2009/11/15 10:12:37 lukem Exp $ */
2 /* from NetBSD: util.c,v 1.152 2009/07/13 19:05:41 roy Exp */
5 * Copyright (c) 1997-2009 The NetBSD Foundation, Inc.
8 * This code is derived from software contributed to The NetBSD Foundation
11 * This code is derived from software contributed to The NetBSD Foundation
12 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
13 * NASA Ames Research Center.
15 * Redistribution and use in source and binary forms, with or without
16 * modification, are permitted provided that the following conditions
18 * 1. Redistributions of source code must retain the above copyright
19 * notice, this list of conditions and the following disclaimer.
20 * 2. Redistributions in binary form must reproduce the above copyright
21 * notice, this list of conditions and the following disclaimer in the
22 * documentation and/or other materials provided with the distribution.
24 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
25 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
26 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
27 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
28 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34 * POSSIBILITY OF SUCH DAMAGE.
38 * Copyright (c) 1985, 1989, 1993, 1994
39 * The Regents of the University of California. All rights reserved.
41 * Redistribution and use in source and binary forms, with or without
42 * modification, are permitted provided that the following conditions
44 * 1. Redistributions of source code must retain the above copyright
45 * notice, this list of conditions and the following disclaimer.
46 * 2. Redistributions in binary form must reproduce the above copyright
47 * notice, this list of conditions and the following disclaimer in the
48 * documentation and/or other materials provided with the distribution.
49 * 3. Neither the name of the University nor the names of its contributors
50 * may be used to endorse or promote products derived from this software
51 * without specific prior written permission.
53 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
54 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
55 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
56 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
57 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
58 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
59 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
60 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
61 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
62 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
70 #include <sys/cdefs.h>
72 __RCSID(" NetBSD: util.c,v 1.152 2009/07/13 19:05:41 roy Exp ");
76 * FTP User Program -- Misc support routines
78 #include <sys/param.h>
79 #include <sys/socket.h>
80 #include <sys/ioctl.h>
82 #include <netinet/in.h>
107 * Connect to peer server and auto-login, if possible.
110 setpeer(int argc, char *argv[])
118 fprintf(ttyout, "Already connected to %s, use close first.\n",
124 (void)another(&argc, &argv, "to");
125 if (argc < 2 || argc > 3) {
127 UPRINTF("usage: %s host-name [port]\n", argv[0]);
139 if (gateserver == NULL || *gateserver == '\0')
140 errx(1, "main: gateserver not defined");
141 host = hookup(gateserver, port);
143 host = hookup(argv[1], port);
146 if (gatemode && verbose) {
148 "Connecting via pass-through server %s\n",
154 * Set up defaults for FTP.
156 (void)strlcpy(typename, "ascii", sizeof(typename));
159 (void)strlcpy(formname, "non-print", sizeof(formname));
161 (void)strlcpy(modename, "stream", sizeof(modename));
163 (void)strlcpy(structname, "file", sizeof(structname));
165 (void)strlcpy(bytename, "8", sizeof(bytename));
168 (void)ftp_login(argv[1], NULL, NULL);
173 parse_feat(const char *fline)
177 * work-around broken ProFTPd servers that can't
180 while (*fline && isspace((int)*fline))
183 if (strcasecmp(fline, "MDTM") == 0)
184 features[FEAT_MDTM] = 1;
185 else if (strncasecmp(fline, "MLST", sizeof("MLST") - 1) == 0) {
186 features[FEAT_MLST] = 1;
187 } else if (strcasecmp(fline, "REST STREAM") == 0)
188 features[FEAT_REST_STREAM] = 1;
189 else if (strcasecmp(fline, "SIZE") == 0)
190 features[FEAT_SIZE] = 1;
191 else if (strcasecmp(fline, "TVFS") == 0)
192 features[FEAT_TVFS] = 1;
196 * Determine the remote system type (SYST) and features (FEAT).
197 * Call after a successful login (i.e, connected = -1)
208 /* determine remote system type */
209 if (command("SYST") == COMPLETE) {
214 cp = strchr(reply_string + 4, ' ');
216 cp = strchr(reply_string + 4, '\r');
224 fprintf(ttyout, "Remote system type is %s.\n",
229 if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
235 * Set type to 0 (not specified by user),
236 * meaning binary by default, but don't bother
237 * telling server. We can use binary
238 * for text files unless changed by the user.
241 (void)strlcpy(typename, "binary", sizeof(typename));
244 "Using %s mode to transfer files.\n",
252 !strncmp(reply_string, "215 TOPS20", 10))
254 "Remember to set tenex mode when transferring binary files from this machine.\n",
259 /* determine features (if any) */
260 for (i = 0; i < FEAT_max; i++)
262 reply_callback = parse_feat;
263 if (command("FEAT") == COMPLETE) {
264 for (i = 0; i < FEAT_max; i++) {
265 if (features[i] == -1)
268 features[FEAT_FEAT] = 1;
270 features[FEAT_FEAT] = 0;
273 #define DEBUG_FEAT(x) fprintf(ttyout, "features[" #x "] = %d\n", features[(x)])
274 DEBUG_FEAT(FEAT_FEAT);
275 DEBUG_FEAT(FEAT_MDTM);
276 DEBUG_FEAT(FEAT_MLST);
277 DEBUG_FEAT(FEAT_REST_STREAM);
278 DEBUG_FEAT(FEAT_SIZE);
279 DEBUG_FEAT(FEAT_TVFS);
283 reply_callback = NULL;
289 * Reset the various variables that indicate connection state back to
290 * disconnected settings.
291 * The caller is responsible for issuing any commands to the remote server
292 * to perform a clean shutdown before this is invoked.
305 * determine if anonftp was specifically set with -a
306 * (1), or implicitly set by auto_fetch() (2). in the
307 * latter case, disable after the current xfer
322 * Top-level signal handler for interrupted commands.
331 write(fileno(ttyout), "\n", 1);
332 siglongjmp(toplevel, 1);
336 * Signal handler for lost connections; cleanup various elements of
337 * the connection state, and call cleanuppeer() to finish it off.
347 (void)shutdown(fileno(cout), 1+1);
352 (void)shutdown(data, 1+1);
361 (void)shutdown(fileno(cout), 1+1);
375 * Login to remote host, using given username & password if supplied.
376 * Return non-zero if successful.
379 ftp_login(const char *host, const char *luser, const char *lpass)
382 char *fuser, *pass, *facct, *p;
383 char emptypass[] = "";
384 const char *errormsg;
385 int n, aflag, rval, nlen;
388 fuser = pass = facct = NULL;
390 fuser = ftp_strdup(luser);
392 pass = ftp_strdup(lpass);
394 DPRINTF("ftp_login: user `%s' pass `%s' host `%s'\n",
395 STRorNULL(fuser), STRorNULL(pass), STRorNULL(host));
398 * Set up arguments for an anonymous FTP session, if necessary.
402 fuser = ftp_strdup("anonymous"); /* as per RFC1635 */
404 pass = ftp_strdup(getoptionvalue("anonpass"));
407 if (ruserpass(host, &fuser, &pass, &facct) < 0) {
409 goto cleanup_ftp_login;
412 while (fuser == NULL) {
414 fprintf(ttyout, "Name (%s:%s): ", host, localname);
416 fprintf(ttyout, "Name (%s): ", host);
418 nlen = get_line(stdin, tmp, sizeof(tmp), &errormsg);
420 fprintf(ttyout, "%s; %s aborted.\n", errormsg, "login");
422 goto cleanup_ftp_login;
423 } else if (nlen == 0) {
424 fuser = ftp_strdup(localname);
426 fuser = ftp_strdup(tmp);
434 len = strlen(fuser) + 1 + strlen(host) + 1;
435 nuser = ftp_malloc(len);
436 (void)strlcpy(nuser, fuser, len);
437 (void)strlcat(nuser, "@", len);
438 (void)strlcat(nuser, host, len);
443 n = command("USER %s", fuser);
446 p = getpass("Password: ");
449 pass = ftp_strdup(p);
450 memset(p, 0, strlen(p));
452 n = command("PASS %s", pass);
453 memset(pass, 0, strlen(pass));
458 p = getpass("Account: ");
461 facct = ftp_strdup(p);
462 memset(p, 0, strlen(p));
464 if (facct[0] == '\0') {
465 warnx("Login failed");
466 goto cleanup_ftp_login;
468 n = command("ACCT %s", facct);
469 memset(facct, 0, strlen(facct));
471 if ((n != COMPLETE) ||
472 (!aflag && facct != NULL && command("ACCT %s", facct) != COMPLETE)) {
473 warnx("Login failed");
474 goto cleanup_ftp_login;
477 username = ftp_strdup(fuser);
479 goto cleanup_ftp_login;
483 for (n = 0; n < macnum; ++n) {
484 if (!strcmp("init", macros[n].mac_name)) {
485 (void)strlcpy(line, "$init", sizeof(line));
487 domacro(margc, margv);
497 memset(pass, 0, strlen(pass));
500 memset(facct, 0, strlen(facct));
506 * `another' gets another argument, and stores the new argc and argv.
507 * It reverts to the top level (via intr()) on EOF/error.
509 * Returns false if no new arguments have been added.
512 another(int *pargc, char ***pargv, const char *aprompt)
514 const char *errormsg;
519 if (len >= sizeof(line) - 3) {
520 fputs("Sorry, arguments too long.\n", ttyout);
523 fprintf(ttyout, "(%s) ", aprompt);
526 nlen = get_line(stdin, line + len, sizeof(line)-len, &errormsg);
528 fprintf(ttyout, "%s; %s aborted.\n", errormsg, "operation");
533 ret = margc > *pargc;
540 * glob files given in argv[] from the remote server.
541 * if errbuf isn't NULL, store error messages there instead
542 * of writing to the screen.
545 remglob(char *argv[], int doswitch, const char **errbuf)
547 static char buf[MAXPATHLEN];
548 static FILE *ftemp = NULL;
550 char temp[MAXPATHLEN];
551 int oldverbose, oldhash, oldprogress, fd;
556 if (!mflag || !connected) {
570 if ((cp = *++args) == NULL)
575 len = strlcpy(temp, tmpdir, sizeof(temp));
576 if (temp[len - 1] != '/')
577 (void)strlcat(temp, "/", sizeof(temp));
578 (void)strlcat(temp, TMPFILE, sizeof(temp));
579 if ((fd = mkstemp(temp)) < 0) {
580 warn("Unable to create temporary file `%s'", temp);
584 oldverbose = verbose;
585 verbose = (errbuf != NULL) ? -1 : 0;
587 oldprogress = progress;
592 for (rmode = "w"; *++argv != NULL; rmode = "a")
593 recvrequest("NLST", temp, *argv, rmode, 0, 0);
594 if ((code / 100) != COMPLETE) {
596 *errbuf = reply_string;
600 verbose = oldverbose;
602 progress = oldprogress;
603 ftemp = fopen(temp, "r");
607 warnx("Can't find list of remote files");
610 "Can't find list of remote files";
614 if (fgets(buf, sizeof(buf), ftemp) == NULL) {
619 if ((cp = strchr(buf, '\n')) != NULL)
625 * Glob a local file name specification with the expectation of a single
626 * return value. Can't control multiple values being expanded from the
627 * expression, we return only the first.
628 * Returns NULL on error, or a pointer to a buffer containing the filename
629 * that's the caller's responsiblity to free(3) when finished with.
632 globulize(const char *pattern)
639 return (ftp_strdup(pattern));
641 flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
642 memset(&gl, 0, sizeof(gl));
643 if (glob(pattern, flags, NULL, &gl) || gl.gl_pathc == 0) {
644 warnx("Glob pattern `%s' not found", pattern);
648 p = ftp_strdup(gl.gl_pathv[0]);
654 * determine size of remote file
657 remotesize(const char *file, int noisy)
666 if (! features[FEAT_SIZE]) {
669 "SIZE is not supported by remote server.\n");
670 goto cleanup_remotesize;
672 r = command("SIZE %s", file);
676 cp = strchr(reply_string, ' ');
679 size = STRTOLL(cp, &ep, 10);
680 if (*ep != '\0' && !isspace((unsigned char)*ep))
684 if (r == ERROR && code == 500 && features[FEAT_SIZE] == -1)
685 features[FEAT_SIZE] = 0;
686 if (noisy && ftp_debug == 0) {
687 fputs(reply_string, ttyout);
697 * determine last modification time (in GMT) of remote file
700 remotemodtime(const char *file, int noisy)
702 int overbose, ocode, r;
710 if (! features[FEAT_MDTM]) {
713 "MDTM is not supported by remote server.\n");
714 goto cleanup_parse_time;
716 r = command("MDTM %s", file);
719 char *timestr, *frac;
722 * time-val = 14DIGIT [ "." 1*DIGIT ]
723 * YYYYMMDDHHMMSS[.sss]
724 * mdtm-response = "213" SP time-val CRLF / error-response
726 timestr = reply_string + 4;
730 * XXX: ignored for now
732 frac = strchr(timestr, '\r');
735 frac = strchr(timestr, '.');
738 if (strlen(timestr) == 15 && strncmp(timestr, "191", 3) == 0) {
740 * XXX: Workaround for lame ftpd's that return
741 * `19100' instead of `2000'
744 "Y2K warning! Incorrect time-val `%s' received from server.\n",
749 fprintf(ttyout, "Converted to `%s'\n", timestr);
751 memset(&timebuf, 0, sizeof(timebuf));
752 if (strlen(timestr) != 14 ||
753 (strptime(timestr, "%Y%m%d%H%M%S", &timebuf) == NULL)) {
755 fprintf(ttyout, "Can't parse time `%s'.\n", timestr);
756 goto cleanup_parse_time;
758 timebuf.tm_isdst = -1;
759 rtime = timegm(&timebuf);
761 if (noisy || ftp_debug != 0)
764 goto cleanup_parse_time;
766 DPRINTF("remotemodtime: parsed date `%s' as " LLF
769 rfc2822time(localtime(&rtime)));
772 if (r == ERROR && code == 500 && features[FEAT_MDTM] == -1)
773 features[FEAT_MDTM] = 0;
774 if (noisy && ftp_debug == 0) {
775 fputs(reply_string, ttyout);
787 * Format tm in an RFC2822 compatible manner, with a trailing \n.
788 * Returns a pointer to a static string containing the result.
791 rfc2822time(const struct tm *tm)
793 static char result[50];
795 if (strftime(result, sizeof(result),
796 "%a, %d %b %Y %H:%M:%S %z\n", tm) == 0)
797 errx(1, "Can't convert RFC2822 time: buffer too small");
802 * Update global `localcwd', which contains the state of the local cwd
808 if (getcwd(localcwd, sizeof(localcwd)) == NULL)
810 DPRINTF("updatelocalcwd: got `%s'\n", localcwd);
814 * Update global `remotecwd', which contains the state of the remote cwd
817 updateremotecwd(void)
827 if (command("PWD") != COMPLETE)
829 cp = strchr(reply_string, ' ');
830 if (cp == NULL || cp[0] == '\0' || cp[1] != '"')
833 for (i = 0; *cp && i < sizeof(remotecwd) - 1; i++, cp++) {
843 DPRINTF("updateremotecwd: got `%s'\n", remotecwd);
844 goto cleanupremotecwd;
853 * Ensure file is in or under dir.
854 * Returns 1 if so, 0 if not (or an error occurred).
857 fileindir(const char *file, const char *dir)
859 char parentdirbuf[PATH_MAX+1], *parentdir;
860 char realdir[PATH_MAX+1];
863 /* determine parent directory of file */
864 (void)strlcpy(parentdirbuf, file, sizeof(parentdirbuf));
865 parentdir = dirname(parentdirbuf);
866 if (strcmp(parentdir, ".") == 0)
867 return 1; /* current directory is ok */
869 /* find the directory */
870 if (realpath(parentdir, realdir) == NULL) {
871 warn("Unable to determine real path of `%s'", parentdir);
874 if (realdir[0] != '/') /* relative result is ok */
876 dirlen = strlen(dir);
877 if (strncmp(realdir, dir, dirlen) == 0 &&
878 (realdir[dirlen] == '/' || realdir[dirlen] == '\0'))
884 * List words in stringlist, vertically arranged
887 list_vertical(StringList *sl)
890 size_t columns, lines;
896 for (i = 0 ; i < sl->sl_cur ; i++) {
897 w = strlen(sl->sl_str[i]);
901 width = (width + 8) &~ 7;
903 columns = ttywidth / width;
906 lines = (sl->sl_cur + columns - 1) / columns;
907 for (i = 0; i < lines; i++) {
908 for (j = 0; j < columns; j++) {
909 p = sl->sl_str[j * lines + i];
912 if (j * lines + i + lines >= sl->sl_cur) {
920 (void)putc('\t', ttyout);
928 * Update the global ttywidth value, using TIOCGWINSZ.
933 struct winsize winsize;
936 if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
938 ttywidth = winsize.ws_col;
945 * Change the rate limit up (SIGUSR1) or down (SIGUSR2)
954 rate_get += rate_get_incr;
956 rate_put += rate_put_incr;
959 if (rate_get && rate_get > rate_get_incr)
960 rate_get -= rate_get_incr;
961 if (rate_put && rate_put > rate_put_incr)
962 rate_put -= rate_put_incr;
965 err(1, "crankrate invoked with unknown signal: %d", sig);
971 * Setup or cleanup EditLine structures
973 #ifndef NO_EDITCOMPLETE
977 if (editing && el == NULL && hist == NULL) {
981 el = el_init(getprogname(), stdin, ttyout, stderr);
983 hist = history_init(); /* init the builtin history */
984 history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
985 el_set(el, EL_HIST, history, hist); /* use history */
987 el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
988 el_set(el, EL_PROMPT, prompt); /* set the prompt functions */
989 el_set(el, EL_RPROMPT, rprompt);
991 /* add local file completion, bind to TAB */
992 el_set(el, EL_ADDFN, "ftp-complete",
993 "Context sensitive argument completion",
995 el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
996 el_source(el, NULL); /* read ~/.editrc */
997 if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
998 editing = 0; /* the user doesn't want editing,
999 * so disable, and let statement
1002 el_set(el, EL_SIGNAL, 1);
1015 #endif /* !NO_EDITCOMPLETE */
1018 * Convert the string `arg' to an int, which may have an optional SI suffix
1019 * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
1022 strsuftoi(const char *arg)
1027 if (!isdigit((unsigned char)arg[0]))
1030 val = strtol(arg, &cp, 10);
1032 if (cp[0] != '\0' && cp[1] != '\0')
1034 switch (tolower((unsigned char)cp[0])) {
1051 if (val < 0 || val > INT_MAX)
1058 * Set up socket buffer sizes before a connection is made.
1061 setupsockbufsize(int sock)
1064 if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
1065 (void *)&sndbuf_size, sizeof(sndbuf_size)) == -1)
1066 warn("Unable to set sndbuf size %d", sndbuf_size);
1068 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1069 (void *)&rcvbuf_size, sizeof(rcvbuf_size)) == -1)
1070 warn("Unable to set rcvbuf size %d", rcvbuf_size);
1074 * Copy characters from src into dst, \ quoting characters that require it
1077 ftpvis(char *dst, size_t dstlen, const char *src, size_t srclen)
1082 src[si] != '\0' && di < dstlen && si < srclen;
1103 * Copy src into buf (which is len bytes long), expanding % sequences.
1106 formatbuf(char *buf, size_t len, const char *src)
1108 const char *p, *p2, *q;
1110 int op, updirs, pdirs;
1112 #define ADDBUF(x) do { \
1119 for (i = 0; *p; p++) {
1131 p2 = connected ? remotecwd : "";
1134 /* option to determine fixed # of dirs from path */
1135 if (op == '.' || op == 'c') {
1139 while (*p2) /* calc # of /'s */
1142 if (p[1] == '0') { /* print <x> or ... */
1146 if (p[1] >= '1' && p[1] <= '9') {
1147 /* calc # to skip */
1154 while (skip-- > 0) {
1155 while ((p2 > q) && (*p2 != '/'))
1160 if (*p2 == '/' && p2 != q)
1164 if (updirs > 0 && pdirs) {
1178 ADDBUF('0' + updirs);
1188 for (p2 = connected && hostname ? hostname : "-";
1190 if (op == 'm' && *p2 == '.')
1197 for (p2 = connected ? username : "-"; *p2 ; p2++)
1205 default: /* display unknown codes literally */
1217 * Determine if given string is an IPv6 address or not.
1218 * Return 1 for yes, 0 for no
1221 isipv6addr(const char *addr)
1225 struct addrinfo hints, *res;
1227 memset(&hints, 0, sizeof(hints));
1228 hints.ai_family = AF_INET6;
1229 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
1230 hints.ai_flags = AI_NUMERICHOST;
1231 if (getaddrinfo(addr, "0", &hints, &res) != 0)
1237 DPRINTF("isipv6addr: got %d for %s\n", rv, addr);
1239 return (rv == 1) ? 1 : 0;
1243 * Read a line from the FILE stream into buf/buflen using fgets(), so up
1244 * to buflen-1 chars will be read and the result will be NUL terminated.
1245 * If the line has a trailing newline it will be removed.
1246 * If the line is too long, excess characters will be read until
1247 * newline/EOF/error.
1248 * If EOF/error occurs or a too-long line is encountered and errormsg
1249 * isn't NULL, it will be changed to a description of the problem.
1250 * (The EOF message has a leading \n for cosmetic purposes).
1252 * >=0 length of line (excluding trailing newline) if all ok
1254 * -2 EOF encountered
1255 * -3 line was too long
1258 get_line(FILE *stream, char *buf, size_t buflen, const char **errormsg)
1263 if (fgets(buf, buflen, stream) == NULL) {
1264 if (feof(stream)) { /* EOF */
1267 *errormsg = "\nEOF received";
1268 } else { /* error */
1271 *errormsg = "Error encountered";
1277 if (buf[len-1] == '\n') { /* clear any trailing newline */
1279 } else if (len == buflen-1) { /* line too long */
1280 while ((ch = getchar()) != '\n' && ch != EOF)
1283 *errormsg = "Input line is too long";
1293 * Internal version of connect(2); sets socket buffer sizes,
1294 * binds to a specific local address (if set), and
1295 * supports a connection timeout using a non-blocking connect(2) with
1297 * Socket fcntl flags are temporarily updated to include O_NONBLOCK;
1298 * these will not be reverted on connection failure.
1299 * Returns 0 on success, or -1 upon failure (with an appropriate
1300 * error message displayed.)
1303 ftp_connect(int sock, const struct sockaddr *name, socklen_t namelen)
1305 int flags, rv, timeout, error;
1307 struct timeval endtime, now, td;
1308 struct pollfd pfd[1];
1309 char hname[NI_MAXHOST];
1310 char sname[NI_MAXSERV];
1312 setupsockbufsize(sock);
1313 if (getnameinfo(name, namelen,
1314 hname, sizeof(hname), sname, sizeof(sname),
1315 NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
1316 strlcpy(hname, "?", sizeof(hname));
1317 strlcpy(sname, "?", sizeof(sname));
1320 if (bindai != NULL) { /* bind to specific addr */
1321 struct addrinfo *ai;
1323 for (ai = bindai; ai != NULL; ai = ai->ai_next) {
1324 if (ai->ai_family == name->sa_family)
1329 if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
1330 char bname[NI_MAXHOST];
1334 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
1335 bname, sizeof(bname), NULL, 0, NI_NUMERICHOST) != 0)
1336 strlcpy(bname, "?", sizeof(bname));
1338 warn("Can't bind to `%s'", bname);
1343 /* save current socket flags */
1344 if ((flags = fcntl(sock, F_GETFL, 0)) == -1) {
1345 warn("Can't %s socket flags for connect to `%s:%s'",
1346 "save", hname, sname);
1349 /* set non-blocking connect */
1350 if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) == -1) {
1351 warn("Can't set socket non-blocking for connect to `%s:%s'",
1356 /* NOTE: we now must restore socket flags on successful exit */
1359 pfd[0].events = POLLIN|POLLOUT;
1361 if (quit_time > 0) { /* want a non default timeout */
1362 (void)gettimeofday(&endtime, NULL);
1363 endtime.tv_sec += quit_time; /* determine end time */
1366 rv = connect(sock, name, namelen); /* inititate the connection */
1367 if (rv == -1) { /* connection error */
1368 if (errno != EINPROGRESS) { /* error isn't "please wait" */
1370 warn("Can't connect to `%s:%s'", hname, sname);
1374 /* connect EINPROGRESS; wait */
1376 if (quit_time > 0) { /* determine timeout */
1377 (void)gettimeofday(&now, NULL);
1378 timersub(&endtime, &now, &td);
1379 timeout = td.tv_sec * 1000 + td.tv_usec/1000;
1386 rv = ftp_poll(pfd, 1, timeout);
1387 /* loop until poll ! EINTR */
1388 } while (rv == -1 && errno == EINTR);
1390 if (rv == 0) { /* poll (connect) timed out */
1395 if (rv == -1) { /* poll error */
1397 } else if (pfd[0].revents & (POLLIN|POLLOUT)) {
1398 slen = sizeof(error); /* OK, or pending error */
1399 if (getsockopt(sock, SOL_SOCKET, SO_ERROR,
1400 &error, &slen) == -1) {
1401 /* Solaris pending error */
1403 } else if (error != 0) {
1404 errno = error; /* BSD pending error */
1408 errno = EBADF; /* this shouldn't happen ... */
1413 if (fcntl(sock, F_SETFL, flags) == -1) {
1414 /* restore socket flags */
1415 warn("Can't %s socket flags for connect to `%s:%s'",
1416 "restore", hname, sname);
1423 * Internal version of listen(2); sets socket buffer sizes first.
1426 ftp_listen(int sock, int backlog)
1429 setupsockbufsize(sock);
1430 return (listen(sock, backlog));
1434 * Internal version of poll(2), to allow reimplementation by select(2)
1435 * on platforms without the former.
1438 ftp_poll(struct pollfd *fds, int nfds, int timeout)
1440 #if defined(HAVE_POLL)
1441 return poll(fds, nfds, timeout);
1443 #elif defined(HAVE_SELECT)
1444 /* implement poll(2) using select(2) */
1445 fd_set rset, wset, xset;
1446 const int rsetflags = POLLIN | POLLRDNORM;
1447 const int wsetflags = POLLOUT | POLLWRNORM;
1448 const int xsetflags = POLLRDBAND;
1449 struct timeval tv, *ptv;
1452 FD_ZERO(&rset); /* build list of read & write events */
1456 for (i = 0; i < nfds; i++) {
1457 if (fds[i].fd > FD_SETSIZE) {
1458 warnx("can't select fd %d", fds[i].fd);
1461 } else if (fds[i].fd > max)
1463 if (fds[i].events & rsetflags)
1464 FD_SET(fds[i].fd, &rset);
1465 if (fds[i].events & wsetflags)
1466 FD_SET(fds[i].fd, &wset);
1467 if (fds[i].events & xsetflags)
1468 FD_SET(fds[i].fd, &xset);
1471 ptv = &tv; /* determine timeout */
1472 if (timeout == -1) { /* wait forever */
1474 } else if (timeout == 0) { /* poll once */
1478 else if (timeout != 0) { /* wait timeout milliseconds */
1479 ptv->tv_sec = timeout / 1000;
1480 ptv->tv_usec = (timeout % 1000) * 1000;
1482 rv = select(max + 1, &rset, &wset, &xset, ptv);
1483 if (rv <= 0) /* -1 == error, 0 == timeout */
1486 for (i = 0; i < nfds; i++) { /* determine results */
1487 if (FD_ISSET(fds[i].fd, &rset))
1488 fds[i].revents |= (fds[i].events & rsetflags);
1489 if (FD_ISSET(fds[i].fd, &wset))
1490 fds[i].revents |= (fds[i].events & wsetflags);
1491 if (FD_ISSET(fds[i].fd, &xset))
1492 fds[i].revents |= (fds[i].events & xsetflags);
1497 # error no way to implement xpoll
1502 * malloc() with inbuilt error checking
1505 ftp_malloc(size_t size)
1511 err(1, "Unable to allocate %ld bytes of memory", (long)size);
1516 * sl_init() with inbuilt error checking
1525 err(1, "Unable to allocate memory for stringlist");
1530 * sl_add() with inbuilt error checking
1533 ftp_sl_add(StringList *sl, char *i)
1536 if (sl_add(sl, i) == -1)
1537 err(1, "Unable to add `%s' to stringlist", i);
1541 * strdup() with inbuilt error checking
1544 ftp_strdup(const char *str)
1549 errx(1, "ftp_strdup: called with NULL argument");
1552 err(1, "Unable to allocate memory for string copy");