1 /* $NetBSD: fetch.c,v 1.206 2014/10/26 16:21:59 christos 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 Scott Aaron Bamford.
13 * Redistribution and use in source and binary forms, with or without
14 * modification, are permitted provided that the following conditions
16 * 1. Redistributions of source code must retain the above copyright
17 * notice, this list of conditions and the following disclaimer.
18 * 2. Redistributions in binary form must reproduce the above copyright
19 * notice, this list of conditions and the following disclaimer in the
20 * documentation and/or other materials provided with the distribution.
22 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
23 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
24 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
25 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
26 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 * POSSIBILITY OF SUCH DAMAGE.
35 #include <sys/cdefs.h>
37 __RCSID("$NetBSD: fetch.c,v 1.206 2014/10/26 16:21:59 christos Exp $");
41 * FTP User Program -- Command line file retrieval
44 #include <sys/types.h>
45 #include <sys/param.h>
46 #include <sys/socket.h>
50 #include <netinet/in.h>
53 #include <arpa/inet.h>
83 __dead static void aborthttp(int);
84 __dead static void timeouthttp(int);
86 static int auth_url(const char *, char **, const char *, const char *);
87 static void base64_encode(const unsigned char *, size_t, unsigned char *);
89 static int go_fetch(const char *);
90 static int fetch_ftp(const char *);
91 static int fetch_url(const char *, const char *, char *, char *);
92 static const char *match_token(const char **, const char *);
93 static int parse_url(const char *, const char *, url_t *, char **,
94 char **, char **, char **, in_port_t *, char **);
95 static void url_decode(char *);
97 static int redirect_loop;
100 #define STRNEQUAL(a,b) (strncasecmp((a), (b), sizeof((b))-1) == 0)
101 #define ISLWS(x) ((x)=='\r' || (x)=='\n' || (x)==' ' || (x)=='\t')
102 #define SKIPLWS(x) do { while (ISLWS((*x))) x++; } while (0)
105 #define ABOUT_URL "about:" /* propaganda */
106 #define FILE_URL "file://" /* file URL prefix */
107 #define FTP_URL "ftp://" /* ftp URL prefix */
108 #define HTTP_URL "http://" /* http URL prefix */
110 #define HTTPS_URL "https://" /* https URL prefix */
112 #define IS_HTTP_TYPE(urltype) \
113 (((urltype) == HTTP_URL_T) || ((urltype) == HTTPS_URL_T))
115 #define IS_HTTP_TYPE(urltype) \
116 ((urltype) == HTTP_URL_T)
120 * Determine if token is the next word in buf (case insensitive).
121 * If so, advance buf past the token and any trailing LWS, and
122 * return a pointer to the token (in buf). Otherwise, return NULL.
123 * token may be preceded by LWS.
124 * token must be followed by LWS or NUL. (I.e, don't partial match).
127 match_token(const char **buf, const char *token)
129 const char *p, *orig;
132 tlen = strlen(token);
136 if (strncasecmp(p, token, tlen) != 0)
139 if (*p != '\0' && !ISLWS(*p))
149 * Generate authorization response based on given authentication challenge.
150 * Returns -1 if an error occurred, otherwise 0.
151 * Sets response to a malloc(3)ed string; caller should free.
154 auth_url(const char *challenge, char **response, const char *guser,
157 const char *cp, *scheme, *errormsg;
158 char *ep, *clear, *realm;
159 char uuser[BUFSIZ], *gotpass;
162 size_t len, clen, rlen;
165 clear = realm = NULL;
168 scheme = "Basic"; /* only support Basic authentication */
171 DPRINTF("auth_url: challenge `%s'\n", challenge);
173 if (! match_token(&cp, scheme)) {
174 warnx("Unsupported authentication challenge `%s'",
176 goto cleanup_auth_url;
179 #define REALM "realm=\""
180 if (STRNEQUAL(cp, REALM))
181 cp += sizeof(REALM) - 1;
183 warnx("Unsupported authentication challenge `%s'",
185 goto cleanup_auth_url;
187 /* XXX: need to improve quoted-string parsing to support \ quoting, etc. */
188 if ((ep = strchr(cp, '\"')) != NULL) {
190 realm = (char *)ftp_malloc(len + 1);
191 (void)strlcpy(realm, cp, len + 1);
193 warnx("Unsupported authentication challenge `%s'",
195 goto cleanup_auth_url;
198 fprintf(ttyout, "Username for `%s': ", realm);
200 (void)strlcpy(uuser, guser, sizeof(uuser));
201 fprintf(ttyout, "%s\n", uuser);
203 (void)fflush(ttyout);
204 if (get_line(stdin, uuser, sizeof(uuser), &errormsg) < 0) {
205 warnx("%s; can't authenticate", errormsg);
206 goto cleanup_auth_url;
212 gotpass = getpass("Password: ");
213 if (gotpass == NULL) {
214 warnx("Can't read password");
215 goto cleanup_auth_url;
220 clen = strlen(uuser) + strlen(upass) + 2; /* user + ":" + pass + "\0" */
221 clear = (char *)ftp_malloc(clen);
222 (void)strlcpy(clear, uuser, clen);
223 (void)strlcat(clear, ":", clen);
224 (void)strlcat(clear, upass, clen);
226 memset(gotpass, 0, strlen(gotpass));
228 /* scheme + " " + enc + "\0" */
229 rlen = strlen(scheme) + 1 + (clen + 2) * 4 / 3 + 1;
230 *response = (char *)ftp_malloc(rlen);
231 (void)strlcpy(*response, scheme, rlen);
232 len = strlcat(*response, " ", rlen);
233 /* use `clen - 1' to not encode the trailing NUL */
234 base64_encode((unsigned char *)clear, clen - 1,
235 (unsigned char *)*response + len);
236 memset(clear, 0, clen);
246 * Encode len bytes starting at clear using base64 encoding into encoded,
247 * which should be at least ((len + 2) * 4 / 3 + 1) in size.
250 base64_encode(const unsigned char *clear, size_t len, unsigned char *encoded)
252 static const unsigned char enc[] =
253 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
258 for (i = 0; i < len; i += 3) {
259 *(cp++) = enc[((clear[i + 0] >> 2))];
260 *(cp++) = enc[((clear[i + 0] << 4) & 0x30)
261 | ((clear[i + 1] >> 4) & 0x0f)];
262 *(cp++) = enc[((clear[i + 1] << 2) & 0x3c)
263 | ((clear[i + 2] >> 6) & 0x03)];
264 *(cp++) = enc[((clear[i + 2] ) & 0x3f)];
273 * Decode %xx escapes in given string, `in-place'.
276 url_decode(char *url)
278 unsigned char *p, *q;
280 if (EMPTYSTRING(url))
282 p = q = (unsigned char *)url;
284 #define HEXTOINT(x) (x - (isdigit(x) ? '0' : (islower(x) ? 'a' : 'A') - 10))
287 && p[1] && isxdigit((unsigned char)p[1])
288 && p[2] && isxdigit((unsigned char)p[2])) {
289 *q++ = HEXTOINT(p[1]) * 16 + HEXTOINT(p[2]);
299 * Parse URL of form (per RFC 3986):
300 * <type>://[<user>[:<password>]@]<host>[:<port>][/<path>]
301 * Returns -1 if a parse error occurred, otherwise 0.
302 * It's the caller's responsibility to url_decode() the returned
303 * user, pass and path.
305 * Sets type to url_t, each of the given char ** pointers to a
306 * malloc(3)ed strings of the relevant section, and port to
307 * the number given, or ftpport if ftp://, or httpport if http://.
309 * XXX: this is not totally RFC 3986 compliant; <path> will have the
310 * leading `/' unless it's an ftp:// URL, as this makes things easier
311 * for file:// and http:// URLs. ftp:// URLs have the `/' between the
312 * host and the URL-path removed, but any additional leading slashes
313 * in the URL-path are retained (because they imply that we should
314 * later do "CWD" with a null argument).
317 * input URL output path
318 * --------- -----------
321 * "http://host/path" "/path"
322 * "file://host/dir/file" "dir/file"
326 * "ftp://host/dir/file" "dir/file"
327 * "ftp://host//dir/file" "/dir/file"
330 parse_url(const char *url, const char *desc, url_t *utype,
331 char **uuser, char **pass, char **host, char **port,
332 in_port_t *portnum, char **path)
334 const char *origurl, *tport;
335 char *cp, *ep, *thost;
338 if (url == NULL || desc == NULL || utype == NULL || uuser == NULL
339 || pass == NULL || host == NULL || port == NULL || portnum == NULL
341 errx(1, "parse_url: invoked with NULL argument!");
342 DPRINTF("parse_url: %s `%s'\n", desc, url);
345 *utype = UNKNOWN_URL_T;
346 *uuser = *pass = *host = *port = *path = NULL;
350 if (STRNEQUAL(url, HTTP_URL)) {
351 url += sizeof(HTTP_URL) - 1;
353 *portnum = HTTP_PORT;
355 } else if (STRNEQUAL(url, FTP_URL)) {
356 url += sizeof(FTP_URL) - 1;
360 } else if (STRNEQUAL(url, FILE_URL)) {
361 url += sizeof(FILE_URL) - 1;
364 } else if (STRNEQUAL(url, HTTPS_URL)) {
365 url += sizeof(HTTPS_URL) - 1;
366 *utype = HTTPS_URL_T;
367 *portnum = HTTPS_PORT;
371 warnx("Invalid %s `%s'", desc, url);
375 memset(*pass, 0, strlen(*pass));
386 /* find [user[:pass]@]host[:port] */
387 ep = strchr(url, '/');
389 thost = ftp_strdup(url);
392 thost = (char *)ftp_malloc(len + 1);
393 (void)strlcpy(thost, url, len + 1);
394 if (*utype == FTP_URL_T) /* skip first / for ftp URLs */
396 *path = ftp_strdup(ep);
399 cp = strchr(thost, '@'); /* look for user[:pass]@ in URLs */
401 if (*utype == FTP_URL_T)
402 anonftp = 0; /* disable anonftp */
405 thost = ftp_strdup(cp + 1);
406 cp = strchr(*uuser, ':');
409 *pass = ftp_strdup(cp + 1);
418 * Check if thost is an encoded IPv6 address, as per
420 * `[' ipv6-address ']'
424 if ((ep = strchr(cp, ']')) == NULL ||
425 (ep[1] != '\0' && ep[1] != ':')) {
426 warnx("Invalid address `%s' in %s `%s'",
427 thost, desc, origurl);
428 goto cleanup_parse_url;
430 len = ep - cp; /* change `[xyz]' -> `xyz' */
431 memmove(thost, thost + 1, len);
433 if (! isipv6addr(thost)) {
434 warnx("Invalid IPv6 address `%s' in %s `%s'",
435 thost, desc, origurl);
436 goto cleanup_parse_url;
445 if ((cp = strchr(thost, ':')) != NULL)
449 /* look for [:port] */
453 nport = strtoul(cp, &ep, 10);
454 if (*cp == '\0' || *ep != '\0' ||
455 nport < 1 || nport > MAX_IN_PORT_T) {
456 warnx("Unknown port `%s' in %s `%s'",
458 goto cleanup_parse_url;
465 *port = ftp_strdup(tport);
467 const char *emptypath = "/";
468 if (*utype == FTP_URL_T) /* skip first / for ftp URLs */
470 *path = ftp_strdup(emptypath);
473 DPRINTF("parse_url: user `%s' pass `%s' host %s port %s(%d) "
475 STRorNULL(*uuser), STRorNULL(*pass),
476 STRorNULL(*host), STRorNULL(*port),
477 *portnum ? *portnum : -1, STRorNULL(*path));
482 sigjmp_buf httpabort;
485 * Retrieve URL, via a proxy if necessary, using HTTP.
486 * If proxyenv is set, use that for the proxy, otherwise try ftp_proxy or
487 * http_proxy/https_proxy as appropriate.
488 * Supports HTTP redirects.
489 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
490 * is still open (e.g, ftp xfer with trailing /)
493 fetch_url(const char *url, const char *proxyenv, char *proxyauth, char *wwwauth)
495 struct addrinfo hints, *res, *res0 = NULL;
497 sigfunc volatile oldint;
498 sigfunc volatile oldpipe;
499 sigfunc volatile oldalrm;
500 sigfunc volatile oldquit;
503 int volatile ischunked;
504 int volatile isproxy;
509 static size_t bufsize;
510 static char *xferbuf;
511 const char *cp, *token;
514 const char *errormsg;
515 char *volatile savefile;
517 char *volatile location;
518 char *volatile message;
519 char *uuser, *pass, *host, *port, *path;
520 char *volatile decodedpath;
521 char *puser, *ppass, *useragent;
522 off_t hashbytes, rangestart, rangeend, entitylen;
523 int (*volatile closefunc)(FILE *);
526 const char *volatile penv = proxyenv;
534 DPRINTF("%s: `%s' proxyenv `%s'\n", __func__, url, STRorNULL(penv));
536 oldquit = oldalrm = oldint = oldpipe = NULL;
542 auth = location = message = NULL;
543 ischunked = isproxy = hcode = 0;
545 uuser = pass = host = path = decodedpath = puser = ppass = NULL;
547 if (sigsetjmp(httpabort, 1))
548 goto cleanup_fetch_url;
550 if (parse_url(url, "URL", &urltype, &uuser, &pass, &host, &port,
551 &portnum, &path) == -1)
552 goto cleanup_fetch_url;
554 if (urltype == FILE_URL_T && ! EMPTYSTRING(host)
555 && strcasecmp(host, "localhost") != 0) {
556 warnx("No support for non local file URL `%s'", url);
557 goto cleanup_fetch_url;
560 if (EMPTYSTRING(path)) {
561 if (urltype == FTP_URL_T) {
562 rval = fetch_ftp(url);
563 goto cleanup_fetch_url;
565 if (!IS_HTTP_TYPE(urltype) || outfile == NULL) {
566 warnx("Invalid URL (no file after host) `%s'", url);
567 goto cleanup_fetch_url;
571 decodedpath = ftp_strdup(path);
572 url_decode(decodedpath);
577 cp = strrchr(decodedpath, '/'); /* find savefile */
579 savefile = ftp_strdup(cp + 1);
581 savefile = ftp_strdup(decodedpath);
583 DPRINTF("%s: savefile `%s'\n", __func__, savefile);
584 if (EMPTYSTRING(savefile)) {
585 if (urltype == FTP_URL_T) {
586 rval = fetch_ftp(url);
587 goto cleanup_fetch_url;
589 warnx("No file after directory (you must specify an "
590 "output file) `%s'", url);
591 goto cleanup_fetch_url;
596 rangestart = rangeend = entitylen = -1;
598 if (restartautofetch) {
599 if (stat(savefile, &sb) == 0)
600 restart_point = sb.st_size;
602 if (urltype == FILE_URL_T) { /* file:// URLs */
603 direction = "copied";
604 fin = fetch_open(decodedpath, "r");
606 warn("Can't open `%s'", decodedpath);
607 goto cleanup_fetch_url;
609 if (fstat(fetch_fileno(fin), &sb) == 0) {
611 filesize = sb.st_size;
614 if (lseek(fetch_fileno(fin), restart_point, SEEK_SET) < 0) {
615 warn("Can't seek to restart `%s'",
617 goto cleanup_fetch_url;
621 fprintf(ttyout, "Copying %s", decodedpath);
623 fprintf(ttyout, " (restarting at " LLF ")",
627 if (0 == rcvbuf_size) {
628 rcvbuf_size = 8 * 1024; /* XXX */
630 } else { /* ftp:// or http:// URLs */
636 if (urltype == HTTPS_URL_T)
637 penv = getoptionvalue("https_proxy");
639 if (penv == NULL && IS_HTTP_TYPE(urltype))
640 penv = getoptionvalue("http_proxy");
641 else if (urltype == FTP_URL_T)
642 penv = getoptionvalue("ftp_proxy");
644 direction = "retrieved";
645 if (! EMPTYSTRING(penv)) { /* use proxy */
648 char *pport, *no_proxy;
653 /* check URL against list of no_proxied sites */
654 no_proxy = getoptionvalue("no_proxy");
655 if (! EMPTYSTRING(no_proxy)) {
656 char *np, *np_copy, *np_iter;
657 unsigned long np_port;
660 np_iter = np_copy = ftp_strdup(no_proxy);
662 while ((cp = strsep(&np_iter, " ,")) != NULL) {
665 if ((np = strrchr(cp, ':')) != NULL) {
667 np_port = strtoul(np, &ep, 10);
668 if (*np == '\0' || *ep != '\0')
670 if (np_port != portnum)
676 if (strncasecmp(host + hlen - plen,
683 if (isproxy == 0 && urltype == FTP_URL_T) {
684 rval = fetch_ftp(url);
685 goto cleanup_fetch_url;
691 warnx("Can't restart via proxy URL `%s'",
693 goto cleanup_fetch_url;
695 if (parse_url(penv, "proxy URL", &purltype,
696 &puser, &ppass, &phost, &pport, &pportnum,
698 goto cleanup_fetch_url;
700 if ((!IS_HTTP_TYPE(purltype)
701 && purltype != FTP_URL_T) ||
702 EMPTYSTRING(phost) ||
703 (! EMPTYSTRING(ppath)
704 && strcmp(ppath, "/") != 0)) {
705 warnx("Malformed proxy URL `%s'", penv);
709 goto cleanup_fetch_url;
711 if (isipv6addr(host) &&
712 strchr(host, '%') != NULL) {
714 "Scoped address notation `%s' disallowed via web proxy",
719 goto cleanup_fetch_url;
727 path = ftp_strdup(url);
731 } /* ! EMPTYSTRING(penv) */
733 memset(&hints, 0, sizeof(hints));
735 hints.ai_family = family;
736 hints.ai_socktype = SOCK_STREAM;
737 hints.ai_protocol = 0;
738 error = getaddrinfo(host, port, &hints, &res0);
740 warnx("Can't LOOKUP `%s:%s': %s", host, port,
741 (error == EAI_SYSTEM) ? strerror(errno)
742 : gai_strerror(error));
743 goto cleanup_fetch_url;
745 if (res0->ai_canonname)
746 host = res0->ai_canonname;
752 for (res = res0; res; res = res->ai_next) {
753 char hname[NI_MAXHOST], sname[NI_MAXSERV];
756 if (getnameinfo(res->ai_addr, res->ai_addrlen,
757 hname, sizeof(hname), sname, sizeof(sname),
758 NI_NUMERICHOST | NI_NUMERICSERV) != 0) {
759 strlcpy(hname, "?", sizeof(hname));
760 strlcpy(sname, "?", sizeof(sname));
763 if (verbose && res0->ai_next) {
764 fprintf(ttyout, "Trying %s:%s ...\n",
768 s = socket(res->ai_family, SOCK_STREAM,
772 "Can't create socket for connection to "
773 "`%s:%s'", hname, sname);
777 if (ftp_connect(s, res->ai_addr, res->ai_addrlen,
778 verbose || !res->ai_next) < 0) {
785 if (urltype == HTTPS_URL_T) {
786 if ((ssl = fetch_start_ssl(s)) == NULL) {
799 warnx("Can't connect to `%s:%s'", host, port);
800 goto cleanup_fetch_url;
803 oldalrm = xsignal(SIGALRM, timeouthttp);
804 alarmtimer(quit_time ? quit_time : 60);
805 fin = fetch_fdopen(s, "r+");
806 fetch_set_ssl(fin, ssl);
809 alarmtimer(quit_time ? quit_time : 60);
811 * Construct and send the request.
814 fprintf(ttyout, "Requesting %s\n", url);
819 fprintf(ttyout, "%svia %s:%s", leading,
824 fetch_printf(fin, "GET %s HTTP/1.0\r\n", path);
826 fetch_printf(fin, "Pragma: no-cache\r\n");
828 fetch_printf(fin, "GET %s HTTP/1.1\r\n", path);
829 if (strchr(host, ':')) {
833 * strip off IPv6 scope identifier, since it is
836 h = ftp_strdup(host);
838 (p = strchr(h, '%')) != NULL) {
841 fetch_printf(fin, "Host: [%s]", h);
844 fetch_printf(fin, "Host: %s", host);
846 if ((urltype == HTTP_URL_T && portnum != HTTP_PORT) ||
847 (urltype == HTTPS_URL_T && portnum != HTTPS_PORT))
849 if (portnum != HTTP_PORT)
851 fetch_printf(fin, ":%u", portnum);
852 fetch_printf(fin, "\r\n");
853 fetch_printf(fin, "Accept: */*\r\n");
854 fetch_printf(fin, "Connection: close\r\n");
856 fputs(leading, ttyout);
857 fetch_printf(fin, "Range: bytes=" LLF "-\r\n",
859 fprintf(ttyout, "restarting at " LLF,
865 fetch_printf(fin, "Cache-Control: no-cache\r\n");
867 if ((useragent=getenv("FTPUSERAGENT")) != NULL) {
868 fetch_printf(fin, "User-Agent: %s\r\n", useragent);
870 fetch_printf(fin, "User-Agent: %s/%s\r\n",
871 FTP_PRODUCT, FTP_VERSION);
875 fprintf(ttyout, "%swith authorization",
880 fetch_printf(fin, "Authorization: %s\r\n", wwwauth);
885 "%swith proxy authorization", leading);
889 fetch_printf(fin, "Proxy-Authorization: %s\r\n", proxyauth);
891 if (verbose && hasleading)
892 fputs(")\n", ttyout);
893 fetch_printf(fin, "\r\n");
894 if (fetch_flush(fin) == EOF) {
895 warn("Writing HTTP request");
897 goto cleanup_fetch_url;
901 /* Read the response */
902 alarmtimer(quit_time ? quit_time : 60);
903 len = fetch_getline(fin, buf, sizeof(buf), &errormsg);
906 if (*errormsg == '\n')
908 warnx("Receiving HTTP reply: %s", errormsg);
909 goto cleanup_fetch_url;
911 while (len > 0 && (ISLWS(buf[len-1])))
913 DPRINTF("%s: received `%s'\n", __func__, buf);
915 /* Determine HTTP response code */
916 cp = strchr(buf, ' ');
921 hcode = strtol(cp, &ep, 10);
922 if (*ep != '\0' && !isspace((unsigned char)*ep))
924 message = ftp_strdup(cp);
926 /* Read the rest of the header. */
928 alarmtimer(quit_time ? quit_time : 60);
929 len = fetch_getline(fin, buf, sizeof(buf), &errormsg);
932 if (*errormsg == '\n')
934 warnx("Receiving HTTP reply: %s", errormsg);
935 goto cleanup_fetch_url;
937 while (len > 0 && (ISLWS(buf[len-1])))
941 DPRINTF("%s: received `%s'\n", __func__, buf);
944 * Look for some headers
949 if (match_token(&cp, "Content-Length:")) {
950 filesize = STRTOLL(cp, &ep, 10);
951 if (filesize < 0 || *ep != '\0')
953 DPRINTF("%s: parsed len as: " LLF "\n",
954 __func__, (LLT)filesize);
956 } else if (match_token(&cp, "Content-Range:")) {
957 if (! match_token(&cp, "bytes"))
963 rangestart = STRTOLL(cp, &ep, 10);
964 if (rangestart < 0 || *ep != '-')
967 rangeend = STRTOLL(cp, &ep, 10);
968 if (rangeend < 0 || rangeend < rangestart)
978 entitylen = STRTOLL(cp, &ep, 10);
988 fprintf(ttyout, "parsed range as: ");
989 if (rangestart == -1)
990 fprintf(ttyout, "*");
992 fprintf(ttyout, LLF "-" LLF,
995 fprintf(ttyout, "/" LLF "\n", (LLT)entitylen);
998 if (! restart_point) {
1000 "Received unexpected Content-Range header");
1001 goto cleanup_fetch_url;
1004 } else if (match_token(&cp, "Last-Modified:")) {
1008 memset(&parsed, 0, sizeof(parsed));
1009 t = parse_rfc2616time(&parsed, cp);
1011 parsed.tm_isdst = -1;
1013 mtime = timegm(&parsed);
1015 if (ftp_debug && mtime != -1) {
1017 "parsed time as: %s",
1018 rfc2822time(localtime(&mtime)));
1023 } else if (match_token(&cp, "Location:")) {
1024 location = ftp_strdup(cp);
1025 DPRINTF("%s: parsed location as `%s'\n",
1028 } else if (match_token(&cp, "Transfer-Encoding:")) {
1029 if (match_token(&cp, "binary")) {
1031 "Bogus transfer encoding `binary' (fetching anyway)");
1034 if (! (token = match_token(&cp, "chunked"))) {
1036 "Unsupported transfer encoding `%s'",
1038 goto cleanup_fetch_url;
1041 DPRINTF("%s: using chunked encoding\n",
1044 } else if (match_token(&cp, "Proxy-Authenticate:")
1045 || match_token(&cp, "WWW-Authenticate:")) {
1046 if (! (token = match_token(&cp, "Basic"))) {
1047 DPRINTF("%s: skipping unknown auth "
1048 "scheme `%s'\n", __func__, token);
1052 auth = ftp_strdup(token);
1053 DPRINTF("%s: parsed auth as `%s'\n",
1058 /* finished parsing header */
1064 if (! restart_point) {
1065 warnx("Not expecting partial content header");
1066 goto cleanup_fetch_url;
1075 if (EMPTYSTRING(location)) {
1077 "No redirection Location provided by server");
1078 goto cleanup_fetch_url;
1080 if (redirect_loop++ > 5) {
1081 warnx("Too many redirections requested");
1082 goto cleanup_fetch_url;
1086 fprintf(ttyout, "Redirected via %s\n",
1088 rval = fetch_url(url, location,
1089 proxyauth, wwwauth);
1092 fprintf(ttyout, "Redirected to %s\n",
1094 rval = go_fetch(location);
1096 goto cleanup_fetch_url;
1102 char *auser, *apass;
1113 if (verbose || *authp == NULL ||
1114 auser == NULL || apass == NULL)
1115 fprintf(ttyout, "%s\n", message);
1116 if (EMPTYSTRING(auth)) {
1118 "No authentication challenge provided by server");
1119 goto cleanup_fetch_url;
1121 if (*authp != NULL) {
1125 "Authorization failed. Retry (y/n)? ");
1126 if (get_line(stdin, reply, sizeof(reply), NULL)
1128 goto cleanup_fetch_url;
1130 if (tolower((unsigned char)reply[0]) != 'y')
1131 goto cleanup_fetch_url;
1135 if (auth_url(auth, authp, auser, apass) == 0) {
1136 rval = fetch_url(url, penv,
1137 proxyauth, wwwauth);
1138 memset(*authp, 0, strlen(*authp));
1141 goto cleanup_fetch_url;
1146 warnx("Error retrieving file `%s'", message);
1148 warnx("Unknown error retrieving file");
1149 goto cleanup_fetch_url;
1151 } /* end of ftp:// or http:// specific setup */
1153 /* Open the output file. */
1156 * Only trust filenames with special meaning if they came from
1159 if (outfile == savefile) {
1160 if (strcmp(savefile, "-") == 0) {
1162 } else if (*savefile == '|') {
1163 errx(1, "Piped output specifications are "
1164 "not supported by tnftp: '%s'",
1167 oldpipe = xsignal(SIGPIPE, SIG_IGN);
1168 fout = popen(savefile + 1, "w");
1170 warn("Can't execute `%s'", savefile + 1);
1171 goto cleanup_fetch_url;
1178 if ((rangeend != -1 && rangeend <= restart_point) ||
1179 (rangestart == -1 && filesize != -1 && filesize <= restart_point)) {
1182 fprintf(ttyout, "already done\n");
1184 goto cleanup_fetch_url;
1186 if (restart_point && rangestart != -1) {
1187 if (entitylen != -1)
1188 filesize = entitylen;
1189 if (rangestart != restart_point) {
1191 "Size of `%s' differs from save file `%s'",
1193 goto cleanup_fetch_url;
1195 fout = fopen(savefile, "a");
1197 fout = fopen(savefile, "w");
1199 warn("Can't open `%s'", savefile);
1200 goto cleanup_fetch_url;
1206 oldquit = xsignal(SIGQUIT, psummary);
1207 oldint = xsignal(SIGINT, aborthttp);
1209 assert(rcvbuf_size > 0);
1210 if ((size_t)rcvbuf_size > bufsize) {
1212 (void)free(xferbuf);
1213 bufsize = rcvbuf_size;
1214 xferbuf = ftp_malloc(bufsize);
1220 (void)xsignal(SIGALRM, oldalrm);
1225 /* Finally, suck down the file. */
1232 /* read chunk-size */
1234 if (fetch_getln(xferbuf, bufsize, fin) == NULL) {
1235 warnx("Unexpected EOF reading chunk-size");
1236 goto cleanup_fetch_url;
1239 chunksize = strtol(xferbuf, &ep, 16);
1240 if (ep == xferbuf) {
1241 warnx("Invalid chunk-size");
1242 goto cleanup_fetch_url;
1244 if (errno == ERANGE || chunksize < 0) {
1246 warn("Chunk-size `%.*s'",
1247 (int)(ep-xferbuf), xferbuf);
1248 goto cleanup_fetch_url;
1252 * XXX: Work around bug in Apache 1.3.9 and
1253 * 1.3.11, which incorrectly put trailing
1254 * space after the chunk-size.
1259 /* skip [ chunk-ext ] */
1261 while (*ep && *ep != '\r')
1265 if (strcmp(ep, "\r\n") != 0) {
1266 warnx("Unexpected data following chunk-size");
1267 goto cleanup_fetch_url;
1269 DPRINTF("%s: got chunk-size of " LLF "\n", __func__,
1271 if (chunksize == 0) {
1276 /* transfer file or chunk */
1278 struct timeval then, now, td;
1279 volatile off_t bufrem;
1282 (void)gettimeofday(&then, NULL);
1283 bufrem = rate_get ? rate_get : (off_t)bufsize;
1285 bufrem = MIN(chunksize, bufrem);
1286 while (bufrem > 0) {
1287 flen = fetch_read(xferbuf, sizeof(char),
1288 MIN((off_t)bufsize, bufrem), fin);
1293 if (fwrite(xferbuf, sizeof(char), flen, fout)
1295 warn("Writing `%s'", savefile);
1296 goto cleanup_fetch_url;
1298 if (hash && !progress) {
1299 while (bytes >= hashbytes) {
1300 (void)putc('#', ttyout);
1303 (void)fflush(ttyout);
1313 (void)gettimeofday(&now, NULL);
1314 timersub(&now, &then, &td);
1317 usleep(1000000 - td.tv_usec);
1320 if (ischunked && chunksize <= 0)
1323 /* read CRLF after chunk*/
1326 if (fetch_getln(xferbuf, bufsize, fin) == NULL) {
1328 warnx("Unexpected EOF reading chunk CRLF");
1329 goto cleanup_fetch_url;
1331 if (strcmp(xferbuf, "\r\n") != 0) {
1332 warnx("Unexpected data following chunk");
1333 goto cleanup_fetch_url;
1338 } while (ischunked);
1340 /* XXX: deal with optional trailer & CRLF here? */
1342 if (hash && !progress && bytes > 0) {
1344 (void)putc('#', ttyout);
1345 (void)putc('\n', ttyout);
1347 if (fetch_error(fin)) {
1348 warn("Reading file");
1349 goto cleanup_fetch_url;
1353 if (closefunc == fclose && mtime != -1) {
1354 struct timeval tval[2];
1356 (void)gettimeofday(&tval[0], NULL);
1357 tval[1].tv_sec = mtime;
1358 tval[1].tv_usec = 0;
1362 if (utimes(savefile, tval) == -1) {
1364 "Can't change modification time to %s",
1365 rfc2822time(localtime(&mtime)));
1373 goto cleanup_fetch_url;
1376 warnx("Improper response from `%s:%s'", host, port);
1380 (void)xsignal(SIGINT, oldint);
1382 (void)xsignal(SIGPIPE, oldpipe);
1384 (void)xsignal(SIGALRM, oldalrm);
1386 (void)xsignal(SIGQUIT, oldpipe);
1391 if (closefunc != NULL && fout != NULL)
1395 if (savefile != outfile)
1399 memset(pass, 0, strlen(pass));
1404 FREEPTR(decodedpath);
1407 memset(ppass, 0, strlen(ppass));
1416 * Abort a HTTP retrieval
1419 aborthttp(int notused)
1427 len = snprintf(msgbuf, sizeof(msgbuf),
1428 "\n%s: HTTP fetch aborted.\n", getprogname());
1430 write(fileno(ttyout), msgbuf, len);
1432 siglongjmp(httpabort, 1);
1436 timeouthttp(int notused)
1443 len = snprintf(msgbuf, sizeof(msgbuf),
1444 "\n%s: HTTP fetch timeout.\n", getprogname());
1446 write(fileno(ttyout), msgbuf, len);
1448 siglongjmp(httpabort, 1);
1452 * Retrieve ftp URL or classic ftp argument using FTP.
1453 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1454 * is still open (e.g, ftp xfer with trailing /)
1457 fetch_ftp(const char *url)
1459 char *cp, *xargv[5], rempath[MAXPATHLEN];
1460 char *host, *path, *dir, *file, *uuser, *pass;
1462 char cmdbuf[MAXPATHLEN];
1464 int dirhasglob, filehasglob, rval, transtype, xargc;
1465 int oanonftp, oautologin;
1469 DPRINTF("fetch_ftp: `%s'\n", url);
1470 host = path = dir = file = uuser = pass = NULL;
1475 if (STRNEQUAL(url, FTP_URL)) {
1476 if ((parse_url(url, "URL", &urltype, &uuser, &pass,
1477 &host, &port, &portnum, &path) == -1) ||
1478 (uuser != NULL && *uuser == '\0') ||
1479 EMPTYSTRING(host)) {
1480 warnx("Invalid URL `%s'", url);
1481 goto cleanup_fetch_ftp;
1484 * Note: Don't url_decode(path) here. We need to keep the
1485 * distinction between "/" and "%2F" until later.
1488 /* check for trailing ';type=[aid]' */
1489 if (! EMPTYSTRING(path) && (cp = strrchr(path, ';')) != NULL) {
1490 if (strcasecmp(cp, ";type=a") == 0)
1492 else if (strcasecmp(cp, ";type=i") == 0)
1494 else if (strcasecmp(cp, ";type=d") == 0) {
1496 "Directory listing via a URL is not supported");
1497 goto cleanup_fetch_ftp;
1499 warnx("Invalid suffix `%s' in URL `%s'", cp,
1501 goto cleanup_fetch_ftp;
1505 } else { /* classic style `[user@]host:[file]' */
1506 urltype = CLASSIC_URL_T;
1507 host = ftp_strdup(url);
1508 cp = strchr(host, '@');
1512 anonftp = 0; /* disable anonftp */
1513 host = ftp_strdup(cp + 1);
1515 cp = strchr(host, ':');
1518 path = ftp_strdup(cp + 1);
1521 if (EMPTYSTRING(host))
1522 goto cleanup_fetch_ftp;
1524 /* Extract the file and (if present) directory name. */
1526 if (! EMPTYSTRING(dir)) {
1528 * If we are dealing with classic `[user@]host:[path]' syntax,
1529 * then a path of the form `/file' (resulting from input of the
1530 * form `host:/file') means that we should do "CWD /" before
1531 * retrieving the file. So we set dir="/" and file="file".
1533 * But if we are dealing with URLs like `ftp://host/path' then
1534 * a path of the form `/file' (resulting from a URL of the form
1535 * `ftp://host//file') means that we should do `CWD ' (with an
1536 * empty argument) before retrieving the file. So we set
1537 * dir="" and file="file".
1539 * If the path does not contain / at all, we set dir=NULL.
1540 * (We get a path without any slashes if we are dealing with
1541 * classic `[user@]host:[file]' or URL `ftp://host/file'.)
1543 * In all other cases, we set dir to a string that does not
1544 * include the final '/' that separates the dir part from the
1545 * file part of the path. (This will be the empty string if
1546 * and only if we are dealing with a path of the form `/file'
1547 * resulting from an URL of the form `ftp://host//file'.)
1549 cp = strrchr(dir, '/');
1550 if (cp == dir && urltype == CLASSIC_URL_T) {
1552 (void)strlcpy(dirbuf, "/", sizeof(dirbuf));
1554 } else if (cp != NULL) {
1563 if (urltype == FTP_URL_T && file != NULL) {
1565 /* but still don't url_decode(dir) */
1567 DPRINTF("fetch_ftp: user `%s' pass `%s' host %s port %s "
1568 "path `%s' dir `%s' file `%s'\n",
1569 STRorNULL(uuser), STRorNULL(pass),
1570 STRorNULL(host), STRorNULL(port),
1571 STRorNULL(path), STRorNULL(dir), STRorNULL(file));
1573 dirhasglob = filehasglob = 0;
1574 if (doglob && urltype == CLASSIC_URL_T) {
1575 if (! EMPTYSTRING(dir) && strpbrk(dir, "*?[]{}") != NULL)
1577 if (! EMPTYSTRING(file) && strpbrk(file, "*?[]{}") != NULL)
1581 /* Set up the connection */
1584 disconnect(0, NULL);
1586 (void)strlcpy(cmdbuf, getprogname(), sizeof(cmdbuf));
1596 oautologin = autologin;
1597 /* don't autologin in setpeer(), use ftp_login() below */
1599 setpeer(xargc, xargv);
1600 autologin = oautologin;
1601 if ((connected == 0) ||
1602 (connected == 1 && !ftp_login(host, uuser, pass))) {
1603 warnx("Can't connect or login to host `%s:%s'",
1604 host, port ? port : "?");
1605 goto cleanup_fetch_ftp;
1608 switch (transtype) {
1613 setbinary(1, xargv);
1616 errx(1, "fetch_ftp: unknown transfer type %d", transtype);
1620 * Change directories, if necessary.
1622 * Note: don't use EMPTYSTRING(dir) below, because
1623 * dir=="" means something different from dir==NULL.
1625 if (dir != NULL && !dirhasglob) {
1629 * If we are dealing with a classic `[user@]host:[path]'
1630 * (urltype is CLASSIC_URL_T) then we have a raw directory
1631 * name (not encoded in any way) and we can change
1632 * directories in one step.
1634 * If we are dealing with an `ftp://host/path' URL
1635 * (urltype is FTP_URL_T), then RFC 3986 says we need to
1636 * send a separate CWD command for each unescaped "/"
1637 * in the path, and we have to interpret %hex escaping
1638 * *after* we find the slashes. It's possible to get
1639 * empty components here, (from multiple adjacent
1640 * slashes in the path) and RFC 3986 says that we should
1641 * still do `CWD ' (with a null argument) in such cases.
1643 * Many ftp servers don't support `CWD ', so if there's an
1644 * error performing that command, bail out with a descriptive
1649 * host: dir="", urltype=CLASSIC_URL_T
1650 * logged in (to default directory)
1651 * host:file dir=NULL, urltype=CLASSIC_URL_T
1653 * host:dir/ dir="dir", urltype=CLASSIC_URL_T
1654 * "CWD dir", logged in
1655 * ftp://host/ dir="", urltype=FTP_URL_T
1656 * logged in (to default directory)
1657 * ftp://host/dir/ dir="dir", urltype=FTP_URL_T
1658 * "CWD dir", logged in
1659 * ftp://host/file dir=NULL, urltype=FTP_URL_T
1661 * ftp://host//file dir="", urltype=FTP_URL_T
1662 * "CWD ", "RETR file"
1663 * host:/file dir="/", urltype=CLASSIC_URL_T
1664 * "CWD /", "RETR file"
1665 * ftp://host///file dir="/", urltype=FTP_URL_T
1666 * "CWD ", "CWD ", "RETR file"
1667 * ftp://host/%2F/file dir="%2F", urltype=FTP_URL_T
1668 * "CWD /", "RETR file"
1669 * ftp://host/foo/file dir="foo", urltype=FTP_URL_T
1670 * "CWD foo", "RETR file"
1671 * ftp://host/foo/bar/file dir="foo/bar"
1672 * "CWD foo", "CWD bar", "RETR file"
1673 * ftp://host//foo/bar/file dir="/foo/bar"
1674 * "CWD ", "CWD foo", "CWD bar", "RETR file"
1675 * ftp://host/foo//bar/file dir="foo//bar"
1676 * "CWD foo", "CWD ", "CWD bar", "RETR file"
1677 * ftp://host/%2F/foo/bar/file dir="%2F/foo/bar"
1678 * "CWD /", "CWD foo", "CWD bar", "RETR file"
1679 * ftp://host/%2Ffoo/bar/file dir="%2Ffoo/bar"
1680 * "CWD /foo", "CWD bar", "RETR file"
1681 * ftp://host/%2Ffoo%2Fbar/file dir="%2Ffoo%2Fbar"
1682 * "CWD /foo/bar", "RETR file"
1683 * ftp://host/%2Ffoo%2Fbar%2Ffile dir=NULL
1684 * "RETR /foo/bar/file"
1686 * Note that we don't need `dir' after this point.
1689 if (urltype == FTP_URL_T) {
1690 nextpart = strchr(dir, '/');
1698 DPRINTF("fetch_ftp: dir `%s', nextpart `%s'\n",
1699 STRorNULL(dir), STRorNULL(nextpart));
1700 if (urltype == FTP_URL_T || *dir != '\0') {
1701 (void)strlcpy(cmdbuf, "cd", sizeof(cmdbuf));
1708 if (*dir == '\0' && code == 500)
1711 "ftp: The `CWD ' command (without a directory), which is required by\n"
1712 " RFC 3986 to support the empty directory in the URL pathname (`//'),\n"
1713 " conflicts with the server's conformance to RFC 959.\n"
1714 " Try the same URL without the `//' in the URL pathname.\n"
1716 goto cleanup_fetch_ftp;
1720 } while (dir != NULL);
1723 if (EMPTYSTRING(file)) {
1725 goto cleanup_fetch_ftp;
1729 (void)strlcpy(rempath, dir, sizeof(rempath));
1730 (void)strlcat(rempath, "/", sizeof(rempath));
1731 (void)strlcat(rempath, file, sizeof(rempath));
1735 /* Fetch the file(s). */
1737 (void)strlcpy(cmdbuf, "get", sizeof(cmdbuf));
1741 if (dirhasglob || filehasglob) {
1744 ointeractive = interactive;
1746 if (restartautofetch)
1747 (void)strlcpy(cmdbuf, "mreget", sizeof(cmdbuf));
1749 (void)strlcpy(cmdbuf, "mget", sizeof(cmdbuf));
1752 interactive = ointeractive;
1754 if (outfile == NULL) {
1755 cp = strrchr(file, '/'); /* find savefile */
1761 xargv[2] = (char *)outfile;
1764 if (restartautofetch)
1765 reget(xargc, xargv);
1770 if ((code / 100) == COMPLETE)
1779 memset(pass, 0, strlen(pass));
1785 * Retrieve the given file to outfile.
1786 * Supports arguments of the form:
1787 * "host:path", "ftp://host/path" if $ftpproxy, call fetch_url() else
1789 * "http://host/path" call fetch_url() to use HTTP
1790 * "file:///path" call fetch_url() to copy
1791 * "about:..." print a message
1793 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1794 * is still open (e.g, ftp xfer with trailing /)
1797 go_fetch(const char *url)
1806 if (STRNEQUAL(url, ABOUT_URL)) {
1807 url += sizeof(ABOUT_URL) -1;
1808 if (strcasecmp(url, "ftp") == 0 ||
1809 strcasecmp(url, "tnftp") == 0) {
1811 "This version of ftp has been enhanced by Luke Mewburn <lukem@NetBSD.org>\n"
1812 "for the NetBSD project. Execute `man ftp' for more details.\n", ttyout);
1813 } else if (strcasecmp(url, "lukem") == 0) {
1815 "Luke Mewburn is the author of most of the enhancements in this ftp client.\n"
1816 "Please email feedback to <lukem@NetBSD.org>.\n", ttyout);
1817 } else if (strcasecmp(url, "netbsd") == 0) {
1819 "NetBSD is a freely available and redistributable UNIX-like operating system.\n"
1820 "For more information, see http://www.NetBSD.org/\n", ttyout);
1821 } else if (strcasecmp(url, "version") == 0) {
1822 fprintf(ttyout, "Version: %s %s%s\n",
1823 FTP_PRODUCT, FTP_VERSION,
1831 fprintf(ttyout, "`%s' is an interesting topic.\n", url);
1833 fputs("\n", ttyout);
1839 * Check for file:// and http:// URLs.
1841 if (STRNEQUAL(url, HTTP_URL)
1843 || STRNEQUAL(url, HTTPS_URL)
1845 || STRNEQUAL(url, FILE_URL))
1846 return (fetch_url(url, NULL, NULL, NULL));
1849 * If it contains "://" but does not begin with ftp://
1850 * or something that was already handled, then it's
1853 * If it contains ":" but not "://" then we assume the
1854 * part before the colon is a host name, not an URL scheme,
1855 * so we don't try to match that here.
1857 if ((p = strstr(url, "://")) != NULL && ! STRNEQUAL(url, FTP_URL))
1858 errx(1, "Unsupported URL scheme `%.*s'", (int)(p - url), url);
1861 * Try FTP URL-style and host:file arguments next.
1862 * If ftpproxy is set with an FTP URL, use fetch_url()
1863 * Othewise, use fetch_ftp().
1865 proxyenv = getoptionvalue("ftp_proxy");
1866 if (!EMPTYSTRING(proxyenv) && STRNEQUAL(url, FTP_URL))
1867 return (fetch_url(url, NULL, NULL, NULL));
1869 return (fetch_ftp(url));
1873 * Retrieve multiple files from the command line,
1874 * calling go_fetch() for each file.
1876 * If an ftp path has a trailing "/", the path will be cd-ed into and
1877 * the connection remains open, and the function will return -1
1878 * (to indicate the connection is alive).
1879 * If an error occurs the return value will be the offset+1 in
1880 * argv[] of the file that caused a problem (i.e, argv[x]
1882 * Otherwise, 0 is returned if all files retrieved successfully.
1885 auto_fetch(int argc, char *argv[])
1887 volatile int argpos, rval;
1891 if (sigsetjmp(toplevel, 1)) {
1893 disconnect(0, NULL);
1898 (void)xsignal(SIGINT, intr);
1899 (void)xsignal(SIGPIPE, lostpeer);
1902 * Loop through as long as there's files to fetch.
1904 for (; (rval == 0) && (argpos < argc); argpos++) {
1905 if (strchr(argv[argpos], ':') == NULL)
1909 anonftp = 2; /* Handle "automatic" transfers. */
1910 rval = go_fetch(argv[argpos]);
1911 if (outfile != NULL && strcmp(outfile, "-") != 0
1912 && outfile[0] != '|')
1918 if (connected && rval != -1)
1919 disconnect(0, NULL);
1925 * Upload multiple files from the command line.
1927 * If an error occurs the return value will be the offset+1 in
1928 * argv[] of the file that caused a problem (i.e, argv[x]
1930 * Otherwise, 0 is returned if all files uploaded successfully.
1933 auto_put(int argc, char **argv, const char *uploadserver)
1935 char *uargv[4], *path, *pathsep;
1936 int uargc, rval, argpos;
1938 char cmdbuf[MAX_C_NAME];
1940 (void)strlcpy(cmdbuf, "mput", sizeof(cmdbuf));
1944 uargv[2] = uargv[3] = NULL;
1948 DPRINTF("auto_put: target `%s'\n", uploadserver);
1950 path = ftp_strdup(uploadserver);
1952 if (path[len - 1] != '/' && path[len - 1] != ':') {
1954 * make sure we always pass a directory to auto_fetch
1956 if (argc > 1) { /* more than one file to upload */
1957 len = strlen(uploadserver) + 2; /* path + "/" + "\0" */
1959 path = (char *)ftp_malloc(len);
1960 (void)strlcpy(path, uploadserver, len);
1961 (void)strlcat(path, "/", len);
1962 } else { /* single file to upload */
1963 (void)strlcpy(cmdbuf, "put", sizeof(cmdbuf));
1965 pathsep = strrchr(path, '/');
1966 if (pathsep == NULL) {
1967 pathsep = strrchr(path, ':');
1968 if (pathsep == NULL) {
1969 warnx("Invalid URL `%s'", path);
1970 goto cleanup_auto_put;
1973 uargv[2] = ftp_strdup(pathsep);
1976 uargv[2] = ftp_strdup(pathsep + 1);
1981 DPRINTF("auto_put: URL `%s' argv[2] `%s'\n",
1982 path, STRorNULL(uargv[2]));
1984 /* connect and cwd */
1985 rval = auto_fetch(1, &path);
1987 goto cleanup_auto_put;
1991 /* target filename provided; upload 1 file */
1992 /* XXX : is this the best way? */
1996 if ((code / 100) != COMPLETE)
1998 } else { /* otherwise a target dir: upload all files to it */
1999 for(argpos = 0; argv[argpos] != NULL; argpos++) {
2000 uargv[1] = argv[argpos];
2002 if ((code / 100) != COMPLETE) {