1 /* $NetBSD: util.c,v 1.157 2012/07/04 06:09:37 is 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.157 2012/07/04 06:09:37 is 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) {
208 cp = strchr(reply_string + 4, ' ');
210 cp = strchr(reply_string + 4, '\r');
218 fprintf(ttyout, "Remote system type is %s.\n",
223 if (!strncmp(reply_string, "215 UNIX Type: L8", 17)) {
229 * Set type to 0 (not specified by user),
230 * meaning binary by default, but don't bother
231 * telling server. We can use binary
232 * for text files unless changed by the user.
235 (void)strlcpy(typename, "binary", sizeof(typename));
238 "Using %s mode to transfer files.\n",
246 !strncmp(reply_string, "215 TOPS20", 10))
248 "Remember to set tenex mode when transferring binary files from this machine.\n",
253 /* determine features (if any) */
254 for (i = 0; i < FEAT_max; i++)
256 reply_callback = parse_feat;
257 if (command("FEAT") == COMPLETE) {
258 for (i = 0; i < FEAT_max; i++) {
259 if (features[i] == -1)
262 features[FEAT_FEAT] = 1;
264 features[FEAT_FEAT] = 0;
267 #define DEBUG_FEAT(x) fprintf(ttyout, "features[" #x "] = %d\n", features[(x)])
268 DEBUG_FEAT(FEAT_FEAT);
269 DEBUG_FEAT(FEAT_MDTM);
270 DEBUG_FEAT(FEAT_MLST);
271 DEBUG_FEAT(FEAT_REST_STREAM);
272 DEBUG_FEAT(FEAT_SIZE);
273 DEBUG_FEAT(FEAT_TVFS);
277 reply_callback = NULL;
283 * Reset the various variables that indicate connection state back to
284 * disconnected settings.
285 * The caller is responsible for issuing any commands to the remote server
286 * to perform a clean shutdown before this is invoked.
299 * determine if anonftp was specifically set with -a
300 * (1), or implicitly set by auto_fetch() (2). in the
301 * latter case, disable after the current xfer
316 * Top-level signal handler for interrupted commands.
325 write(fileno(ttyout), "\n", 1);
326 siglongjmp(toplevel, 1);
330 * Signal handler for lost connections; cleanup various elements of
331 * the connection state, and call cleanuppeer() to finish it off.
341 (void)shutdown(fileno(cout), 1+1);
346 (void)shutdown(data, 1+1);
355 (void)shutdown(fileno(cout), 1+1);
369 * Login to remote host, using given username & password if supplied.
370 * Return non-zero if successful.
373 ftp_login(const char *host, const char *luser, const char *lpass)
376 char *fuser, *pass, *facct, *p;
377 char emptypass[] = "";
378 const char *errormsg;
379 int n, aflag, rval, nlen;
382 fuser = pass = facct = NULL;
384 fuser = ftp_strdup(luser);
386 pass = ftp_strdup(lpass);
388 DPRINTF("ftp_login: user `%s' pass `%s' host `%s'\n",
389 STRorNULL(fuser), STRorNULL(pass), STRorNULL(host));
392 * Set up arguments for an anonymous FTP session, if necessary.
396 fuser = ftp_strdup("anonymous"); /* as per RFC 1635 */
398 pass = ftp_strdup(getoptionvalue("anonpass"));
401 if (ruserpass(host, &fuser, &pass, &facct) < 0) {
403 goto cleanup_ftp_login;
406 while (fuser == NULL) {
408 fprintf(ttyout, "Name (%s:%s): ", host, localname);
410 fprintf(ttyout, "Name (%s): ", host);
412 nlen = get_line(stdin, tmp, sizeof(tmp), &errormsg);
414 fprintf(ttyout, "%s; %s aborted.\n", errormsg, "login");
416 goto cleanup_ftp_login;
417 } else if (nlen == 0) {
418 fuser = ftp_strdup(localname);
420 fuser = ftp_strdup(tmp);
428 len = strlen(fuser) + 1 + strlen(host) + 1;
429 nuser = ftp_malloc(len);
430 (void)strlcpy(nuser, fuser, len);
431 (void)strlcat(nuser, "@", len);
432 (void)strlcat(nuser, host, len);
437 n = command("USER %s", fuser);
440 p = getpass("Password: ");
443 pass = ftp_strdup(p);
444 memset(p, 0, strlen(p));
446 n = command("PASS %s", pass);
447 memset(pass, 0, strlen(pass));
452 p = getpass("Account: ");
455 facct = ftp_strdup(p);
456 memset(p, 0, strlen(p));
458 if (facct[0] == '\0') {
459 warnx("Login failed");
460 goto cleanup_ftp_login;
462 n = command("ACCT %s", facct);
463 memset(facct, 0, strlen(facct));
465 if ((n != COMPLETE) ||
466 (!aflag && facct != NULL && command("ACCT %s", facct) != COMPLETE)) {
467 warnx("Login failed");
468 goto cleanup_ftp_login;
471 username = ftp_strdup(fuser);
473 goto cleanup_ftp_login;
477 for (n = 0; n < macnum; ++n) {
478 if (!strcmp("init", macros[n].mac_name)) {
479 (void)strlcpy(line, "$init", sizeof(line));
481 domacro(margc, margv);
491 memset(pass, 0, strlen(pass));
494 memset(facct, 0, strlen(facct));
500 * `another' gets another argument, and stores the new argc and argv.
501 * It reverts to the top level (via intr()) on EOF/error.
503 * Returns false if no new arguments have been added.
506 another(int *pargc, char ***pargv, const char *aprompt)
508 const char *errormsg;
513 if (len >= sizeof(line) - 3) {
514 fputs("Sorry, arguments too long.\n", ttyout);
517 fprintf(ttyout, "(%s) ", aprompt);
520 nlen = get_line(stdin, line + len, sizeof(line)-len, &errormsg);
522 fprintf(ttyout, "%s; %s aborted.\n", errormsg, "operation");
527 ret = margc > *pargc;
534 * glob files given in argv[] from the remote server.
535 * if errbuf isn't NULL, store error messages there instead
536 * of writing to the screen.
539 remglob(char *argv[], int doswitch, const char **errbuf)
541 static char buf[MAXPATHLEN];
542 static FILE *ftemp = NULL;
544 char temp[MAXPATHLEN];
545 int oldverbose, oldhash, oldprogress, fd;
550 if (!mflag || !connected) {
564 if ((cp = *++args) == NULL)
569 len = strlcpy(temp, tmpdir, sizeof(temp));
570 if (temp[len - 1] != '/')
571 (void)strlcat(temp, "/", sizeof(temp));
572 (void)strlcat(temp, TMPFILE, sizeof(temp));
573 if ((fd = mkstemp(temp)) < 0) {
574 warn("Unable to create temporary file `%s'", temp);
578 oldverbose = verbose;
579 verbose = (errbuf != NULL) ? -1 : 0;
581 oldprogress = progress;
586 for (rmode = "w"; *++argv != NULL; rmode = "a")
587 recvrequest("NLST", temp, *argv, rmode, 0, 0);
588 if ((code / 100) != COMPLETE) {
590 *errbuf = reply_string;
594 verbose = oldverbose;
596 progress = oldprogress;
597 ftemp = fopen(temp, "r");
601 warnx("Can't find list of remote files");
604 "Can't find list of remote files";
608 if (fgets(buf, sizeof(buf), ftemp) == NULL) {
613 if ((cp = strchr(buf, '\n')) != NULL)
619 * Glob a local file name specification with the expectation of a single
620 * return value. Can't control multiple values being expanded from the
621 * expression, we return only the first.
622 * Returns NULL on error, or a pointer to a buffer containing the filename
623 * that's the caller's responsiblity to free(3) when finished with.
626 globulize(const char *pattern)
633 return (ftp_strdup(pattern));
635 flags = GLOB_BRACE|GLOB_NOCHECK|GLOB_TILDE;
636 memset(&gl, 0, sizeof(gl));
637 if (glob(pattern, flags, NULL, &gl) || gl.gl_pathc == 0) {
638 warnx("Glob pattern `%s' not found", pattern);
642 p = ftp_strdup(gl.gl_pathv[0]);
648 * determine size of remote file
651 remotesize(const char *file, int noisy)
660 if (! features[FEAT_SIZE]) {
663 "SIZE is not supported by remote server.\n");
664 goto cleanup_remotesize;
666 r = command("SIZE %s", file);
670 cp = strchr(reply_string, ' ');
673 size = STRTOLL(cp, &ep, 10);
674 if (*ep != '\0' && !isspace((unsigned char)*ep))
678 if (r == ERROR && code == 500 && features[FEAT_SIZE] == -1)
679 features[FEAT_SIZE] = 0;
680 if (noisy && ftp_debug == 0) {
681 fputs(reply_string, ttyout);
691 * determine last modification time (in GMT) of remote file
694 remotemodtime(const char *file, int noisy)
696 int overbose, ocode, r;
704 if (! features[FEAT_MDTM]) {
707 "MDTM is not supported by remote server.\n");
708 goto cleanup_parse_time;
710 r = command("MDTM %s", file);
713 char *timestr, *frac;
716 * time-val = 14DIGIT [ "." 1*DIGIT ]
717 * YYYYMMDDHHMMSS[.sss]
718 * mdtm-response = "213" SP time-val CRLF / error-response
720 timestr = reply_string + 4;
724 * XXX: ignored for now
726 frac = strchr(timestr, '\r');
729 frac = strchr(timestr, '.');
732 if (strlen(timestr) == 15 && strncmp(timestr, "191", 3) == 0) {
734 * XXX: Workaround for lame ftpd's that return
735 * `19100' instead of `2000'
738 "Y2K warning! Incorrect time-val `%s' received from server.\n",
743 fprintf(ttyout, "Converted to `%s'\n", timestr);
745 memset(&timebuf, 0, sizeof(timebuf));
746 if (strlen(timestr) != 14 ||
747 (strptime(timestr, "%Y%m%d%H%M%S", &timebuf) == NULL)) {
749 fprintf(ttyout, "Can't parse time `%s'.\n", timestr);
750 goto cleanup_parse_time;
752 timebuf.tm_isdst = -1;
753 rtime = timegm(&timebuf);
755 if (noisy || ftp_debug != 0)
758 goto cleanup_parse_time;
760 DPRINTF("remotemodtime: parsed time `%s' as " LLF
763 rfc2822time(localtime(&rtime)));
766 if (r == ERROR && code == 500 && features[FEAT_MDTM] == -1)
767 features[FEAT_MDTM] = 0;
768 if (noisy && ftp_debug == 0) {
769 fputs(reply_string, ttyout);
781 * Format tm in an RFC 2822 compatible manner, with a trailing \n.
782 * Returns a pointer to a static string containing the result.
785 rfc2822time(const struct tm *tm)
787 static char result[50];
789 if (strftime(result, sizeof(result),
790 "%a, %d %b %Y %H:%M:%S %z\n", tm) == 0)
791 errx(1, "Can't convert RFC 2822 time: buffer too small");
796 * Parse HTTP-date as per RFC 2616.
797 * Return a pointer to the next character of the consumed date string,
801 parse_rfc2616time(struct tm *parsed, const char *httpdate)
804 const char *curlocale;
806 /* The representation of %a depends on the current locale. */
807 curlocale = setlocale(LC_TIME, NULL);
808 (void)setlocale(LC_TIME, "C");
810 if ((t = strptime(httpdate, "%a, %d %b %Y %H:%M:%S GMT", parsed)) ||
812 (t = strptime(httpdate, "%a, %d-%b-%y %H:%M:%S GMT", parsed)) ||
814 (t = strptime(httpdate, "%a, %b %d %H:%M:%S %Y", parsed))) {
817 (void)setlocale(LC_TIME, curlocale);
822 * Update global `localcwd', which contains the state of the local cwd
828 if (getcwd(localcwd, sizeof(localcwd)) == NULL)
830 DPRINTF("updatelocalcwd: got `%s'\n", localcwd);
834 * Update global `remotecwd', which contains the state of the remote cwd
837 updateremotecwd(void)
847 if (command("PWD") != COMPLETE)
849 cp = strchr(reply_string, ' ');
850 if (cp == NULL || cp[0] == '\0' || cp[1] != '"')
853 for (i = 0; *cp && i < sizeof(remotecwd) - 1; i++, cp++) {
863 DPRINTF("updateremotecwd: got `%s'\n", remotecwd);
864 goto cleanupremotecwd;
873 * Ensure file is in or under dir.
874 * Returns 1 if so, 0 if not (or an error occurred).
877 fileindir(const char *file, const char *dir)
879 char parentdirbuf[PATH_MAX+1], *parentdir;
880 char realdir[PATH_MAX+1];
883 /* determine parent directory of file */
884 (void)strlcpy(parentdirbuf, file, sizeof(parentdirbuf));
885 parentdir = dirname(parentdirbuf);
886 if (strcmp(parentdir, ".") == 0)
887 return 1; /* current directory is ok */
889 /* find the directory */
890 if (realpath(parentdir, realdir) == NULL) {
891 warn("Unable to determine real path of `%s'", parentdir);
894 if (realdir[0] != '/') /* relative result is ok */
896 dirlen = strlen(dir);
897 if (strncmp(realdir, dir, dirlen) == 0 &&
898 (realdir[dirlen] == '/' || realdir[dirlen] == '\0'))
904 * List words in stringlist, vertically arranged
907 list_vertical(StringList *sl)
910 size_t columns, lines;
916 for (i = 0 ; i < sl->sl_cur ; i++) {
917 w = strlen(sl->sl_str[i]);
921 width = (width + 8) &~ 7;
923 columns = ttywidth / width;
926 lines = (sl->sl_cur + columns - 1) / columns;
927 for (i = 0; i < lines; i++) {
928 for (j = 0; j < columns; j++) {
929 p = sl->sl_str[j * lines + i];
932 if (j * lines + i + lines >= sl->sl_cur) {
940 (void)putc('\t', ttyout);
948 * Update the global ttywidth value, using TIOCGWINSZ.
953 struct winsize winsize;
956 if (ioctl(fileno(ttyout), TIOCGWINSZ, &winsize) != -1 &&
958 ttywidth = winsize.ws_col;
965 * Change the rate limit up (SIGUSR1) or down (SIGUSR2)
974 rate_get += rate_get_incr;
976 rate_put += rate_put_incr;
979 if (rate_get && rate_get > rate_get_incr)
980 rate_get -= rate_get_incr;
981 if (rate_put && rate_put > rate_put_incr)
982 rate_put -= rate_put_incr;
985 err(1, "crankrate invoked with unknown signal: %d", sig);
991 * Setup or cleanup EditLine structures
993 #ifndef NO_EDITCOMPLETE
997 if (editing && el == NULL && hist == NULL) {
1001 el = el_init(getprogname(), stdin, ttyout, stderr);
1003 hist = history_init(); /* init the builtin history */
1004 history(hist, &ev, H_SETSIZE, 100);/* remember 100 events */
1005 el_set(el, EL_HIST, history, hist); /* use history */
1007 el_set(el, EL_EDITOR, "emacs"); /* default editor is emacs */
1008 el_set(el, EL_PROMPT, prompt); /* set the prompt functions */
1009 el_set(el, EL_RPROMPT, rprompt);
1011 /* add local file completion, bind to TAB */
1012 el_set(el, EL_ADDFN, "ftp-complete",
1013 "Context sensitive argument completion",
1015 el_set(el, EL_BIND, "^I", "ftp-complete", NULL);
1016 el_source(el, NULL); /* read ~/.editrc */
1017 if ((el_get(el, EL_EDITMODE, &editmode) != -1) && editmode == 0)
1018 editing = 0; /* the user doesn't want editing,
1019 * so disable, and let statement
1022 el_set(el, EL_SIGNAL, 1);
1035 #endif /* !NO_EDITCOMPLETE */
1038 * Convert the string `arg' to an int, which may have an optional SI suffix
1039 * (`b', `k', `m', `g'). Returns the number for success, -1 otherwise.
1042 strsuftoi(const char *arg)
1047 if (!isdigit((unsigned char)arg[0]))
1050 val = strtol(arg, &cp, 10);
1052 if (cp[0] != '\0' && cp[1] != '\0')
1054 switch (tolower((unsigned char)cp[0])) {
1071 if (val < 0 || val > INT_MAX)
1078 * Set up socket buffer sizes before a connection is made.
1081 setupsockbufsize(int sock)
1085 if (0 == rcvbuf_size) {
1086 slen = sizeof(rcvbuf_size);
1087 if (getsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1088 (void *)&rcvbuf_size, &slen) == -1)
1089 err(1, "Unable to determine rcvbuf size");
1090 if (rcvbuf_size <= 0)
1091 rcvbuf_size = 8 * 1024;
1092 if (rcvbuf_size > 8 * 1024 * 1024)
1093 rcvbuf_size = 8 * 1024 * 1024;
1094 DPRINTF("setupsockbufsize: rcvbuf_size determined as %d\n",
1097 if (0 == sndbuf_size) {
1098 slen = sizeof(sndbuf_size);
1099 if (getsockopt(sock, SOL_SOCKET, SO_SNDBUF,
1100 (void *)&sndbuf_size, &slen) == -1)
1101 err(1, "Unable to determine sndbuf size");
1102 if (sndbuf_size <= 0)
1103 sndbuf_size = 8 * 1024;
1104 if (sndbuf_size > 8 * 1024 * 1024)
1105 sndbuf_size = 8 * 1024 * 1024;
1106 DPRINTF("setupsockbufsize: sndbuf_size determined as %d\n",
1110 if (setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
1111 (void *)&sndbuf_size, sizeof(sndbuf_size)) == -1)
1112 warn("Unable to set sndbuf size %d", sndbuf_size);
1114 if (setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
1115 (void *)&rcvbuf_size, sizeof(rcvbuf_size)) == -1)
1116 warn("Unable to set rcvbuf size %d", rcvbuf_size);
1120 * Copy characters from src into dst, \ quoting characters that require it
1123 ftpvis(char *dst, size_t dstlen, const char *src, size_t srclen)
1128 while (src[si] != '\0' && di < dstlen && si < srclen) {
1137 * Need room for two characters and NUL, avoiding
1138 * incomplete escape sequences at end of dst.
1140 if (di >= dstlen - 3)
1145 dst[di] = src[si++];
1154 * Copy src into buf (which is len bytes long), expanding % sequences.
1157 formatbuf(char *buf, size_t len, const char *src)
1159 const char *p, *p2, *q;
1161 int op, updirs, pdirs;
1163 #define ADDBUF(x) do { \
1170 for (i = 0; *p; p++) {
1182 p2 = connected ? remotecwd : "";
1185 /* option to determine fixed # of dirs from path */
1186 if (op == '.' || op == 'c') {
1190 while (*p2) /* calc # of /'s */
1193 if (p[1] == '0') { /* print <x> or ... */
1197 if (p[1] >= '1' && p[1] <= '9') {
1198 /* calc # to skip */
1205 while (skip-- > 0) {
1206 while ((p2 > q) && (*p2 != '/'))
1211 if (*p2 == '/' && p2 != q)
1215 if (updirs > 0 && pdirs) {
1229 ADDBUF('0' + updirs);
1239 for (p2 = connected && hostname ? hostname : "-";
1241 if (op == 'm' && *p2 == '.')
1248 for (p2 = connected ? username : "-"; *p2 ; p2++)
1256 default: /* display unknown codes literally */
1268 * Determine if given string is an IPv6 address or not.
1269 * Return 1 for yes, 0 for no
1272 isipv6addr(const char *addr)
1276 struct addrinfo hints, *res;
1278 memset(&hints, 0, sizeof(hints));
1279 hints.ai_family = AF_INET6;
1280 hints.ai_socktype = SOCK_DGRAM; /*dummy*/
1281 hints.ai_flags = AI_NUMERICHOST;
1282 if (getaddrinfo(addr, "0", &hints, &res) != 0)
1288 DPRINTF("isipv6addr: got %d for %s\n", rv, addr);
1290 return (rv == 1) ? 1 : 0;
1294 * Read a line from the FILE stream into buf/buflen using fgets(), so up
1295 * to buflen-1 chars will be read and the result will be NUL terminated.
1296 * If the line has a trailing newline it will be removed.
1297 * If the line is too long, excess characters will be read until
1298 * newline/EOF/error.
1299 * If EOF/error occurs or a too-long line is encountered and errormsg
1300 * isn't NULL, it will be changed to a description of the problem.
1301 * (The EOF message has a leading \n for cosmetic purposes).
1303 * >=0 length of line (excluding trailing newline) if all ok
1305 * -2 EOF encountered
1306 * -3 line was too long
1309 get_line(FILE *stream, char *buf, size_t buflen, const char **errormsg)
1314 if (fgets(buf, buflen, stream) == NULL) {
1315 if (feof(stream)) { /* EOF */
1318 *errormsg = "\nEOF received";
1319 } else { /* error */
1322 *errormsg = "Error encountered";
1328 if (buf[len-1] == '\n') { /* clear any trailing newline */
1330 } else if (len == buflen-1) { /* line too long */
1331 while ((ch = getchar()) != '\n' && ch != EOF)
1334 *errormsg = "Input line is too long";
1344 * Internal version of connect(2); sets socket buffer sizes,
1345 * binds to a specific local address (if set), and
1346 * supports a connection timeout using a non-blocking connect(2) with
1348 * Socket fcntl flags are temporarily updated to include O_NONBLOCK;
1349 * these will not be reverted on connection failure.
1350 * Returns 0 on success, or -1 upon failure (with an appropriate
1351 * error message displayed.)
1354 ftp_connect(int sock, const struct sockaddr *name, socklen_t namelen, int pe)
1356 int flags, rv, timeout, error;
1358 struct timeval endtime, now, td;
1359 struct pollfd pfd[1];
1360 char hname[NI_MAXHOST];
1361 char sname[NI_MAXSERV];
1363 setupsockbufsize(sock);
1364 if (getnameinfo(name, namelen,
1365 hname, sizeof(hname), sname, sizeof(sname),
1366 NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
1367 strlcpy(hname, "?", sizeof(hname));
1368 strlcpy(sname, "?", sizeof(sname));
1371 if (bindai != NULL) { /* bind to specific addr */
1372 struct addrinfo *ai;
1374 for (ai = bindai; ai != NULL; ai = ai->ai_next) {
1375 if (ai->ai_family == name->sa_family)
1380 if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
1381 char bname[NI_MAXHOST];
1385 if (getnameinfo(ai->ai_addr, ai->ai_addrlen,
1386 bname, sizeof(bname), NULL, 0, NI_NUMERICHOST) != 0)
1387 strlcpy(bname, "?", sizeof(bname));
1389 warn("Can't bind to `%s'", bname);
1394 /* save current socket flags */
1395 if ((flags = fcntl(sock, F_GETFL, 0)) == -1) {
1396 warn("Can't %s socket flags for connect to `%s:%s'",
1397 "save", hname, sname);
1400 /* set non-blocking connect */
1401 if (fcntl(sock, F_SETFL, flags | O_NONBLOCK) == -1) {
1402 warn("Can't set socket non-blocking for connect to `%s:%s'",
1407 /* NOTE: we now must restore socket flags on successful exit */
1410 pfd[0].events = POLLIN|POLLOUT;
1412 if (quit_time > 0) { /* want a non default timeout */
1413 (void)gettimeofday(&endtime, NULL);
1414 endtime.tv_sec += quit_time; /* determine end time */
1417 rv = connect(sock, name, namelen); /* inititate the connection */
1418 if (rv == -1) { /* connection error */
1419 if (errno != EINPROGRESS) { /* error isn't "please wait" */
1420 if (pe || (errno != EHOSTUNREACH))
1422 warn("Can't connect to `%s:%s'", hname, sname);
1426 /* connect EINPROGRESS; wait */
1428 if (quit_time > 0) { /* determine timeout */
1429 (void)gettimeofday(&now, NULL);
1430 timersub(&endtime, &now, &td);
1431 timeout = td.tv_sec * 1000 + td.tv_usec/1000;
1438 rv = ftp_poll(pfd, 1, timeout);
1439 /* loop until poll ! EINTR */
1440 } while (rv == -1 && errno == EINTR);
1442 if (rv == 0) { /* poll (connect) timed out */
1447 if (rv == -1) { /* poll error */
1449 } else if (pfd[0].revents & (POLLIN|POLLOUT)) {
1450 slen = sizeof(error); /* OK, or pending error */
1451 if (getsockopt(sock, SOL_SOCKET, SO_ERROR,
1452 &error, &slen) == -1) {
1453 /* Solaris pending error */
1455 } else if (error != 0) {
1456 errno = error; /* BSD pending error */
1460 errno = EBADF; /* this shouldn't happen ... */
1465 if (fcntl(sock, F_SETFL, flags) == -1) {
1466 /* restore socket flags */
1467 warn("Can't %s socket flags for connect to `%s:%s'",
1468 "restore", hname, sname);
1475 * Internal version of listen(2); sets socket buffer sizes first.
1478 ftp_listen(int sock, int backlog)
1481 setupsockbufsize(sock);
1482 return (listen(sock, backlog));
1486 * Internal version of poll(2), to allow reimplementation by select(2)
1487 * on platforms without the former.
1490 ftp_poll(struct pollfd *fds, int nfds, int timeout)
1492 return poll(fds, nfds, timeout);
1496 * malloc() with inbuilt error checking
1499 ftp_malloc(size_t size)
1505 err(1, "Unable to allocate %ld bytes of memory", (long)size);
1510 * sl_init() with inbuilt error checking
1519 err(1, "Unable to allocate memory for stringlist");
1524 * sl_add() with inbuilt error checking
1527 ftp_sl_add(StringList *sl, char *i)
1534 * strdup() with inbuilt error checking
1537 ftp_strdup(const char *str)
1542 errx(1, "ftp_strdup: called with NULL argument");
1545 err(1, "Unable to allocate memory for string copy");