fetch.c revision 1.32 1 /* $NetBSD: fetch.c,v 1.32 1998/08/08 04:04:17 lukem Exp $ */
2
3 /*-
4 * Copyright (c) 1997, 1998 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Jason Thorpe and Luke Mewburn.
9 *
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
12 * are met:
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the NetBSD
21 * Foundation, Inc. and its contributors.
22 * 4. Neither the name of The NetBSD Foundation nor the names of its
23 * contributors may be used to endorse or promote products derived
24 * from this software without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
37 */
38
39 #include <sys/cdefs.h>
40 #ifndef lint
41 __RCSID("$NetBSD: fetch.c,v 1.32 1998/08/08 04:04:17 lukem Exp $");
42 #endif /* not lint */
43
44 /*
45 * FTP User Program -- Command line file retrieval
46 */
47
48 #include <sys/types.h>
49 #include <sys/param.h>
50 #include <sys/socket.h>
51 #include <sys/stat.h>
52 #include <sys/time.h>
53
54 #include <netinet/in.h>
55
56 #include <arpa/ftp.h>
57 #include <arpa/inet.h>
58
59 #include <ctype.h>
60 #include <err.h>
61 #include <errno.h>
62 #include <netdb.h>
63 #include <fcntl.h>
64 #include <signal.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68 #include <unistd.h>
69 #include <util.h>
70
71 #include "ftp_var.h"
72
73 typedef enum {
74 UNKNOWN_URL_T=-1,
75 HTTP_URL_T,
76 FTP_URL_T,
77 FILE_URL_T
78 } url_t;
79
80 static int parse_url __P((const char *, const char *, url_t *, char **,
81 char **, char **, in_port_t *, char **));
82 static int url_get __P((const char *, const char *, const char *));
83 void aborthttp __P((int));
84
85
86 #define ABOUT_URL "about:" /* propaganda */
87 #define FILE_URL "file://" /* file URL prefix */
88 #define FTP_URL "ftp://" /* ftp URL prefix */
89 #define HTTP_URL "http://" /* http URL prefix */
90 #define FTP_PROXY "ftp_proxy" /* env var with ftp proxy location */
91 #define HTTP_PROXY "http_proxy" /* env var with http proxy location */
92 #define NO_PROXY "no_proxy" /* env var with list of non-proxied
93 * hosts, comma or space separated */
94
95
96 #define EMPTYSTRING(x) ((x) == NULL || (*(x) == '\0'))
97 #define FREEPTR(x) if ((x) != NULL) { free(x); (x) = NULL; }
98
99 /*
100 * Parse URL of form:
101 * <type>://[<user>[:<password>@]]<host>[:<port>]/<url-path>
102 * Returns -1 if a parse error occurred, otherwise 0.
103 * Sets type to url_t, each of the given char ** pointers to a
104 * malloc(3)ed strings of the relevant section, and port to
105 * 0 if not given, or the number given.
106 */
107 static int
108 parse_url(url, desc, type, user, pass, host, port, path)
109 const char *url;
110 const char *desc;
111 url_t *type;
112 char **user;
113 char **pass;
114 char **host;
115 in_port_t *port;
116 char **path;
117 {
118 char *cp, *ep, *thost;
119
120 if (url == NULL || desc == NULL || type == NULL || user == NULL
121 || pass == NULL || host == NULL || port == NULL || path == NULL)
122 errx(1, "parse_url: invoked with NULL argument!");
123
124 *type = UNKNOWN_URL_T;
125 *user = *pass = *host = *path = NULL;
126 *port = 0;
127
128 if (strncasecmp(url, HTTP_URL, sizeof(HTTP_URL) - 1) == 0) {
129 url += sizeof(HTTP_URL) - 1;
130 *type = HTTP_URL_T;
131 } else if (strncasecmp(url, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
132 url += sizeof(FTP_URL) - 1;
133 *type = FTP_URL_T;
134 } else if (strncasecmp(url, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
135 url += sizeof(FILE_URL) - 1;
136 *type = FILE_URL_T;
137 } else {
138 warnx("Invalid %s `%s'", desc, url);
139 cleanup_parse_url:
140 FREEPTR(*user);
141 FREEPTR(*pass);
142 FREEPTR(*host);
143 FREEPTR(*path);
144 return (-1);
145 }
146
147 if (*url == '\0')
148 return (0);
149
150 /* find [user[:pass]@]host[:port] */
151 ep = strchr(url, '/');
152 if (ep == NULL)
153 thost = xstrdup(url);
154 else {
155 size_t len = ep - url;
156 thost = (char *)xmalloc(len + 1);
157 strncpy(thost, url, len);
158 thost[len] = '\0';
159 *path = xstrdup(ep);
160 }
161
162 cp = strchr(thost, '@');
163 if (cp != NULL) {
164 *user = thost;
165 *cp = '\0';
166 *host = xstrdup(cp + 1);
167 cp = strchr(*user, ':');
168 if (cp != NULL) {
169 *cp = '\0';
170 *pass = xstrdup(cp + 1);
171 }
172 } else
173 *host = thost;
174
175 /* look for [:port] */
176 cp = strrchr(*host, ':');
177 if (cp != NULL) {
178 long nport;
179
180 *cp = '\0';
181 nport = strtol(cp + 1, &ep, 10);
182 if (nport < 1 || nport > MAX_IN_PORT_T || *ep != '\0') {
183 warnx("Invalid port `%s' in %s `%s'", cp, desc, line);
184 goto cleanup_parse_url;
185 }
186 *port = htons((in_port_t)nport);
187 }
188
189 if (debug)
190 fprintf(ttyout,
191 "parse_url: user `%s', pass `%s', host %s:%d, path `%s'\n",
192 *user ? *user : "", *pass ? *pass : "", *host ? *host : "",
193 ntohs(*port), *path ? *path : "");
194
195 return (0);
196 }
197
198
199 jmp_buf httpabort;
200
201 /*
202 * Retrieve URL, via the proxy in $proxyvar if necessary.
203 * Modifies the string argument given.
204 * Returns -1 on failure, 0 on success
205 */
206 static int
207 url_get(url, proxyenv, outfile)
208 const char *url;
209 const char *proxyenv;
210 const char *outfile;
211 {
212 struct sockaddr_in sin;
213 int isredirected, isproxy;
214 volatile int s;
215 size_t len;
216 char *cp, *ep;
217 char *buf, *savefile;
218 volatile sig_t oldintr, oldintp;
219 off_t hashbytes;
220 struct hostent *hp = NULL;
221 int (*closefunc) __P((FILE *));
222 FILE *fin, *fout;
223 int retval;
224 time_t mtime;
225 url_t urltype;
226 char *user, *pass, *host;
227 in_port_t port;
228 char *path;
229
230 closefunc = NULL;
231 fin = fout = NULL;
232 s = -1;
233 buf = savefile = NULL;
234 isredirected = isproxy = 0;
235 retval = -1;
236
237 #ifdef __GNUC__ /* shut up gcc warnings */
238 (void)&closefunc;
239 (void)&fin;
240 (void)&fout;
241 (void)&buf;
242 (void)&savefile;
243 (void)&retval;
244 (void)&isproxy;
245 #endif
246
247 if (parse_url(url, "URL", &urltype, &user, &pass, &host, &port, &path)
248 == -1)
249 goto cleanup_url_get;
250 if (port == 0)
251 port = httpport;
252
253 if (urltype == FILE_URL_T && ! EMPTYSTRING(host)
254 && strcasecmp(host, "localhost") != 0) {
255 warnx("No support for non local file URL `%s'", url);
256 goto cleanup_url_get;
257 }
258
259 if (EMPTYSTRING(path)) {
260 if (urltype == FTP_URL_T)
261 goto noftpautologin;
262 if (urltype != HTTP_URL_T || outfile == NULL) {
263 warnx("Invalid URL (no file after host) `%s'", url);
264 goto cleanup_url_get;
265 }
266 }
267
268 if (outfile)
269 savefile = xstrdup(outfile);
270 else {
271 cp = strrchr(path, '/'); /* find savefile */
272 if (cp != NULL)
273 savefile = xstrdup(cp + 1);
274 else
275 savefile = xstrdup(path);
276 }
277 if (EMPTYSTRING(savefile)) {
278 if (urltype == FTP_URL_T)
279 goto noftpautologin;
280 warnx("Invalid URL (no file after directory) `%s'", url);
281 goto cleanup_url_get;
282 }
283
284 filesize = -1;
285 mtime = -1;
286 if (urltype == FILE_URL_T) { /* file:// URLs */
287 struct stat sb;
288
289 direction = "copied";
290 fin = fopen(path, "r");
291 if (fin == NULL) {
292 warn("Cannot open file `%s'", path);
293 goto cleanup_url_get;
294 }
295 if (fstat(fileno(fin), &sb) == 0) {
296 mtime = sb.st_mtime;
297 filesize = sb.st_size;
298 }
299 fprintf(ttyout, "Copying %s\n", path);
300 } else { /* ftp:// or http:// URLs */
301 direction = "retrieved";
302 if (proxyenv != NULL) { /* use proxy */
303 url_t purltype;
304 char *puser, *ppass, *phost;
305 in_port_t pport;
306 char *ppath;
307 char *no_proxy;
308
309 isproxy = 1;
310
311 /* check URL against list of no_proxied sites */
312 no_proxy = getenv(NO_PROXY);
313 if (no_proxy != NULL) {
314 char *np, *np_copy;
315 long np_port;
316 size_t hlen, plen;
317
318 np_copy = xstrdup(no_proxy);
319 hlen = strlen(host);
320 while ((cp = strsep(&np_copy, " ,")) != NULL) {
321 if (*cp == '\0')
322 continue;
323 if ((np = strchr(cp, ':')) != NULL) {
324 *np = '\0';
325 np_port =
326 strtol(np + 1, &ep, 10);
327 if (*ep != '\0')
328 continue;
329 if (port !=
330 htons((in_port_t)np_port))
331 continue;
332 }
333 plen = strlen(cp);
334 if (strncasecmp(host + hlen - plen,
335 cp, plen) == 0) {
336 isproxy = 0;
337 break;
338 }
339 }
340 FREEPTR(np_copy);
341 }
342
343 if (isproxy) {
344 if (parse_url(proxyenv, "proxy URL", &purltype,
345 &puser, &ppass, &phost, &pport, &ppath)
346 == -1)
347 goto cleanup_url_get;
348
349 if ((purltype != HTTP_URL_T
350 && purltype != FTP_URL_T) ||
351 EMPTYSTRING(phost) ||
352 (! EMPTYSTRING(ppath)
353 && strcmp(ppath, "/") != 0)) {
354 warnx("Malformed proxy URL `%s'",
355 proxyenv);
356 FREEPTR(puser);
357 FREEPTR(ppass);
358 FREEPTR(phost);
359 FREEPTR(ppath);
360 goto cleanup_url_get;
361 }
362
363 FREEPTR(user);
364 user = puser;
365 FREEPTR(pass);
366 pass = ppass;
367 FREEPTR(host);
368 host = phost;
369 if (pport == 0)
370 port = httpport;
371 else
372 port = pport;
373 FREEPTR(path);
374 FREEPTR(ppath);
375 path = xstrdup(url);
376 }
377 } /* proxyenv != NULL */
378
379 memset(&sin, 0, sizeof(sin));
380 sin.sin_family = AF_INET;
381
382 if (isdigit((unsigned char)host[0])) {
383 if (inet_aton(host, &sin.sin_addr) == 0) {
384 warnx("Invalid IP address `%s'", host);
385 goto cleanup_url_get;
386 }
387 } else {
388 hp = gethostbyname(host);
389 if (hp == NULL) {
390 warnx("%s: %s", host, hstrerror(h_errno));
391 goto cleanup_url_get;
392 }
393 if (hp->h_addrtype != AF_INET) {
394 warnx("`%s': not an Internet address?", host);
395 goto cleanup_url_get;
396 }
397 memcpy(&sin.sin_addr, hp->h_addr, hp->h_length);
398 }
399
400 if (port == 0)
401 port = httpport;
402 sin.sin_port = port;
403
404 s = socket(AF_INET, SOCK_STREAM, 0);
405 if (s == -1) {
406 warn("Can't create socket");
407 goto cleanup_url_get;
408 }
409
410 while (xconnect(s, (struct sockaddr *)&sin,
411 sizeof(sin)) == -1) {
412 if (errno == EINTR)
413 continue;
414 if (hp && hp->h_addr_list[1]) {
415 int oerrno = errno;
416 char *ia;
417
418 ia = inet_ntoa(sin.sin_addr);
419 errno = oerrno;
420 warn("Connect to address `%s'", ia);
421 hp->h_addr_list++;
422 memcpy(&sin.sin_addr, hp->h_addr_list[0],
423 (size_t)hp->h_length);
424 fprintf(ttyout, "Trying %s...\n",
425 inet_ntoa(sin.sin_addr));
426 (void)close(s);
427 s = socket(AF_INET, SOCK_STREAM, 0);
428 if (s < 0) {
429 warn("Can't create socket");
430 goto cleanup_url_get;
431 }
432 continue;
433 }
434 warn("Can't connect to `%s'", host);
435 goto cleanup_url_get;
436 }
437
438 fin = fdopen(s, "r+");
439 /*
440 * Construct and send the request.
441 * Proxy requests don't want leading /.
442 */
443 if (isproxy) {
444 fprintf(ttyout, "Requesting %s\n (via %s)\n",
445 url, proxyenv);
446 fprintf(fin, "GET %s HTTP/1.0\r\n\r\n", path);
447 } else {
448 fprintf(ttyout, "Requesting %s\n", url);
449 fprintf(fin, "GET %s HTTP/1.1\r\n", path);
450 fprintf(fin, "Host: %s\r\n", host);
451 fprintf(fin, "Connection: close\r\n\r\n");
452 }
453 if (fflush(fin) == EOF) {
454 warn("Writing HTTP request");
455 goto cleanup_url_get;
456 }
457
458 /* Read the response */
459 if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0)) == NULL) {
460 warn("Receiving HTTP reply");
461 goto cleanup_url_get;
462 }
463 while (len > 0 && (buf[len-1] == '\r' || buf[len-1] == '\n'))
464 buf[--len] = '\0';
465 if (debug)
466 fprintf(ttyout, "received `%s'\n", buf);
467
468 cp = strchr(buf, ' ');
469 if (cp == NULL)
470 goto improper;
471 else
472 cp++;
473 if (strncmp(cp, "301", 3) == 0 || strncmp(cp, "302", 3) == 0) {
474 isredirected++;
475 } else if (strncmp(cp, "200", 3)) {
476 warnx("Error retrieving file `%s'", cp);
477 goto cleanup_url_get;
478 }
479
480 /* Read the rest of the header. */
481 FREEPTR(buf);
482 while (1) {
483 if ((buf = fparseln(fin, &len, NULL, "\0\0\0", 0))
484 == NULL) {
485 warn("Receiving HTTP reply");
486 goto cleanup_url_get;
487 }
488 while (len > 0 &&
489 (buf[len-1] == '\r' || buf[len-1] == '\n'))
490 buf[--len] = '\0';
491 if (len == 0)
492 break;
493 if (debug)
494 fprintf(ttyout, "received `%s'\n", buf);
495
496 /* Look for some headers */
497 cp = buf;
498 #define CONTENTLEN "Content-Length: "
499 if (strncasecmp(cp, CONTENTLEN,
500 sizeof(CONTENTLEN) - 1) == 0) {
501 cp += sizeof(CONTENTLEN) - 1;
502 filesize = strtol(cp, &ep, 10);
503 if (filesize < 1 || *ep != '\0')
504 goto improper;
505 if (debug)
506 fprintf(ttyout,
507 #ifndef NO_QUAD
508 "parsed length as: %qd\n",
509 (long long)filesize);
510 #else
511 "parsed length as: %ld\n",
512 (long)filesize);
513 #endif
514 #define LASTMOD "Last-Modified: "
515 } else if (strncasecmp(cp, LASTMOD,
516 sizeof(LASTMOD) - 1) == 0) {
517 struct tm parsed;
518 char *t;
519
520 cp += sizeof(LASTMOD) - 1;
521 /* RFC 1123 */
522 if ((t = strptime(cp,
523 "%a, %d %b %Y %H:%M:%S GMT",
524 &parsed))
525 /* RFC 850 */
526 || (t = strptime(cp,
527 "%a, %d-%b-%y %H:%M:%S GMT",
528 &parsed))
529 /* asctime */
530 || (t = strptime(cp,
531 "%a, %b %d %H:%M:%S %Y",
532 &parsed))) {
533 if (*t == '\0')
534 mtime = mktime(&parsed);
535 if (debug && mtime != -1)
536 fprintf(ttyout,
537 "parsed date as: %s",
538 ctime(&mtime));
539 }
540 #define LOCATION "Location: "
541 } else if (isredirected &&
542 strncasecmp(cp, LOCATION,
543 sizeof(LOCATION) - 1) == 0) {
544 cp += sizeof(LOCATION) - 1;
545 if (debug)
546 fprintf(ttyout,
547 "parsed location as: %s\n", cp);
548 if (verbose)
549 fprintf(ttyout,
550 "Redirected to %s\n", cp);
551 retval = url_get(cp, proxyenv, outfile);
552 goto cleanup_url_get;
553 }
554 }
555 FREEPTR(buf);
556 }
557
558 oldintr = oldintp = NULL;
559
560 /* Open the output file. */
561 if (strcmp(savefile, "-") == 0) {
562 fout = stdout;
563 } else if (*savefile == '|') {
564 oldintp = signal(SIGPIPE, SIG_IGN);
565 fout = popen(savefile + 1, "w");
566 if (fout == NULL) {
567 warn("Can't run `%s'", savefile + 1);
568 goto cleanup_url_get;
569 }
570 closefunc = pclose;
571 } else {
572 fout = fopen(savefile, "w");
573 if (fout == NULL) {
574 warn("Can't open `%s'", savefile);
575 goto cleanup_url_get;
576 }
577 closefunc = fclose;
578 }
579
580 /* Trap signals */
581 if (setjmp(httpabort)) {
582 if (oldintr)
583 (void)signal(SIGINT, oldintr);
584 if (oldintp)
585 (void)signal(SIGPIPE, oldintp);
586 goto cleanup_url_get;
587 }
588 oldintr = signal(SIGINT, aborthttp);
589
590 bytes = 0;
591 hashbytes = mark;
592 progressmeter(-1);
593
594 /* Finally, suck down the file. */
595 buf = xmalloc(BUFSIZ);
596 while ((len = fread(buf, sizeof(char), BUFSIZ, fin)) > 0) {
597 bytes += len;
598 if (fwrite(buf, sizeof(char), len, fout) != len) {
599 warn("Writing `%s'", savefile);
600 goto cleanup_url_get;
601 }
602 if (hash && !progress) {
603 while (bytes >= hashbytes) {
604 (void)putc('#', ttyout);
605 hashbytes += mark;
606 }
607 (void)fflush(ttyout);
608 }
609 }
610 if (hash && !progress && bytes > 0) {
611 if (bytes < mark)
612 (void)putc('#', ttyout);
613 (void)putc('\n', ttyout);
614 (void)fflush(ttyout);
615 }
616 if (ferror(fin)) {
617 warn("Reading file");
618 goto cleanup_url_get;
619 }
620 progressmeter(1);
621 (void)fflush(fout);
622 (void)signal(SIGINT, oldintr);
623 if (oldintp)
624 (void)signal(SIGPIPE, oldintp);
625 if (closefunc == fclose && mtime != -1) {
626 struct timeval tval[2];
627
628 (void)gettimeofday(&tval[0], NULL);
629 tval[1].tv_sec = mtime;
630 tval[1].tv_usec = 0;
631 (*closefunc)(fout);
632 fout = NULL;
633
634 if (utimes(savefile, tval) == -1) {
635 fprintf(ttyout,
636 "Can't change modification time to %s",
637 asctime(localtime(&mtime)));
638 }
639 }
640 if (bytes > 0)
641 ptransfer(0);
642
643 retval = 0;
644 goto cleanup_url_get;
645
646 noftpautologin:
647 warnx(
648 "Auto-login using ftp URLs isn't supported when using $ftp_proxy");
649 goto cleanup_url_get;
650
651 improper:
652 warnx("Improper response from `%s'", host);
653
654 cleanup_url_get:
655 resetsockbufsize();
656 if (fin != NULL)
657 fclose(fin);
658 else if (s != -1)
659 close(s);
660 if (closefunc != NULL && fout != NULL)
661 (*closefunc)(fout);
662 FREEPTR(savefile);
663 FREEPTR(user);
664 FREEPTR(pass);
665 FREEPTR(host);
666 FREEPTR(path);
667 FREEPTR(buf);
668 return (retval);
669 }
670
671 /*
672 * Abort a http retrieval
673 */
674 void
675 aborthttp(notused)
676 int notused;
677 {
678
679 alarmtimer(0);
680 fputs("\nHTTP fetch aborted.\n", ttyout);
681 (void)fflush(ttyout);
682 longjmp(httpabort, 1);
683 }
684
685 /*
686 * Retrieve multiple files from the command line, transferring
687 * URLs of the form "host:path", "ftp://host/path" using the
688 * ftp protocol, URLs of the form "http://host/path" using the
689 * http protocol, and URLs of the form "file:///" by simple
690 * copying.
691 * If path has a trailing "/", then return (-1);
692 * the path will be cd-ed into and the connection remains open,
693 * and the function will return -1 (to indicate the connection
694 * is alive).
695 * If an error occurs the return value will be the offset+1 in
696 * argv[] of the file that caused a problem (i.e, argv[x]
697 * returns x+1)
698 * Otherwise, 0 is returned if all files retrieved successfully.
699 */
700 int
701 auto_fetch(argc, argv, outfile)
702 int argc;
703 char *argv[];
704 char *outfile;
705 {
706 static char lasthost[MAXHOSTNAMELEN];
707 char portnum[6]; /* large enough for "65535\0" */
708 char *xargv[5];
709 const char *line;
710 char *cp, *host, *path, *dir, *file;
711 char *user, *pass;
712 in_port_t port;
713 char *ftpproxy, *httpproxy;
714 int rval, xargc;
715 volatile int argpos;
716 int dirhasglob, filehasglob;
717 char rempath[MAXPATHLEN];
718
719 #ifdef __GNUC__ /* to shut up gcc warnings */
720 (void)&outfile;
721 #endif
722
723 argpos = 0;
724
725 if (setjmp(toplevel)) {
726 if (connected)
727 disconnect(0, NULL);
728 return (argpos + 1);
729 }
730 (void)signal(SIGINT, (sig_t)intr);
731 (void)signal(SIGPIPE, (sig_t)lostpeer);
732
733 ftpproxy = getenv(FTP_PROXY);
734 httpproxy = getenv(HTTP_PROXY);
735 host = path = dir = file = user = pass = NULL;
736
737 /*
738 * Loop through as long as there's files to fetch.
739 */
740 for (rval = 0; (rval == 0) && (argpos < argc); argpos++) {
741 if (strchr(argv[argpos], ':') == NULL)
742 break;
743 host = path = dir = file = user = pass = NULL;
744 port = 0;
745 line = argv[argpos];
746
747 #ifndef SMALL
748 /*
749 * Check for about:*
750 */
751 if (strncasecmp(line, ABOUT_URL, sizeof(ABOUT_URL) - 1) == 0) {
752 line += sizeof(ABOUT_URL) -1;
753 if (strcasecmp(line, "ftp") == 0) {
754 fprintf(ttyout, "%s\n%s\n",
755 "This version of ftp has been enhanced by Luke Mewburn <lukem (at) netbsd.org>.",
756 "Execute 'man ftp' for more details");
757 } else if (strcasecmp(line, "netbsd") == 0) {
758 fprintf(ttyout, "%s\n%s\n",
759 "NetBSD is a freely available and redistributable UNIX-like operating system.",
760 "For more information, see http://www.netbsd.org/index.html");
761 } else {
762 fprintf(ttyout,
763 "`%s' is an interesting topic.\n", line);
764 }
765 continue;
766 }
767 #endif /* SMALL */
768
769 /*
770 * Check for file:// and http:// URLs.
771 */
772 if (strncasecmp(line, HTTP_URL, sizeof(HTTP_URL) - 1) == 0 ||
773 strncasecmp(line, FILE_URL, sizeof(FILE_URL) - 1) == 0) {
774 if (url_get(line, httpproxy, outfile) == -1)
775 rval = argpos + 1;
776 continue;
777 }
778
779 /*
780 * Try FTP URL-style arguments next. If ftpproxy is
781 * set, use url_get() instead of standard ftp.
782 * Finally, try host:file.
783 */
784 if (strncasecmp(line, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
785 int urltype;
786
787 if (ftpproxy) {
788 if (url_get(line, ftpproxy, outfile) == -1)
789 rval = argpos + 1;
790 continue;
791 }
792 if ((parse_url(line, "URL", &urltype, &user, &pass,
793 &host, &port, &path) == -1) ||
794 (user != NULL && *user == '\0') ||
795 (pass != NULL && *pass == '\0') ||
796 EMPTYSTRING(host)) {
797 warnx("Invalid URL `%s'", argv[argpos]);
798 rval = argpos + 1;
799 break;
800 }
801 } else { /* classic style `host:file' */
802 host = xstrdup(line);
803 cp = strchr(host, ':');
804 if (cp != NULL) {
805 *cp = '\0';
806 path = xstrdup(cp + 1);
807 }
808 }
809 if (EMPTYSTRING(host)) {
810 rval = argpos + 1;
811 break;
812 }
813
814 /*
815 * If dir is NULL, the file wasn't specified
816 * (URL looked something like ftp://host)
817 */
818 dir = path;
819 if (dir != NULL)
820 *dir++ = '\0';
821
822 /*
823 * Extract the file and (if present) directory name.
824 */
825 if (! EMPTYSTRING(dir)) {
826 cp = strrchr(dir, '/');
827 if (cp != NULL) {
828 *cp++ = '\0';
829 file = cp;
830 } else {
831 file = dir;
832 dir = NULL;
833 }
834 }
835 if (debug)
836 fprintf(ttyout,
837 "auto_fetch: user `%s', pass `%s', host %s:%d, path, `%s', dir `%s', file `%s'\n",
838 user ? user : "", pass ? pass : "",
839 host ? host : "", ntohs(port), path ? path : "",
840 dir ? dir : "", file ? file : "");
841
842 /*
843 * Set up the connection if we don't have one.
844 */
845 if (strcasecmp(host, lasthost) != 0) {
846 int oautologin;
847
848 (void)strcpy(lasthost, host);
849 if (connected)
850 disconnect(0, NULL);
851 xargv[0] = __progname;
852 xargv[1] = host;
853 xargv[2] = NULL;
854 xargc = 2;
855 if (port) {
856 snprintf(portnum, sizeof(portnum),
857 "%d", (int)port);
858 xargv[2] = portnum;
859 xargv[3] = NULL;
860 xargc = 3;
861 }
862 oautologin = autologin;
863 if (user != NULL)
864 autologin = 0;
865 setpeer(xargc, xargv);
866 autologin = oautologin;
867 if ((connected == 0)
868 || ((connected == 1) &&
869 !ftp_login(host, user, pass)) ) {
870 warnx("Can't connect or login to host `%s'",
871 host);
872 rval = argpos + 1;
873 break;
874 }
875
876 /* Always use binary transfers. */
877 setbinary(0, NULL);
878 }
879 /* cd back to `/' */
880 xargv[0] = "cd";
881 xargv[1] = "/";
882 xargv[2] = NULL;
883 cd(2, xargv);
884 if (! dirchange) {
885 rval = argpos + 1;
886 break;
887 }
888
889 dirhasglob = filehasglob = 0;
890 if (doglob) {
891 if (! EMPTYSTRING(dir) &&
892 strpbrk(dir, "*?[]{}") != NULL)
893 dirhasglob = 1;
894 if (! EMPTYSTRING(file) &&
895 strpbrk(file, "*?[]{}") != NULL)
896 filehasglob = 1;
897 }
898
899 /* Change directories, if necessary. */
900 if (! EMPTYSTRING(dir) && !dirhasglob) {
901 xargv[0] = "cd";
902 xargv[1] = dir;
903 xargv[2] = NULL;
904 cd(2, xargv);
905 if (! dirchange) {
906 rval = argpos + 1;
907 break;
908 }
909 }
910
911 if (EMPTYSTRING(file)) {
912 rval = -1;
913 break;
914 }
915
916 if (!verbose)
917 fprintf(ttyout, "Retrieving %s/%s\n", dir ? dir : "",
918 file);
919
920 if (dirhasglob) {
921 snprintf(rempath, sizeof(rempath), "%s/%s", dir, file);
922 file = rempath;
923 }
924
925 /* Fetch the file(s). */
926 xargc = 2;
927 xargv[0] = "get";
928 xargv[1] = file;
929 xargv[2] = NULL;
930 if (dirhasglob || filehasglob) {
931 int ointeractive;
932
933 ointeractive = interactive;
934 interactive = 0;
935 xargv[0] = "mget";
936 mget(xargc, xargv);
937 interactive = ointeractive;
938 } else {
939 if (outfile != NULL) {
940 xargv[2] = outfile;
941 xargv[3] = NULL;
942 xargc++;
943 }
944 get(xargc, xargv);
945 if (outfile != NULL && strcmp(outfile, "-") != 0
946 && outfile[0] != '|')
947 outfile = NULL;
948 }
949
950 if ((code / 100) != COMPLETE)
951 rval = argpos + 1;
952 }
953 if (connected && rval != -1)
954 disconnect(0, NULL);
955 FREEPTR(host);
956 FREEPTR(path);
957 FREEPTR(user);
958 FREEPTR(pass);
959 return (rval);
960 }
961