1 /* $NetBSD: fetch.c,v 1.175 2007/04/17 05:52:03 lukem Exp $ */
4 * Copyright (c) 1997-2007 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.
21 * 3. All advertising materials mentioning features or use of this software
22 * must display the following acknowledgement:
23 * This product includes software developed by the NetBSD
24 * Foundation, Inc. and its contributors.
25 * 4. Neither the name of The NetBSD Foundation nor the names of its
26 * contributors may be used to endorse or promote products derived
27 * from this software without specific prior written permission.
29 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
30 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
31 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
32 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
33 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
34 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
35 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
36 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
37 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
38 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
39 * POSSIBILITY OF SUCH DAMAGE.
42 #include <sys/cdefs.h>
44 __RCSID("$NetBSD: fetch.c,v 1.175 2007/04/17 05:52:03 lukem Exp $");
48 * FTP User Program -- Command line file retrieval
51 #include <sys/types.h>
52 #include <sys/param.h>
53 #include <sys/socket.h>
57 #include <netinet/in.h>
60 #include <arpa/inet.h>
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 */
112 * Determine if token is the next word in buf (case insensitive).
113 * If so, advance buf past the token and any trailing LWS, and
114 * return a pointer to the token (in buf). Otherwise, return NULL.
115 * token may be preceded by LWS.
116 * token must be followed by LWS or NUL. (I.e, don't partial match).
119 match_token(const char **buf
, const char *token
)
121 const char *p
, *orig
;
124 tlen
= strlen(token
);
128 if (strncasecmp(p
, token
, tlen
) != 0)
131 if (*p
!= '\0' && !ISLWS(*p
))
141 * Generate authorization response based on given authentication challenge.
142 * Returns -1 if an error occurred, otherwise 0.
143 * Sets response to a malloc(3)ed string; caller should free.
146 auth_url(const char *challenge
, char **response
, const char *guser
,
149 const char *cp
, *scheme
, *errormsg
;
150 char *ep
, *clear
, *realm
;
151 char user
[BUFSIZ
], *pass
;
153 size_t len
, clen
, rlen
;
156 clear
= realm
= NULL
;
159 scheme
= "Basic"; /* only support Basic authentication */
161 DPRINTF("auth_url: challenge `%s'\n", challenge
);
163 if (! match_token(&cp
, scheme
)) {
164 warnx("Unsupported authentication challenge `%s'",
166 goto cleanup_auth_url
;
169 #define REALM "realm=\""
170 if (STRNEQUAL(cp
, REALM
))
171 cp
+= sizeof(REALM
) - 1;
173 warnx("Unsupported authentication challenge `%s'",
175 goto cleanup_auth_url
;
177 /* XXX: need to improve quoted-string parsing to support \ quoting, etc. */
178 if ((ep
= strchr(cp
, '\"')) != NULL
) {
179 size_t len
= ep
- cp
;
181 realm
= (char *)ftp_malloc(len
+ 1);
182 (void)strlcpy(realm
, cp
, len
+ 1);
184 warnx("Unsupported authentication challenge `%s'",
186 goto cleanup_auth_url
;
189 fprintf(ttyout
, "Username for `%s': ", realm
);
191 (void)strlcpy(user
, guser
, sizeof(user
));
192 fprintf(ttyout
, "%s\n", user
);
194 (void)fflush(ttyout
);
195 if (getline(stdin
, user
, sizeof(user
), &errormsg
) < 0) {
196 warnx("%s; can't authenticate", errormsg
);
197 goto cleanup_auth_url
;
201 pass
= (char *)gpass
;
203 pass
= getpass("Password: ");
205 warnx("Can't read password");
206 goto cleanup_auth_url
;
210 clen
= strlen(user
) + strlen(pass
) + 2; /* user + ":" + pass + "\0" */
211 clear
= (char *)ftp_malloc(clen
);
212 (void)strlcpy(clear
, user
, clen
);
213 (void)strlcat(clear
, ":", clen
);
214 (void)strlcat(clear
, pass
, clen
);
216 memset(pass
, 0, strlen(pass
));
218 /* scheme + " " + enc + "\0" */
219 rlen
= strlen(scheme
) + 1 + (clen
+ 2) * 4 / 3 + 1;
220 *response
= (char *)ftp_malloc(rlen
);
221 (void)strlcpy(*response
, scheme
, rlen
);
222 len
= strlcat(*response
, " ", rlen
);
223 /* use `clen - 1' to not encode the trailing NUL */
224 base64_encode((unsigned char *)clear
, clen
- 1,
225 (unsigned char *)*response
+ len
);
226 memset(clear
, 0, clen
);
236 * Encode len bytes starting at clear using base64 encoding into encoded,
237 * which should be at least ((len + 2) * 4 / 3 + 1) in size.
240 base64_encode(const unsigned char *clear
, size_t len
, unsigned char *encoded
)
242 static const unsigned char enc
[] =
243 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
248 for (i
= 0; i
< len
; i
+= 3) {
249 *(cp
++) = enc
[((clear
[i
+ 0] >> 2))];
250 *(cp
++) = enc
[((clear
[i
+ 0] << 4) & 0x30)
251 | ((clear
[i
+ 1] >> 4) & 0x0f)];
252 *(cp
++) = enc
[((clear
[i
+ 1] << 2) & 0x3c)
253 | ((clear
[i
+ 2] >> 6) & 0x03)];
254 *(cp
++) = enc
[((clear
[i
+ 2] ) & 0x3f)];
263 * Decode %xx escapes in given string, `in-place'.
266 url_decode(char *url
)
268 unsigned char *p
, *q
;
270 if (EMPTYSTRING(url
))
272 p
= q
= (unsigned char *)url
;
274 #define HEXTOINT(x) (x - (isdigit(x) ? '0' : (islower(x) ? 'a' : 'A') - 10))
277 && p
[1] && isxdigit((unsigned char)p
[1])
278 && p
[2] && isxdigit((unsigned char)p
[2])) {
279 *q
++ = HEXTOINT(p
[1]) * 16 + HEXTOINT(p
[2]);
290 * <type>://[<user>[:<password>]@]<host>[:<port>][/<path>]
291 * Returns -1 if a parse error occurred, otherwise 0.
292 * It's the caller's responsibility to url_decode() the returned
293 * user, pass and path.
295 * Sets type to url_t, each of the given char ** pointers to a
296 * malloc(3)ed strings of the relevant section, and port to
297 * the number given, or ftpport if ftp://, or httpport if http://.
299 * If <host> is surrounded by `[' and ']', it's parsed as an
300 * IPv6 address (as per RFC 2732).
302 * XXX: this is not totally RFC 1738 compliant; <path> will have the
303 * leading `/' unless it's an ftp:// URL, as this makes things easier
304 * for file:// and http:// URLs. ftp:// URLs have the `/' between the
305 * host and the URL-path removed, but any additional leading slashes
306 * in the URL-path are retained (because they imply that we should
307 * later do "CWD" with a null argument).
310 * input URL output path
311 * --------- -----------
313 * "http://host/" NULL
314 * "file://host/dir/file" "dir/file"
316 * "ftp://host//" NULL
317 * "ftp://host//dir/file" "/dir/file"
320 parse_url(const char *url
, const char *desc
, url_t
*type
,
321 char **user
, char **pass
, char **host
, char **port
,
322 in_port_t
*portnum
, char **path
)
325 char *cp
, *ep
, *thost
, *tport
;
328 if (url
== NULL
|| desc
== NULL
|| type
== NULL
|| user
== NULL
329 || pass
== NULL
|| host
== NULL
|| port
== NULL
|| portnum
== NULL
331 errx(1, "parse_url: invoked with NULL argument!");
334 *type
= UNKNOWN_URL_T
;
335 *user
= *pass
= *host
= *port
= *path
= NULL
;
339 if (STRNEQUAL(url
, HTTP_URL
)) {
340 url
+= sizeof(HTTP_URL
) - 1;
342 *portnum
= HTTP_PORT
;
344 } else if (STRNEQUAL(url
, FTP_URL
)) {
345 url
+= sizeof(FTP_URL
) - 1;
349 } else if (STRNEQUAL(url
, FILE_URL
)) {
350 url
+= sizeof(FILE_URL
) - 1;
353 warnx("Invalid %s `%s'", desc
, url
);
357 memset(*pass
, 0, strlen(*pass
));
368 /* find [user[:pass]@]host[:port] */
369 ep
= strchr(url
, '/');
371 thost
= ftp_strdup(url
);
374 thost
= (char *)ftp_malloc(len
+ 1);
375 (void)strlcpy(thost
, url
, len
+ 1);
376 if (*type
== FTP_URL_T
) /* skip first / for ftp URLs */
378 *path
= ftp_strdup(ep
);
381 cp
= strchr(thost
, '@'); /* look for user[:pass]@ in URLs */
383 if (*type
== FTP_URL_T
)
384 anonftp
= 0; /* disable anonftp */
387 thost
= ftp_strdup(cp
+ 1);
388 cp
= strchr(*user
, ':');
391 *pass
= ftp_strdup(cp
+ 1);
400 * Check if thost is an encoded IPv6 address, as per
402 * `[' ipv6-address ']'
406 if ((ep
= strchr(cp
, ']')) == NULL
||
407 (ep
[1] != '\0' && ep
[1] != ':')) {
408 warnx("Invalid address `%s' in %s `%s'",
409 thost
, desc
, origurl
);
410 goto cleanup_parse_url
;
412 len
= ep
- cp
; /* change `[xyz]' -> `xyz' */
413 memmove(thost
, thost
+ 1, len
);
415 if (! isipv6addr(thost
)) {
416 warnx("Invalid IPv6 address `%s' in %s `%s'",
417 thost
, desc
, origurl
);
418 goto cleanup_parse_url
;
427 if ((cp
= strchr(thost
, ':')) != NULL
)
431 /* look for [:port] */
435 nport
= parseport(cp
, -1);
437 warnx("Unknown port `%s' in %s `%s'",
439 goto cleanup_parse_url
;
446 *port
= ftp_strdup(tport
);
448 *path
= ftp_strdup("/");
450 DPRINTF("parse_url: user `%s' pass `%s' host %s port %s(%d) "
452 *user
? *user
: "<null>", *pass
? *pass
: "<null>",
453 *host
? *host
: "<null>", *port
? *port
: "<null>",
454 *portnum
? *portnum
: -1, *path
? *path
: "<null>");
459 sigjmp_buf httpabort
;
462 * Retrieve URL, via a proxy if necessary, using HTTP.
463 * If proxyenv is set, use that for the proxy, otherwise try ftp_proxy or
464 * http_proxy as appropriate.
465 * Supports HTTP redirects.
466 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
467 * is still open (e.g, ftp xfer with trailing /)
470 fetch_url(const char *url
, const char *proxyenv
, char *proxyauth
, char *wwwauth
)
472 struct addrinfo hints
, *res
, *res0
= NULL
;
474 char hbuf
[NI_MAXHOST
];
475 sigfunc
volatile oldintr
;
476 sigfunc
volatile oldintp
;
479 int volatile ischunked
;
480 int volatile isproxy
;
484 static size_t bufsize
;
485 static char *xferbuf
;
486 const char *cp
, *token
;
489 char *volatile savefile
;
491 char *volatile location
;
492 char *volatile message
;
493 char *user
, *pass
, *host
, *port
, *path
;
494 char *volatile decodedpath
;
495 char *puser
, *ppass
, *useragent
;
496 off_t hashbytes
, rangestart
, rangeend
, entitylen
;
497 int (*volatile closefunc
)(FILE *);
504 oldintr
= oldintp
= NULL
;
508 buf
= savefile
= NULL
;
509 auth
= location
= message
= NULL
;
510 ischunked
= isproxy
= hcode
= 0;
512 user
= pass
= host
= path
= decodedpath
= puser
= ppass
= NULL
;
514 if (parse_url(url
, "URL", &urltype
, &user
, &pass
, &host
, &port
,
515 &portnum
, &path
) == -1)
516 goto cleanup_fetch_url
;
518 if (urltype
== FILE_URL_T
&& ! EMPTYSTRING(host
)
519 && strcasecmp(host
, "localhost") != 0) {
520 warnx("No support for non local file URL `%s'", url
);
521 goto cleanup_fetch_url
;
524 if (EMPTYSTRING(path
)) {
525 if (urltype
== FTP_URL_T
) {
526 rval
= fetch_ftp(url
);
527 goto cleanup_fetch_url
;
529 if (urltype
!= HTTP_URL_T
|| outfile
== NULL
) {
530 warnx("Invalid URL (no file after host) `%s'", url
);
531 goto cleanup_fetch_url
;
535 decodedpath
= ftp_strdup(path
);
536 url_decode(decodedpath
);
539 savefile
= ftp_strdup(outfile
);
541 cp
= strrchr(decodedpath
, '/'); /* find savefile */
543 savefile
= ftp_strdup(cp
+ 1);
545 savefile
= ftp_strdup(decodedpath
);
547 if (EMPTYSTRING(savefile
)) {
548 if (urltype
== FTP_URL_T
) {
549 rval
= fetch_ftp(url
);
550 goto cleanup_fetch_url
;
552 warnx("No file after directory (you must specify an "
553 "output file) `%s'", url
);
554 goto cleanup_fetch_url
;
556 DPRINTF("savefile `%s'\n", savefile
);
561 rangestart
= rangeend
= entitylen
= -1;
563 if (restartautofetch
) {
564 if (strcmp(savefile
, "-") != 0 && *savefile
!= '|' &&
565 stat(savefile
, &sb
) == 0)
566 restart_point
= sb
.st_size
;
568 if (urltype
== FILE_URL_T
) { /* file:// URLs */
569 direction
= "copied";
570 fin
= fopen(decodedpath
, "r");
572 warn("Can't open `%s'", decodedpath
);
573 goto cleanup_fetch_url
;
575 if (fstat(fileno(fin
), &sb
) == 0) {
577 filesize
= sb
.st_size
;
580 if (lseek(fileno(fin
), restart_point
, SEEK_SET
) < 0) {
581 warn("Can't seek to restart `%s'",
583 goto cleanup_fetch_url
;
587 fprintf(ttyout
, "Copying %s", decodedpath
);
589 fprintf(ttyout
, " (restarting at " LLF
")",
593 } else { /* ftp:// or http:// URLs */
597 if (proxyenv
== NULL
) {
598 if (urltype
== HTTP_URL_T
)
599 proxyenv
= getoptionvalue("http_proxy");
600 else if (urltype
== FTP_URL_T
)
601 proxyenv
= getoptionvalue("ftp_proxy");
603 direction
= "retrieved";
604 if (! EMPTYSTRING(proxyenv
)) { /* use proxy */
607 char *pport
, *no_proxy
;
611 /* check URL against list of no_proxied sites */
612 no_proxy
= getoptionvalue("no_proxy");
613 if (! EMPTYSTRING(no_proxy
)) {
614 char *np
, *np_copy
, *np_iter
;
618 np_iter
= np_copy
= ftp_strdup(no_proxy
);
620 while ((cp
= strsep(&np_iter
, " ,")) != NULL
) {
623 if ((np
= strrchr(cp
, ':')) != NULL
) {
626 strtol(np
+ 1, &ep
, 10);
629 if (np_port
!= portnum
)
635 if (strncasecmp(host
+ hlen
- plen
,
642 if (isproxy
== 0 && urltype
== FTP_URL_T
) {
643 rval
= fetch_ftp(url
);
644 goto cleanup_fetch_url
;
649 if (parse_url(proxyenv
, "proxy URL", &purltype
,
650 &puser
, &ppass
, &phost
, &pport
, &portnum
,
652 goto cleanup_fetch_url
;
654 if ((purltype
!= HTTP_URL_T
655 && purltype
!= FTP_URL_T
) ||
656 EMPTYSTRING(phost
) ||
657 (! EMPTYSTRING(ppath
)
658 && strcmp(ppath
, "/") != 0)) {
659 warnx("Malformed proxy URL `%s'",
664 goto cleanup_fetch_url
;
666 if (isipv6addr(host
) &&
667 strchr(host
, '%') != NULL
) {
669 "Scoped address notation `%s' disallowed via web proxy",
674 goto cleanup_fetch_url
;
682 path
= ftp_strdup(url
);
685 } /* ! EMPTYSTRING(proxyenv) */
687 memset(&hints
, 0, sizeof(hints
));
689 hints
.ai_family
= family
;
690 hints
.ai_socktype
= SOCK_STREAM
;
691 hints
.ai_protocol
= 0;
692 error
= getaddrinfo(host
, NULL
, &hints
, &res0
);
694 warnx("Can't lookup `%s': %s", host
,
695 (error
== EAI_SYSTEM
) ? strerror(errno
)
696 : gai_strerror(error
));
697 goto cleanup_fetch_url
;
699 if (res0
->ai_canonname
)
700 host
= res0
->ai_canonname
;
703 for (res
= res0
; res
; res
= res
->ai_next
) {
705 if (getnameinfo(res
->ai_addr
, res
->ai_addrlen
,
706 hbuf
, sizeof(hbuf
), NULL
, 0, NI_NUMERICHOST
) != 0)
707 strlcpy(hbuf
, "?", sizeof(hbuf
));
709 if (verbose
&& res0
->ai_next
) {
710 fprintf(ttyout
, "Trying %s...\n", hbuf
);
713 ((struct sockaddr_in
*)res
->ai_addr
)->sin_port
=
715 s
= socket(res
->ai_family
, SOCK_STREAM
,
719 "Can't create socket for connection to `%s'",
724 if (ftp_connect(s
, res
->ai_addr
, res
->ai_addrlen
) < 0) {
735 warnx("Can't connect to `%s'", host
);
736 goto cleanup_fetch_url
;
739 fin
= fdopen(s
, "r+");
741 * Construct and send the request.
744 fprintf(ttyout
, "Requesting %s\n", url
);
749 fprintf(ttyout
, "%svia %s:%s", leading
,
754 fprintf(fin
, "GET %s HTTP/1.0\r\n", path
);
756 fprintf(fin
, "Pragma: no-cache\r\n");
758 fprintf(fin
, "GET %s HTTP/1.1\r\n", path
);
759 if (strchr(host
, ':')) {
763 * strip off IPv6 scope identifier, since it is
766 h
= ftp_strdup(host
);
768 (p
= strchr(h
, '%')) != NULL
) {
771 fprintf(fin
, "Host: [%s]", h
);
774 fprintf(fin
, "Host: %s", host
);
775 if (portnum
!= HTTP_PORT
)
776 fprintf(fin
, ":%u", portnum
);
777 fprintf(fin
, "\r\n");
778 fprintf(fin
, "Accept: */*\r\n");
779 fprintf(fin
, "Connection: close\r\n");
781 fputs(leading
, ttyout
);
782 fprintf(fin
, "Range: bytes=" LLF
"-\r\n",
784 fprintf(ttyout
, "restarting at " LLF
,
790 fprintf(fin
, "Cache-Control: no-cache\r\n");
792 if ((useragent
=getenv("FTPUSERAGENT")) != NULL
) {
793 fprintf(fin
, "User-Agent: %s\r\n", useragent
);
795 fprintf(fin
, "User-Agent: %s/%s\r\n",
796 FTP_PRODUCT
, FTP_VERSION
);
800 fprintf(ttyout
, "%swith authorization",
805 fprintf(fin
, "Authorization: %s\r\n", wwwauth
);
810 "%swith proxy authorization", leading
);
814 fprintf(fin
, "Proxy-Authorization: %s\r\n", proxyauth
);
816 if (verbose
&& hasleading
)
817 fputs(")\n", ttyout
);
818 fprintf(fin
, "\r\n");
819 if (fflush(fin
) == EOF
) {
820 warn("Writing HTTP request");
821 goto cleanup_fetch_url
;
824 /* Read the response */
825 if ((buf
= fparseln(fin
, &len
, NULL
, "\0\0\0", 0)) == NULL
) {
826 warn("Receiving HTTP reply");
827 goto cleanup_fetch_url
;
829 while (len
> 0 && (ISLWS(buf
[len
-1])))
831 DPRINTF("received `%s'\n", buf
);
833 /* Determine HTTP response code */
834 cp
= strchr(buf
, ' ');
839 hcode
= strtol(cp
, &ep
, 10);
840 if (*ep
!= '\0' && !isspace((unsigned char)*ep
))
842 message
= ftp_strdup(cp
);
844 /* Read the rest of the header. */
847 if ((buf
= fparseln(fin
, &len
, NULL
, "\0\0\0", 0))
849 warn("Receiving HTTP reply");
850 goto cleanup_fetch_url
;
852 while (len
> 0 && (ISLWS(buf
[len
-1])))
856 DPRINTF("received `%s'\n", buf
);
859 * Look for some headers
864 if (match_token(&cp
, "Content-Length:")) {
865 filesize
= STRTOLL(cp
, &ep
, 10);
866 if (filesize
< 0 || *ep
!= '\0')
868 DPRINTF("parsed len as: " LLF
"\n",
871 } else if (match_token(&cp
, "Content-Range:")) {
872 if (! match_token(&cp
, "bytes"))
878 rangestart
= STRTOLL(cp
, &ep
, 10);
879 if (rangestart
< 0 || *ep
!= '-')
882 rangeend
= STRTOLL(cp
, &ep
, 10);
883 if (rangeend
< 0 || rangeend
< rangestart
)
893 entitylen
= STRTOLL(cp
, &ep
, 10);
903 fprintf(ttyout
, "parsed range as: ");
904 if (rangestart
== -1)
905 fprintf(ttyout
, "*");
907 fprintf(ttyout
, LLF
"-" LLF
,
910 fprintf(ttyout
, "/" LLF
"\n", (LLT
)entitylen
);
913 if (! restart_point
) {
915 "Received unexpected Content-Range header");
916 goto cleanup_fetch_url
;
919 } else if (match_token(&cp
, "Last-Modified:")) {
924 if ((t
= strptime(cp
,
925 "%a, %d %b %Y %H:%M:%S GMT",
929 "%a, %d-%b-%y %H:%M:%S GMT",
933 "%a, %b %d %H:%M:%S %Y",
935 parsed
.tm_isdst
= -1;
937 mtime
= timegm(&parsed
);
939 if (ftp_debug
&& mtime
!= -1) {
941 "parsed date as: %s",
947 } else if (match_token(&cp
, "Location:")) {
948 location
= ftp_strdup(cp
);
949 DPRINTF("parsed location as `%s'\n", cp
);
951 } else if (match_token(&cp
, "Transfer-Encoding:")) {
952 if (match_token(&cp
, "binary")) {
954 "Bogus transfer encoding `binary' (fetching anyway)");
957 if (! (token
= match_token(&cp
, "chunked"))) {
959 "Unsupported transfer encoding `%s'",
961 goto cleanup_fetch_url
;
964 DPRINTF("using chunked encoding\n");
966 } else if (match_token(&cp
, "Proxy-Authenticate:")
967 || match_token(&cp
, "WWW-Authenticate:")) {
968 if (! (token
= match_token(&cp
, "Basic"))) {
970 "skipping unknown auth scheme `%s'\n",
975 auth
= ftp_strdup(token
);
976 DPRINTF("parsed auth as `%s'\n", cp
);
980 /* finished parsing header */
987 if (! restart_point
) {
988 warnx("Not expecting partial content header");
989 goto cleanup_fetch_url
;
998 if (EMPTYSTRING(location
)) {
1000 "No redirection Location provided by server");
1001 goto cleanup_fetch_url
;
1003 if (redirect_loop
++ > 5) {
1004 warnx("Too many redirections requested");
1005 goto cleanup_fetch_url
;
1009 fprintf(ttyout
, "Redirected via %s\n",
1011 rval
= fetch_url(url
, location
,
1012 proxyauth
, wwwauth
);
1015 fprintf(ttyout
, "Redirected to %s\n",
1017 rval
= go_fetch(location
);
1019 goto cleanup_fetch_url
;
1025 char *auser
, *apass
;
1036 if (verbose
|| *authp
== NULL
||
1037 auser
== NULL
|| apass
== NULL
)
1038 fprintf(ttyout
, "%s\n", message
);
1039 if (EMPTYSTRING(auth
)) {
1041 "No authentication challenge provided by server");
1042 goto cleanup_fetch_url
;
1044 if (*authp
!= NULL
) {
1048 "Authorization failed. Retry (y/n)? ");
1049 if (getline(stdin
, reply
, sizeof(reply
), NULL
)
1051 goto cleanup_fetch_url
;
1053 if (tolower((unsigned char)reply
[0]) != 'y')
1054 goto cleanup_fetch_url
;
1058 if (auth_url(auth
, authp
, auser
, apass
) == 0) {
1059 rval
= fetch_url(url
, proxyenv
,
1060 proxyauth
, wwwauth
);
1061 memset(*authp
, 0, strlen(*authp
));
1064 goto cleanup_fetch_url
;
1069 warnx("Error retrieving file `%s'", message
);
1071 warnx("Unknown error retrieving file");
1072 goto cleanup_fetch_url
;
1074 } /* end of ftp:// or http:// specific setup */
1076 /* Open the output file. */
1077 if (strcmp(savefile
, "-") == 0) {
1079 } else if (*savefile
== '|') {
1080 oldintp
= xsignal(SIGPIPE
, SIG_IGN
);
1081 fout
= popen(savefile
+ 1, "w");
1083 warn("Can't execute `%s'", savefile
+ 1);
1084 goto cleanup_fetch_url
;
1088 if ((rangeend
!= -1 && rangeend
<= restart_point
) ||
1089 (rangestart
== -1 && filesize
!= -1 && filesize
<= restart_point
)) {
1092 fprintf(ttyout
, "already done\n");
1094 goto cleanup_fetch_url
;
1096 if (restart_point
&& rangestart
!= -1) {
1097 if (entitylen
!= -1)
1098 filesize
= entitylen
;
1099 if (rangestart
!= restart_point
) {
1101 "Size of `%s' differs from save file `%s'",
1103 goto cleanup_fetch_url
;
1105 fout
= fopen(savefile
, "a");
1107 fout
= fopen(savefile
, "w");
1109 warn("Can't open `%s'", savefile
);
1110 goto cleanup_fetch_url
;
1116 if (sigsetjmp(httpabort
, 1))
1117 goto cleanup_fetch_url
;
1118 (void)xsignal(SIGQUIT
, psummary
);
1119 oldintr
= xsignal(SIGINT
, aborthttp
);
1121 if (rcvbuf_size
> bufsize
) {
1123 (void)free(xferbuf
);
1124 bufsize
= rcvbuf_size
;
1125 xferbuf
= ftp_malloc(bufsize
);
1132 /* Finally, suck down the file. */
1137 /* read chunksize */
1139 if (fgets(xferbuf
, bufsize
, fin
) == NULL
) {
1140 warnx("Unexpected EOF reading chunksize");
1141 goto cleanup_fetch_url
;
1143 chunksize
= strtol(xferbuf
, &ep
, 16);
1146 * XXX: Work around bug in Apache 1.3.9 and
1147 * 1.3.11, which incorrectly put trailing
1148 * space after the chunksize.
1153 if (strcmp(ep
, "\r\n") != 0) {
1154 warnx("Unexpected data following chunksize");
1155 goto cleanup_fetch_url
;
1157 DPRINTF("got chunksize of " LLF
"\n", (LLT
)chunksize
);
1161 /* transfer file or chunk */
1163 struct timeval then
, now
, td
;
1167 (void)gettimeofday(&then
, NULL
);
1168 bufrem
= rate_get
? rate_get
: bufsize
;
1170 bufrem
= MIN(chunksize
, bufrem
);
1171 while (bufrem
> 0) {
1172 len
= fread(xferbuf
, sizeof(char),
1173 MIN(bufsize
, bufrem
), fin
);
1178 if (fwrite(xferbuf
, sizeof(char), len
, fout
)
1180 warn("Writing `%s'", savefile
);
1181 goto cleanup_fetch_url
;
1183 if (hash
&& !progress
) {
1184 while (bytes
>= hashbytes
) {
1185 (void)putc('#', ttyout
);
1188 (void)fflush(ttyout
);
1198 (void)gettimeofday(&now
, NULL
);
1199 timersub(&now
, &then
, &td
);
1202 usleep(1000000 - td
.tv_usec
);
1205 if (ischunked
&& chunksize
<= 0)
1208 /* read CRLF after chunk*/
1211 if (fgets(xferbuf
, bufsize
, fin
) == NULL
)
1213 if (strcmp(xferbuf
, "\r\n") != 0) {
1214 warnx("Unexpected data following chunk");
1215 goto cleanup_fetch_url
;
1218 } while (ischunked
);
1219 if (hash
&& !progress
&& bytes
> 0) {
1221 (void)putc('#', ttyout
);
1222 (void)putc('\n', ttyout
);
1225 warn("Reading file");
1226 goto cleanup_fetch_url
;
1230 if (closefunc
== fclose
&& mtime
!= -1) {
1231 struct timeval tval
[2];
1233 (void)gettimeofday(&tval
[0], NULL
);
1234 tval
[1].tv_sec
= mtime
;
1235 tval
[1].tv_usec
= 0;
1239 if (utimes(savefile
, tval
) == -1) {
1241 "Can't change modification time to %s",
1242 asctime(localtime(&mtime
)));
1250 goto cleanup_fetch_url
;
1253 warnx("Improper response from `%s'", host
);
1257 (void)xsignal(SIGINT
, oldintr
);
1259 (void)xsignal(SIGPIPE
, oldintp
);
1264 if (closefunc
!= NULL
&& fout
!= NULL
)
1271 memset(pass
, 0, strlen(pass
));
1276 FREEPTR(decodedpath
);
1279 memset(ppass
, 0, strlen(ppass
));
1289 * Abort a HTTP retrieval
1292 aborthttp(int notused
)
1299 len
= strlcpy(msgbuf
, "\nHTTP fetch aborted.\n", sizeof(msgbuf
));
1300 write(fileno(ttyout
), msgbuf
, len
);
1301 siglongjmp(httpabort
, 1);
1305 * Retrieve ftp URL or classic ftp argument using FTP.
1306 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1307 * is still open (e.g, ftp xfer with trailing /)
1310 fetch_ftp(const char *url
)
1312 char *cp
, *xargv
[5], rempath
[MAXPATHLEN
];
1313 char *host
, *path
, *dir
, *file
, *user
, *pass
;
1315 int dirhasglob
, filehasglob
, rval
, type
, xargc
;
1316 int oanonftp
, oautologin
;
1320 host
= path
= dir
= file
= user
= pass
= NULL
;
1325 if (STRNEQUAL(url
, FTP_URL
)) {
1326 if ((parse_url(url
, "URL", &urltype
, &user
, &pass
,
1327 &host
, &port
, &portnum
, &path
) == -1) ||
1328 (user
!= NULL
&& *user
== '\0') ||
1329 EMPTYSTRING(host
)) {
1330 warnx("Invalid URL `%s'", url
);
1331 goto cleanup_fetch_ftp
;
1334 * Note: Don't url_decode(path) here. We need to keep the
1335 * distinction between "/" and "%2F" until later.
1338 /* check for trailing ';type=[aid]' */
1339 if (! EMPTYSTRING(path
) && (cp
= strrchr(path
, ';')) != NULL
) {
1340 if (strcasecmp(cp
, ";type=a") == 0)
1342 else if (strcasecmp(cp
, ";type=i") == 0)
1344 else if (strcasecmp(cp
, ";type=d") == 0) {
1346 "Directory listing via a URL is not supported");
1347 goto cleanup_fetch_ftp
;
1349 warnx("Invalid suffix `%s' in URL `%s'", cp
,
1351 goto cleanup_fetch_ftp
;
1355 } else { /* classic style `[user@]host:[file]' */
1356 urltype
= CLASSIC_URL_T
;
1357 host
= ftp_strdup(url
);
1358 cp
= strchr(host
, '@');
1362 anonftp
= 0; /* disable anonftp */
1363 host
= ftp_strdup(cp
+ 1);
1365 cp
= strchr(host
, ':');
1368 path
= ftp_strdup(cp
+ 1);
1371 if (EMPTYSTRING(host
))
1372 goto cleanup_fetch_ftp
;
1374 /* Extract the file and (if present) directory name. */
1376 if (! EMPTYSTRING(dir
)) {
1378 * If we are dealing with classic `[user@]host:[path]' syntax,
1379 * then a path of the form `/file' (resulting from input of the
1380 * form `host:/file') means that we should do "CWD /" before
1381 * retrieving the file. So we set dir="/" and file="file".
1383 * But if we are dealing with URLs like `ftp://host/path' then
1384 * a path of the form `/file' (resulting from a URL of the form
1385 * `ftp://host//file') means that we should do `CWD ' (with an
1386 * empty argument) before retrieving the file. So we set
1387 * dir="" and file="file".
1389 * If the path does not contain / at all, we set dir=NULL.
1390 * (We get a path without any slashes if we are dealing with
1391 * classic `[user@]host:[file]' or URL `ftp://host/file'.)
1393 * In all other cases, we set dir to a string that does not
1394 * include the final '/' that separates the dir part from the
1395 * file part of the path. (This will be the empty string if
1396 * and only if we are dealing with a path of the form `/file'
1397 * resulting from an URL of the form `ftp://host//file'.)
1399 cp
= strrchr(dir
, '/');
1400 if (cp
== dir
&& urltype
== CLASSIC_URL_T
) {
1403 } else if (cp
!= NULL
) {
1412 if (urltype
== FTP_URL_T
&& file
!= NULL
) {
1414 /* but still don't url_decode(dir) */
1416 DPRINTF("fetch_ftp: user `%s' pass `%s' host %s port %s "
1417 "path `%s' dir `%s' file `%s'\n",
1418 user
? user
: "<null>", pass
? pass
: "<null>",
1419 host
? host
: "<null>", port
? port
: "<null>",
1420 path
? path
: "<null>",
1421 dir
? dir
: "<null>", file
? file
: "<null>");
1423 dirhasglob
= filehasglob
= 0;
1424 if (doglob
&& urltype
== CLASSIC_URL_T
) {
1425 if (! EMPTYSTRING(dir
) && strpbrk(dir
, "*?[]{}") != NULL
)
1427 if (! EMPTYSTRING(file
) && strpbrk(file
, "*?[]{}") != NULL
)
1431 /* Set up the connection */
1434 disconnect(0, NULL
);
1436 xargv
[0] = (char *)getprogname(); /* XXX discards const */
1445 oautologin
= autologin
;
1446 /* don't autologin in setpeer(), use ftp_login() below */
1448 setpeer(xargc
, xargv
);
1449 autologin
= oautologin
;
1450 if ((connected
== 0) ||
1451 (connected
== 1 && !ftp_login(host
, user
, pass
))) {
1452 warnx("Can't connect or login to host `%s'", host
);
1453 goto cleanup_fetch_ftp
;
1461 setbinary(1, xargv
);
1464 errx(1, "fetch_ftp: unknown transfer type %d", type
);
1468 * Change directories, if necessary.
1470 * Note: don't use EMPTYSTRING(dir) below, because
1471 * dir=="" means something different from dir==NULL.
1473 if (dir
!= NULL
&& !dirhasglob
) {
1477 * If we are dealing with a classic `[user@]host:[path]'
1478 * (urltype is CLASSIC_URL_T) then we have a raw directory
1479 * name (not encoded in any way) and we can change
1480 * directories in one step.
1482 * If we are dealing with an `ftp://host/path' URL
1483 * (urltype is FTP_URL_T), then RFC 1738 says we need to
1484 * send a separate CWD command for each unescaped "/"
1485 * in the path, and we have to interpret %hex escaping
1486 * *after* we find the slashes. It's possible to get
1487 * empty components here, (from multiple adjacent
1488 * slashes in the path) and RFC 1738 says that we should
1489 * still do `CWD ' (with a null argument) in such cases.
1491 * Many ftp servers don't support `CWD ', so if there's an
1492 * error performing that command, bail out with a descriptive
1497 * host: dir="", urltype=CLASSIC_URL_T
1498 * logged in (to default directory)
1499 * host:file dir=NULL, urltype=CLASSIC_URL_T
1501 * host:dir/ dir="dir", urltype=CLASSIC_URL_T
1502 * "CWD dir", logged in
1503 * ftp://host/ dir="", urltype=FTP_URL_T
1504 * logged in (to default directory)
1505 * ftp://host/dir/ dir="dir", urltype=FTP_URL_T
1506 * "CWD dir", logged in
1507 * ftp://host/file dir=NULL, urltype=FTP_URL_T
1509 * ftp://host//file dir="", urltype=FTP_URL_T
1510 * "CWD ", "RETR file"
1511 * host:/file dir="/", urltype=CLASSIC_URL_T
1512 * "CWD /", "RETR file"
1513 * ftp://host///file dir="/", urltype=FTP_URL_T
1514 * "CWD ", "CWD ", "RETR file"
1515 * ftp://host/%2F/file dir="%2F", urltype=FTP_URL_T
1516 * "CWD /", "RETR file"
1517 * ftp://host/foo/file dir="foo", urltype=FTP_URL_T
1518 * "CWD foo", "RETR file"
1519 * ftp://host/foo/bar/file dir="foo/bar"
1520 * "CWD foo", "CWD bar", "RETR file"
1521 * ftp://host//foo/bar/file dir="/foo/bar"
1522 * "CWD ", "CWD foo", "CWD bar", "RETR file"
1523 * ftp://host/foo//bar/file dir="foo//bar"
1524 * "CWD foo", "CWD ", "CWD bar", "RETR file"
1525 * ftp://host/%2F/foo/bar/file dir="%2F/foo/bar"
1526 * "CWD /", "CWD foo", "CWD bar", "RETR file"
1527 * ftp://host/%2Ffoo/bar/file dir="%2Ffoo/bar"
1528 * "CWD /foo", "CWD bar", "RETR file"
1529 * ftp://host/%2Ffoo%2Fbar/file dir="%2Ffoo%2Fbar"
1530 * "CWD /foo/bar", "RETR file"
1531 * ftp://host/%2Ffoo%2Fbar%2Ffile dir=NULL
1532 * "RETR /foo/bar/file"
1534 * Note that we don't need `dir' after this point.
1537 if (urltype
== FTP_URL_T
) {
1538 nextpart
= strchr(dir
, '/');
1546 DPRINTF("dir `%s', nextpart `%s'\n",
1547 dir
? dir
: "<null>",
1548 nextpart
? nextpart
: "<null>");
1549 if (urltype
== FTP_URL_T
|| *dir
!= '\0') {
1556 if (*dir
== '\0' && code
== 500)
1559 "ftp: The `CWD ' command (without a directory), which is required by\n"
1560 " RFC 1738 to support the empty directory in the URL pathname (`//'),\n"
1561 " conflicts with the server's conformance to RFC 959.\n"
1562 " Try the same URL without the `//' in the URL pathname.\n"
1564 goto cleanup_fetch_ftp
;
1568 } while (dir
!= NULL
);
1571 if (EMPTYSTRING(file
)) {
1573 goto cleanup_fetch_ftp
;
1577 (void)strlcpy(rempath
, dir
, sizeof(rempath
));
1578 (void)strlcat(rempath
, "/", sizeof(rempath
));
1579 (void)strlcat(rempath
, file
, sizeof(rempath
));
1583 /* Fetch the file(s). */
1588 if (dirhasglob
|| filehasglob
) {
1591 ointeractive
= interactive
;
1593 if (restartautofetch
)
1594 xargv
[0] = "mreget";
1598 interactive
= ointeractive
;
1600 if (outfile
== NULL
) {
1601 cp
= strrchr(file
, '/'); /* find savefile */
1607 xargv
[2] = (char *)outfile
;
1610 if (restartautofetch
)
1611 reget(xargc
, xargv
);
1616 if ((code
/ 100) == COMPLETE
)
1625 memset(pass
, 0, strlen(pass
));
1631 * Retrieve the given file to outfile.
1632 * Supports arguments of the form:
1633 * "host:path", "ftp://host/path" if $ftpproxy, call fetch_url() else
1635 * "http://host/path" call fetch_url() to use HTTP
1636 * "file:///path" call fetch_url() to copy
1637 * "about:..." print a message
1639 * Returns 1 on failure, 0 on completed xfer, -1 if ftp connection
1640 * is still open (e.g, ftp xfer with trailing /)
1643 go_fetch(const char *url
)
1651 if (STRNEQUAL(url
, ABOUT_URL
)) {
1652 url
+= sizeof(ABOUT_URL
) -1;
1653 if (strcasecmp(url
, "ftp") == 0 ||
1654 strcasecmp(url
, "tnftp") == 0) {
1656 "This version of ftp has been enhanced by Luke Mewburn <lukem@NetBSD.org>\n"
1657 "for the NetBSD project. Execute `man ftp' for more details.\n", ttyout
);
1658 } else if (strcasecmp(url
, "lukem") == 0) {
1660 "Luke Mewburn is the author of most of the enhancements in this ftp client.\n"
1661 "Please email feedback to <lukem@NetBSD.org>.\n", ttyout
);
1662 } else if (strcasecmp(url
, "netbsd") == 0) {
1664 "NetBSD is a freely available and redistributable UNIX-like operating system.\n"
1665 "For more information, see http://www.NetBSD.org/\n", ttyout
);
1666 } else if (strcasecmp(url
, "version") == 0) {
1667 fprintf(ttyout
, "Version: %s %s%s\n",
1668 FTP_PRODUCT
, FTP_VERSION
,
1676 fprintf(ttyout
, "`%s' is an interesting topic.\n", url
);
1678 fputs("\n", ttyout
);
1684 * Check for file:// and http:// URLs.
1686 if (STRNEQUAL(url
, HTTP_URL
) || STRNEQUAL(url
, FILE_URL
))
1687 return (fetch_url(url
, NULL
, NULL
, NULL
));
1690 * Try FTP URL-style and host:file arguments next.
1691 * If ftpproxy is set with an FTP URL, use fetch_url()
1692 * Othewise, use fetch_ftp().
1694 proxy
= getoptionvalue("ftp_proxy");
1695 if (!EMPTYSTRING(proxy
) && STRNEQUAL(url
, FTP_URL
))
1696 return (fetch_url(url
, NULL
, NULL
, NULL
));
1698 return (fetch_ftp(url
));
1702 * Retrieve multiple files from the command line,
1703 * calling go_fetch() for each file.
1705 * If an ftp path has a trailing "/", the path will be cd-ed into and
1706 * the connection remains open, and the function will return -1
1707 * (to indicate the connection is alive).
1708 * If an error occurs the return value will be the offset+1 in
1709 * argv[] of the file that caused a problem (i.e, argv[x]
1711 * Otherwise, 0 is returned if all files retrieved successfully.
1714 auto_fetch(int argc
, char *argv
[])
1716 volatile int argpos
, rval
;
1720 if (sigsetjmp(toplevel
, 1)) {
1722 disconnect(0, NULL
);
1727 (void)xsignal(SIGINT
, intr
);
1728 (void)xsignal(SIGPIPE
, lostpeer
);
1731 * Loop through as long as there's files to fetch.
1733 for (; (rval
== 0) && (argpos
< argc
); argpos
++) {
1734 if (strchr(argv
[argpos
], ':') == NULL
)
1738 anonftp
= 2; /* Handle "automatic" transfers. */
1739 rval
= go_fetch(argv
[argpos
]);
1740 if (outfile
!= NULL
&& strcmp(outfile
, "-") != 0
1741 && outfile
[0] != '|')
1747 if (connected
&& rval
!= -1)
1748 disconnect(0, NULL
);
1754 * Upload multiple files from the command line.
1756 * If an error occurs the return value will be the offset+1 in
1757 * argv[] of the file that caused a problem (i.e, argv[x]
1759 * Otherwise, 0 is returned if all files uploaded successfully.
1762 auto_put(int argc
, char **argv
, const char *uploadserver
)
1764 char *uargv
[4], *path
, *pathsep
;
1765 int uargc
, rval
, argpos
;
1769 uargv
[uargc
++] = "mput";
1770 uargv
[uargc
++] = argv
[0];
1771 uargv
[2] = uargv
[3] = NULL
;
1775 DPRINTF("auto_put: target `%s'\n", uploadserver
);
1777 path
= ftp_strdup(uploadserver
);
1779 if (path
[len
- 1] != '/' && path
[len
- 1] != ':') {
1781 * make sure we always pass a directory to auto_fetch
1783 if (argc
> 1) { /* more than one file to upload */
1784 len
= strlen(uploadserver
) + 2; /* path + "/" + "\0" */
1786 path
= (char *)ftp_malloc(len
);
1787 (void)strlcpy(path
, uploadserver
, len
);
1788 (void)strlcat(path
, "/", len
);
1789 } else { /* single file to upload */
1791 pathsep
= strrchr(path
, '/');
1792 if (pathsep
== NULL
) {
1793 pathsep
= strrchr(path
, ':');
1794 if (pathsep
== NULL
) {
1795 warnx("Invalid URL `%s'", path
);
1796 goto cleanup_auto_put
;
1799 uargv
[2] = ftp_strdup(pathsep
);
1802 uargv
[2] = ftp_strdup(pathsep
+ 1);
1807 DPRINTF("auto_put: URL `%s' argv[2] `%s'\n",
1808 path
, uargv
[2] ? uargv
[2] : "<null>");
1810 /* connect and cwd */
1811 rval
= auto_fetch(1, &path
);
1813 goto cleanup_auto_put
;
1817 /* target filename provided; upload 1 file */
1818 /* XXX : is this the best way? */
1822 if ((code
/ 100) != COMPLETE
)
1824 } else { /* otherwise a target dir: upload all files to it */
1825 for(argpos
= 0; argv
[argpos
] != NULL
; argpos
++) {
1826 uargv
[1] = argv
[argpos
];
1828 if ((code
/ 100) != COMPLETE
) {