1 /* $NetBSD: util.c,v 1.158 2013/02/19 23:29:15 dsl Exp $ */
4 * Copyright (c) 1997-2009 The NetBSD Foundation, Inc.
7 * This code is derived from software contributed to The NetBSD Foundation
10 * This code is derived from software contributed to The NetBSD Foundation
11 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
12 * NASA Ames Research Center.
14 * Redistribution and use in source and binary forms, with or without
15 * modification, are permitted provided that the following conditions
17 * 1. Redistributions of source code must retain the above copyright
18 * notice, this list of conditions and the following disclaimer.
19 * 2. Redistributions in binary form must reproduce the above copyright
20 * notice, this list of conditions and the following disclaimer in the
21 * documentation and/or other materials provided with the distribution.
23 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
24 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
25 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
26 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
27 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
28 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
29 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
30 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
31 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
32 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
33 * POSSIBILITY OF SUCH DAMAGE.
37 * Copyright (c) 1985, 1989, 1993, 1994
38 * The Regents of the University of California. All rights reserved.
40 * Redistribution and use in source and binary forms, with or without
41 * modification, are permitted provided that the following conditions
43 * 1. Redistributions of source code must retain the above copyright
44 * notice, this list of conditions and the following disclaimer.
45 * 2. Redistributions in binary form must reproduce the above copyright
46 * notice, this list of conditions and the following disclaimer in the
47 * documentation and/or other materials provided with the distribution.
48 * 3. Neither the name of the University nor the names of its contributors
49 * may be used to endorse or promote products derived from this software
50 * without specific prior written permission.
52 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
53 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
55 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
56 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
57 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
58 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
59 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
60 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
61 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
65 #include <sys/cdefs.h>
67 __RCSID("$NetBSD: util.c,v 1.158 2013/02/19 23:29:15 dsl Exp $");
71 * FTP User Program -- Misc support routines
73 #include <sys/param.h>
74 #include <sys/socket.h>
75 #include <sys/ioctl.h>
77 #include <netinet/in.h>
101 * Connect to peer server and auto-login, if possible.
104 setpeer(int argc, char *argv[])
112 fprintf(ttyout, "Already connected to %s, use close first.\n",
118 (void)another(&argc, &argv, "to");
119 if (argc < 2 || argc > 3) {
121 UPRINTF("usage: %s host-name [port]\n", argv[0]);
133 if (gateserver == NULL || *gateserver == '\0')
134 errx(1, "main: gateserver not defined");
135 host = hookup(gateserver, port);
137 host = hookup(argv[1], port);
140 if (gatemode && verbose) {
142 "Connecting via pass-through server %s\n",
148 * Set up defaults for FTP.
150 (void)strlcpy(typename, "ascii", sizeof(typename));
153 (void)strlcpy(formname, "non-print", sizeof(formname));
155 (void)strlcpy(modename, "stream", sizeof(modename));
157 (void)strlcpy(structname, "file", sizeof(structname));
159 (void)strlcpy(bytename, "8", sizeof(bytename));
162 (void)ftp_login(argv[1], NULL, NULL);
167 parse_feat(const char *fline)
171 * work-around broken ProFTPd servers that can't
172 * even obey RFC 2389.
174 while (*fline && isspace((int)*fline))
177 if (strcasecmp(fline, "MDTM") == 0)
178 features[FEAT_MDTM] = 1;
179 else if (strncasecmp(fline, "MLST", sizeof("MLST") - 1) == 0) {
180 features[FEAT_MLST] = 1;
181 } else if (strcasecmp(fline, "REST STREAM") == 0)
182 features[FEAT_REST_STREAM] = 1;
183 else if (strcasecmp(fline, "SIZE") == 0)
184 features[FEAT_SIZE] = 1;
185 else if (strcasecmp(fline, "TVFS") == 0)
186 features[FEAT_TVFS] = 1;
190 * Determine the remote system type (SYST) and features (FEAT).
191 * Call after a successful login (i.e, connected = -1)
202 /* determine remote system type */
203 if (command("SYST") == COMPLETE) {
205 int os_len = strcspn(reply_string + 4, " \r\n\t");
206 if (os_len > 1 && reply_string[4 + os_len - 1] == '.')
208 fprintf(ttyout, "Remote system type is %.*s.\n",
209 os_len, reply_string + 4);
212 * Decide whether we should default to bninary.
213 * Traditionally checked for "215 UNIX Type: L8", but
214 * some printers report "Linux" ! so be more forgiving.
215 * In reality we probably almost never want text any more.
217 if (!strncasecmp(reply_string + 4, "unix", 4) ||
218 !strncasecmp(reply_string + 4, "linux", 5)) {
224 * Set type to 0 (not specified by user),
225 * meaning binary by default, but don't bother
226 * telling server. We can use binary
227 * for text files unless changed by the user.
230 (void)strlcpy(typename, "binary", sizeof(typename));
233 "Using %s mode to transfer files.\n",
241 !strncmp(reply_string, "215 TOPS20", 10))
243 "Remember to set tenex mode when transferring binary files from this machine.\n",
248 /* determine features (if any) */
249 for (i = 0; i < FEAT_max; i++)
251 reply_callback = parse_feat;
252 if (command("FEAT") == COMPLETE) {
253 for (i = 0; i < FEAT_max; i++) {
254 if (features[i] == -1)
257 features[FEAT_FEAT] = 1;
259 features[FEAT_FEAT] = 0;
262 #define DEBUG_FEAT(x) fprintf(ttyout, "features[" #x "] = %d\n", features[(x)])
263 DEBUG_FEAT(FEAT_FEAT);
264 DEBUG_FEAT(FEAT_MDTM);
265 DEBUG_FEAT(FEAT_MLST);
266 DEBUG_FEAT(FEAT_REST_STREAM);
267 DEBUG_FEAT(FEAT_SIZE);
268 DEBUG_FEAT(FEAT_TVFS);
272 reply_callback = NULL;
278 * Reset the various variables that indicate connection state back to
279 * disconnected settings.
280 * The caller is responsible for issuing any commands to the remote server
281 * to perform a clean shutdown before this is invoked.
294 * determine if anonftp was specifically set with -a
295 * (1), or implicitly set by auto_fetch() (2). in the
296 * latter case, disable after the current xfer
311 * Top-level signal handler for interrupted commands.
320 write(fileno(ttyout), "\n", 1);
321 siglongjmp(toplevel, 1);
325 * Signal handler for lost connections; cleanup various elements of
326 * the connection state, and call cleanuppeer() to finish it off.
336 (void)shutdown(fileno(cout), 1+1);
341 (void)shutdown(data, 1+1);
350 (void)shutdown(fileno(cout), 1+1);
364 * Login to remote host, using given username & password if supplied.
365 * Return non-zero if successful.
368 ftp_login(const char *host, const char *luser, const char *lpass)
371 char *fuser, *pass, *facct, *p;
372 char emptypass[] = "";
373 const char *errormsg;
374 int n, aflag, rval, nlen;
377 fuser = pass = facct = NULL;
379 fuser = ftp_strdup(luser);
381 pass = ftp_strdup(lpass);
383 DPRINTF("ftp_login: user `%s' pass `%s' host `%s'\n",
384 STRorNULL(fuser), STRorNULL(pass), STRorNULL(host));
387 * Set up arguments for an anonymous FTP session, if necessary.
391 fuser = ftp_strdup("anonymous"); /* as per RFC 1635 */
393 pass = ftp_strdup(getoptionvalue("anonpass"));
396 if (ruserpass(host, &fuser, &pass, &facct) < 0) {
398 goto cleanup_ftp_login;
401 while (fuser == NULL) {
403 fprintf(ttyout, "Name (%s:%s): ", host, localname);
405 fprintf(ttyout, "Name (%s): ", host);
407 nlen = get_line(stdin, tmp, sizeof(tmp), &errormsg);
409 fprintf(ttyout, "%s; %s aborted.\n", errormsg, "login");
411 goto cleanup_ftp_login;
412 } else if (nlen == 0) {
413 fuser = ftp_strdup(localname);
415 fuser = ftp_strdup(tmp);
423 len = strlen(fuser) + 1 + strlen(host) + 1;
424 nuser = ftp_malloc(len);
425 (void)strlcpy(nuser, fuser, len);
426 (void)strlcat(nuser, "@", len);
427 (void)strlcat(nuser, host, len);
432 n = command("USER %s", fuser);
435 p = getpass("Password: ");
438 pass = ftp_strdup(p);
439 memset(p, 0, strlen(p));
441 n = command("PASS %s", pass);
442 memset(pass, 0, strlen(pass));
447 p = getpass("Account: ");
450 facct = ftp_strdup(p);
451 memset(p, 0, strlen(p));
453 if (facct[0] == '\0') {
454 warnx("Login failed");
455 goto cleanup_ftp_login;
457 n = command("ACCT %s", facct);
458 memset(facct, 0, strlen(facct));
460 if ((n != COMPLETE) ||
461 (!aflag && facct != NULL && command("ACCT %s", facct) != COMPLETE)) {
462 warnx("Login failed");
463 goto cleanup_ftp_login;
466 username = ftp_strdup(fuser);
468 goto cleanup_ftp_login;
472 for (n = 0; n < macnum; ++n) {
473 if (!strcmp("init", macros[n].mac_name)) {
474 (void)strlcpy(line, "$init", sizeof(line));
476 domacro(margc, margv);
486 memset(pass, 0, strlen(pass));
489 memset(facct, 0, strlen(facct));
495 * `another' gets another argument, and stores the new argc and argv.
496 * It reverts to the top level (via intr()) on EOF/error.
498 * Returns false if no new arguments have been added.
501 another(int *pargc, char ***pargv, const char *aprompt)
503 const char *errormsg;
508 if (len >= sizeof(line) - 3) {
509 fputs("Sorry, arguments too long.\n", ttyout);
512 fprintf(ttyout, "(%s) ", aprompt);
515 nlen = get_line(stdin, line + len, sizeof(line)-len, &errormsg);
517 fprintf(ttyout, "%s; %s aborted.\n", errormsg, "operation");
522 ret = margc > *pargc;
529 * glob files given in argv[] from the remote server.
530 * if errbuf isn't NULL, store error messages there instead
531 * of writing to the screen.
534 remglob(char *argv[], int doswitch, const char **errbuf)
536 static char buf[MAXPATHLEN];
537 static FILE *ftemp = NULL;
539 char temp[MAXPATHLEN];
540 int oldverbose, oldhash, oldprogress, fd;
545 if (!mflag || !connected) {
559 if ((cp = *++args) == NULL)
564 len = strlcpy(temp, tmpdir, sizeof(temp));
565 if (temp[len - 1] != '/')
566 (void)strlcat(temp, "/", sizeof(temp));
567 (void)strlcat(temp, TMPFILE, sizeof(temp));
568 if ((fd = mkstemp(temp)) < 0) {
569 warn("Unable to create temporary file `%s'", temp);
573 oldverbose = verbose;
574 verbose = (errbuf != NULL) ? -1 : 0;
576 oldprogress = progress;
581 for (rmode = "w"; *++argv != NULL; rmode = "a")
582 recvrequest("NLST", temp, *argv, rmode, 0, 0);
583 if ((code / 100) != COMPLETE) {
585 *errbuf = reply_string;
589 verbose = oldverbose;
591 progress = oldprogress;
592 ftemp = fopen(temp, "r");
596 warnx("Can't find list of remote files");
599 "Can't find list of remote files";
603 if (fgets(buf, sizeof(buf), ftemp) == NULL) {
608 if ((cp = strchr(buf, '\n')) != NULL)
614 * Glob a local file name specification with the expectation of a single
615 * return value. Can't control multiple values being expanded from the
616 * expression, we return only the first.
617 * Returns NULL on error, or a pointer to a buffer containing the filename
618 * that's the caller's responsiblity to free(3) when finished with.
621 globulize(const char *pattern)
628 return (ftp_strdup(pattern));
630 flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
631 memset(&gl, 0, sizeof(gl));
632 if (glob(pattern, flags, NULL, &gl) || gl.gl_pathc == 0) {
633 warnx("Glob pattern `%s' not found", pattern);
637 p = ftp_strdup(gl.gl_pathv[0]);
643 * determine size of remote file
646 remotesize(const char *file, int noisy)
655 if (! features[FEAT_SIZE]) {
658 "SIZE is not supported by remote server.\n");
659 goto cleanup_remotesize;
661 r = command("SIZE %s", file);
665 cp = strchr(reply_string, ' ');
668 size = STRTOLL(cp, &ep, 10);
669 if (*ep != '\0' && !isspace((unsigned char)*ep))
673 if (r == ERROR && code == 500 && features[FEAT_SIZE] == -1)
674 features[FEAT_SIZE] = 0;
675 if (noisy && ftp_debug == 0) {
676 fputs(reply_string, ttyout);
686 * determine last modification time (in GMT) of remote file
689 remotemodtime(const char *file, int noisy)
691 int overbose, ocode, r;
699 if (! features[FEAT_MDTM]) {
702 "MDTM is not supported by remote server.\n");
703 goto cleanup_parse_time;
705 r = command("MDTM %s", file);
708 char *timestr, *frac;
711 * time-val = 14DIGIT [ "." 1*DIGIT ]
712 * YYYYMMDDHHMMSS[.sss]
713 * mdtm-response = "213" SP time-val CRLF / error-response
715 timestr = reply_string + 4;
719 * XXX: ignored for now
721 frac = strchr(timestr, '\r');
724 frac = strchr(timestr, '.');
727 if (strlen(timestr) == 15 && strncmp(timestr, "191", 3) == 0) {
729 * XXX: Workaround for lame ftpd's that return
730 * `19100' instead of `2000'
733 "Y2K warning! Incorrect time-val `%s' received from server.\n",
738 fprintf(ttyout, "Converted to `%s'\n", timestr);
740 memset(&timebuf, 0, sizeof(timebuf));
741 if (strlen(timestr) != 14 ||
742 (strptime(timestr, "%Y%m%d%H%M%S", &timebuf) == NULL)) {
744 fprintf(ttyout, "Can't parse time `%s'.\n", timestr);
745 goto cleanup_parse_time;
747 timebuf.tm_isdst = -1;
748 rtime = timegm(&timebuf);
750 if (noisy || ftp_debug != 0)
753 goto cleanup_parse_time;
755 DPRINTF("remotemodtime: parsed time `%s' as " LLF
758 rfc2822time(localtime(&rtime)));
761 if (r == ERROR && code == 500 && features[FEAT_MDTM] == -1)
762 features[FEAT_MDTM] = 0;
763 if (noisy && ftp_debug == 0) {
764 fputs(reply_string, ttyout);
776 * Format tm in an RFC 2822 compatible manner, with a trailing \n.
777 * Returns a pointer to a static string containing the result.
780 rfc2822time(const struct tm *tm)
782 static char result[50];
784 if (strftime(result, sizeof(result),
785 "%a, %d %b %Y %H:%M:%S %z\n", tm) == 0)
786 errx(1, "Can't convert RFC 2822 time: buffer too small");
791 * Parse HTTP-date as per RFC 2616.
792 * Return a pointer to the next character of the consumed date string,
796 parse_rfc2616time(struct tm *parsed, const char *httpdate)
799 const char *curlocale;
801 /* The representation of %a depends on the current locale. */
802 curlocale = setlocale(LC_TIME, NULL);
803 (void)setlocale(LC_TIME, "C");
805 if ((t = strptime(httpdate, "%a, %d %b %Y %H:%M:%S GMT", parsed)) ||
807 (t = strptime(httpdate, "%a, %d-%b-%y %H:%M:%S GMT", parsed)) ||
809 (t = strptime(httpdate, "%a, %b %d %H:%M:%S %Y", parsed))) {
812 (void)setlocale(LC_TIME, curlocale);
817 * Update global `localcwd', which contains the state of the local cwd
823 if (getcwd(localcwd, sizeof(localcwd)) == NULL)
825 DPRINTF("updatelocalcwd: got `%s'\n", localcwd);
829 * Update global `remotecwd', which contains the state of the remote cwd
832 updateremotecwd(void)
842 if (command("PWD") != COMPLETE)
844 cp = strchr(reply_string, ' ');
845 if (cp == NULL || cp[0] == '\0' || cp[1] != '"')
848 for (i = 0; *cp && i < sizeof(remotecwd) - 1; i++, cp++) {
858 DPRINTF("updateremotecwd: got `%s'\n", remotecwd);
859 goto cleanupremotecwd;
868 * Ensure file is in or under dir.
869 * Returns 1 if so, 0 if not (or an error occurred).
872 fileindir(const char *file, const char *dir)
874 char parentdirbuf[PATH_MAX+1], *parentdir;
875 char realdir[PATH_MAX+1];
878 /* determine parent directory of file */
879 (void)strlcpy(parentdirbuf, file, sizeof(parentdirbuf));
880 parentdir = dirname(parentdirbuf);
881 if (strcmp(parentdir, ".") == 0)
882 return 1; /* current directory is ok */
884 /* find the directory */
885 if (realpath(parentdir, realdir) == NULL) {
886 warn("Unable to determine real path of `%s'", parentdir);
889 if (realdir[0] != '/') /* relative result is ok */
891 dirlen = strlen(dir);
892 if (strncmp(realdir, dir, dirlen) == 0 &&
893 (realdir[dirlen] == '/' || realdir[dirlen] == '\0'))
899 * List words in stringlist, vertically arranged
902 list_vertical(StringList *sl)
905 size_t columns, lines;
911 for (i = 0 ; i < sl->sl_cur ; i++) {
912 w = strlen(sl->sl_str[i]);
916 width = (width + 8) &~ 7;
918 columns = ttywidth / width;
921 lines = (sl->sl_cur + columns - 1) / columns;
922 for (i = 0; i < lines; i++) {
923 for (j = 0; j < columns; j++) {
924 p = sl->sl_str[j * lines + i];
927 if (j * lines + i + lines >= sl->sl_cur) {
935 (void)putc('\t', ttyout);
943 * Update the global ttywidth value, using TIOCGWINSZ.
948 struct winsize winsize;
951 if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
953 ttywidth = winsize.ws_col;
960 * Change the rate limit up (SIGUSR1) or down (SIGUSR2)
969 rate_get += rate_get_incr;
971 rate_put += rate_put_incr;
974 if (rate_get && rate_get > rate_get_incr)
975 rate_get -= rate_get_incr;
976 if (rate_put && rate_put > rate_put_incr)
977 rate_put -= rate_put_incr;
980 err(1, "crankrate invoked with unknown signal: %d", sig);
986 * Setup or cleanup EditLine structures
988 #ifndef NO_EDITCOMPLETE
992 if (editing && el == NULL && hist == NULL) {
996 el = el_init(getprogname(), stdin, ttyout, stderr);
998 hist = history_init(); /* init the builtin history */
999 history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
1000 el_set(el, EL_HIST, history, hist); /* use history */
1002 el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
1003 el_set(el, EL_PROMPT, prompt); /* set the prompt functions */
1004 el_set(el, EL_RPROMPT, rprompt);
1006 /* add local file completion, bind to TAB */
1007 el_set(el, EL_ADDFN, "ftp-complete",
1008 "Context sensitive argument completion",
1010 el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
1011 el_source(el, NULL); /* read ~/.editrc */
1012 if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
1013 editing = 0; /* the user doesn't want editing,
1014 * so disable, and let statement
1017 el_set(el, EL_SIGNAL, 1);
1030 #endif /* !NO_EDITCOMPLETE */
1033 * Convert the string `arg' to an int, which may have an optional SI suffix
1034 * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
1037 strsuftoi(const char *arg)
1042 if (!isdigit((unsigned char)arg[0]))
1045 val = strtol(arg, &cp, 10);
1047 if (cp[0] != '\0' && cp[1] != '\0')
1049 switch (tolower((unsigned char)cp[0])) {
1066 if (val < 0 || val > INT_MAX)
1073 * Set up socket buffer sizes before a connection is made.
1076 setupsockbufsize(int sock)
1080 if (0 == rcvbuf_size) {
1081 slen = sizeof(rcvbuf_size);
1082 if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1083 (void *)&rcvbuf_size, &slen) == -1)
1084 err(1, "Unable to determine rcvbuf size");
1085 if (rcvbuf_size <= 0)
1086 rcvbuf_size = 8 * 1024;
1087 if (rcvbuf_size > 8 * 1024 * 1024)
1088 rcvbuf_size = 8 * 1024 * 1024;
1089 DPRINTF("setupsockbufsize: rcvbuf_size determined as %d\n",
1092 if (0 == sndbuf_size) {
1093 slen = sizeof(sndbuf_size);
1094 if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF,
1095 (void *)&sndbuf_size, &slen) == -1)
1096 err(1, "Unable to determine sndbuf size");
1097 if (sndbuf_size <= 0)
1098 sndbuf_size = 8 * 1024;
1099 if (sndbuf_size > 8 * 1024 * 1024)
1100 sndbuf_size = 8 * 1024 * 1024;
1101 DPRINTF("setupsockbufsize: sndbuf_size determined as %d\n",
1105 if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
1106 (void *)&sndbuf_size, sizeof(sndbuf_size)) == -1)
1107 warn("Unable to set sndbuf size %d", sndbuf_size);
1109 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1110 (void *)&rcvbuf_size, sizeof(rcvbuf_size)) == -1)
1111 warn("Unable to set rcvbuf size %d", rcvbuf_size);
1115 * Copy characters from src into dst, \ quoting characters that require it
1118 ftpvis(char *dst, size_t dstlen, const char *src, size_t srclen)
1123 while (src[si] != '\0' && di < dstlen && si < srclen) {
1132 * Need room for two characters and NUL, avoiding
1133 * incomplete escape sequences at end of dst.
1135 if (di >= dstlen - 3)
1140 dst[di] = src[si++];
1149 * Copy src into buf (which is len bytes long), expanding % sequences.
1152 formatbuf(char *buf, size_t len, const char *src)
1154 const char *p, *p2, *q;
1156 int op, updirs, pdirs;
1158 #define ADDBUF(x) do { \
1165 for (i = 0; *p; p++) {
1177 p2 = connected ? remotecwd : "";
1180 /* option to determine fixed # of dirs from path */
1181 if (op == '.' || op == 'c') {
1185 while (*p2) /* calc # of /'s */
1188 if (p[1] == '0') { /* print <x> or ... */
1192 if (p[1] >= '1' && p[1] <= '9') {
1193 /* calc # to skip */
1200 while (skip-- > 0) {
1201 while ((p2 > q) && (*p2 != '/'))
1206 if (*p2 == '/' && p2 != q)
1210 if (updirs > 0 && pdirs) {
1224 ADDBUF('0' + updirs);
1234 for (p2 = connected && hostname ? hostname : "-";
1236 if (op == 'm' && *p2 == '.')
1243 for (p2 = connected ? username : "-"; *p2 ; p2++)
1251 default: /* display unknown codes literally */
1263 * Determine if given string is an IPv6 address or not.
1264 * Return 1 for yes, 0 for no
1267 isipv6addr(const char *addr)
1271 struct addrinfo hints, *res;
1273 memset(&hints, 0, sizeof(hints));
1274 hints.ai_family = AF_INET6;
1275 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
1276 hints.ai_flags = AI_NUMERICHOST;
1277 if (getaddrinfo(addr, "0", &hints, &res) != 0)
1283 DPRINTF("isipv6addr: got %d for %s\n", rv, addr);
1285 return (rv == 1) ? 1 : 0;
1289 * Read a line from the FILE stream into buf/buflen using fgets(), so up
1290 * to buflen-1 chars will be read and the result will be NUL terminated.
1291 * If the line has a trailing newline it will be removed.
1292 * If the line is too long, excess characters will be read until
1293 * newline/EOF/error.
1294 * If EOF/error occurs or a too-long line is encountered and errormsg
1295 * isn't NULL, it will be changed to a description of the problem.
1296 * (The EOF message has a leading \n for cosmetic purposes).
1298 * >=0 length of line (excluding trailing newline) if all ok
1300 * -2 EOF encountered
1301 * -3 line was too long
1304 get_line(FILE *stream, char *buf, size_t buflen, const char **errormsg)
1309 if (fgets(buf, buflen, stream) == NULL) {
1310 if (feof(stream)) { /* EOF */
1313 *errormsg = "\nEOF received";
1314 } else { /* error */
1317 *errormsg = "Error encountered";
1323 if (buf[len-1] == '\n') { /* clear any trailing newline */
1325 } else if (len == buflen-1) { /* line too long */
1326 while ((ch = getchar()) != '\n' && ch != EOF)
1329 *errormsg = "Input line is too long";
1339 * Internal version of connect(2); sets socket buffer sizes,
1340 * binds to a specific local address (if set), and
1341 * supports a connection timeout using a non-blocking connect(2) with
1343 * Socket fcntl flags are temporarily updated to include O_NONBLOCK;
1344 * these will not be reverted on connection failure.
1345 * Returns 0 on success, or -1 upon failure (with an appropriate
1346 * error message displayed.)
1349 ftp_connect(int sock, const struct sockaddr *name, socklen_t namelen, int pe)
1351 int flags, rv, timeout, error;
1353 struct timeval endtime, now, td;
1354 struct pollfd pfd[1];
1355 char hname[NI_MAXHOST];
1356 char sname[NI_MAXSERV];
1358 setupsockbufsize(sock);
1359 if (getnameinfo(name, namelen,
1360 hname, sizeof(hname), sname, sizeof(sname),
1361 NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
1362 strlcpy(hname, "?", sizeof(hname));
1363 strlcpy(sname, "?", sizeof(sname));
1366 if (bindai != NULL) { /* bind to specific addr */
1367 struct addrinfo *ai;
1369 for (ai = bindai; ai != NULL; ai = ai->ai_next) {
1370 if (ai->ai_family == name->sa_family)
1375 if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
1376 char bname[NI_MAXHOST];
1380 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
1381 bname, sizeof(bname), NULL, 0, NI_NUMERICHOST) != 0)
1382 strlcpy(bname, "?", sizeof(bname));
1384 warn("Can't bind to `%s'", bname);
1389 /* save current socket flags */
1390 if ((flags = fcntl(sock, F_GETFL, 0)) == -1) {
1391 warn("Can't %s socket flags for connect to `%s:%s'",
1392 "save", hname, sname);
1395 /* set non-blocking connect */
1396 if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) == -1) {
1397 warn("Can't set socket non-blocking for connect to `%s:%s'",
1402 /* NOTE: we now must restore socket flags on successful exit */
1405 pfd[0].events = POLLIN|POLLOUT;
1407 if (quit_time > 0) { /* want a non default timeout */
1408 (void)gettimeofday(&endtime, NULL);
1409 endtime.tv_sec += quit_time; /* determine end time */
1412 rv = connect(sock, name, namelen); /* inititate the connection */
1413 if (rv == -1) { /* connection error */
1414 if (errno != EINPROGRESS) { /* error isn't "please wait" */
1415 if (pe || (errno != EHOSTUNREACH))
1417 warn("Can't connect to `%s:%s'", hname, sname);
1421 /* connect EINPROGRESS; wait */
1423 if (quit_time > 0) { /* determine timeout */
1424 (void)gettimeofday(&now, NULL);
1425 timersub(&endtime, &now, &td);
1426 timeout = td.tv_sec * 1000 + td.tv_usec/1000;
1433 rv = ftp_poll(pfd, 1, timeout);
1434 /* loop until poll ! EINTR */
1435 } while (rv == -1 && errno == EINTR);
1437 if (rv == 0) { /* poll (connect) timed out */
1442 if (rv == -1) { /* poll error */
1444 } else if (pfd[0].revents & (POLLIN|POLLOUT)) {
1445 slen = sizeof(error); /* OK, or pending error */
1446 if (getsockopt(sock, SOL_SOCKET, SO_ERROR,
1447 &error, &slen) == -1) {
1448 /* Solaris pending error */
1450 } else if (error != 0) {
1451 errno = error; /* BSD pending error */
1455 errno = EBADF; /* this shouldn't happen ... */
1460 if (fcntl(sock, F_SETFL, flags) == -1) {
1461 /* restore socket flags */
1462 warn("Can't %s socket flags for connect to `%s:%s'",
1463 "restore", hname, sname);
1470 * Internal version of listen(2); sets socket buffer sizes first.
1473 ftp_listen(int sock, int backlog)
1476 setupsockbufsize(sock);
1477 return (listen(sock, backlog));
1481 * Internal version of poll(2), to allow reimplementation by select(2)
1482 * on platforms without the former.
1485 ftp_poll(struct pollfd *fds, int nfds, int timeout)
1487 return poll(fds, nfds, timeout);
1491 * malloc() with inbuilt error checking
1494 ftp_malloc(size_t size)
1500 err(1, "Unable to allocate %ld bytes of memory", (long)size);
1505 * sl_init() with inbuilt error checking
1514 err(1, "Unable to allocate memory for stringlist");
1519 * sl_add() with inbuilt error checking
1522 ftp_sl_add(StringList *sl, char *i)
1529 * strdup() with inbuilt error checking
1532 ftp_strdup(const char *str)
1537 errx(1, "ftp_strdup: called with NULL argument");
1540 err(1, "Unable to allocate memory for string copy");