fetch.c revision 1.12 1 /* $NetBSD: fetch.c,v 1.12 1997/07/20 09:45:50 lukem Exp $ */
2
3 /*-
4 * Copyright (c) 1997 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 REGENTS OR CONTRIBUTORS BE
30 * 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.12 1997/07/20 09:45:50 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
52 #include <netinet/in.h>
53
54 #include <arpa/ftp.h>
55 #include <arpa/inet.h>
56
57 #include <ctype.h>
58 #include <err.h>
59 #include <netdb.h>
60 #include <fcntl.h>
61 #include <signal.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <unistd.h>
66
67 #include "ftp_var.h"
68
69 static int url_get __P((const char *, const char *));
70 void aborthttp __P((int));
71
72
73 #define FTP_URL "ftp://" /* ftp URL prefix */
74 #define HTTP_URL "http://" /* http URL prefix */
75 #define FTP_PROXY "ftp_proxy" /* env var with ftp proxy location */
76 #define HTTP_PROXY "http_proxy" /* env var with http proxy location */
77
78
79 #define EMPTYSTRING(x) ((x) == NULL || (*(x) == '\0'))
80
81 jmp_buf httpabort;
82
83 /*
84 * Retrieve URL, via the proxy in $proxyvar if necessary.
85 * Modifies the string argument given.
86 * Returns -1 on failure, 0 on success
87 */
88 static int
89 url_get(origline, proxyenv)
90 const char *origline;
91 const char *proxyenv;
92 {
93 struct sockaddr_in sin;
94 int i, out, isftpurl;
95 u_int16_t port;
96 volatile int s;
97 size_t buflen, len;
98 char c, *cp, *ep, *portnum, *path, buf[4096];
99 const char *savefile;
100 char *line, *proxy, *host;
101 volatile sig_t oldintr;
102 off_t hashbytes;
103
104 s = -1;
105 proxy = NULL;
106 isftpurl = 0;
107
108 #ifdef __GNUC__ /* XXX: to shut up gcc warnings */
109 (void)&savefile;
110 (void)&proxy;
111 #endif
112
113 line = strdup(origline);
114 if (line == NULL)
115 errx(1, "Can't allocate memory to parse URL");
116 if (strncasecmp(line, HTTP_URL, sizeof(HTTP_URL) - 1) == 0)
117 host = line + sizeof(HTTP_URL) - 1;
118 else if (strncasecmp(line, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
119 host = line + sizeof(FTP_URL) - 1;
120 isftpurl = 1;
121 } else
122 errx(1, "url_get: Invalid URL '%s'", line);
123
124 path = strchr(host, '/'); /* find path */
125 if (EMPTYSTRING(path)) {
126 if (isftpurl)
127 goto noftpautologin;
128 warnx("Invalid URL (no `/' after host): %s", origline);
129 goto cleanup_url_get;
130 }
131 *path++ = '\0';
132 if (EMPTYSTRING(path)) {
133 if (isftpurl)
134 goto noftpautologin;
135 warnx("Invalid URL (no file after host): %s", origline);
136 goto cleanup_url_get;
137 }
138
139 savefile = strrchr(path, '/'); /* find savefile */
140 if (savefile != NULL)
141 savefile++;
142 else
143 savefile = path;
144 if (EMPTYSTRING(savefile)) {
145 if (isftpurl)
146 goto noftpautologin;
147 warnx("Invalid URL (no file after directory): %s", origline);
148 goto cleanup_url_get;
149 }
150
151 if (proxyenv != NULL) { /* use proxy */
152 proxy = strdup(proxyenv);
153 if (proxy == NULL)
154 errx(1, "Can't allocate memory for proxy URL.");
155 if (strncasecmp(proxy, HTTP_URL, sizeof(HTTP_URL) - 1) == 0)
156 host = proxy + sizeof(HTTP_URL) - 1;
157 else if (strncasecmp(proxy, FTP_URL, sizeof(FTP_URL) - 1) == 0)
158 host = proxy + sizeof(FTP_URL) - 1;
159 else {
160 warnx("Malformed proxy URL: %s", proxyenv);
161 goto cleanup_url_get;
162 }
163 if (EMPTYSTRING(host)) {
164 warnx("Malformed proxy URL: %s", proxyenv);
165 goto cleanup_url_get;
166 }
167 *--path = '/'; /* add / back to real path */
168 path = strchr(host, '/'); /* remove trailing / on host */
169 if (! EMPTYSTRING(path))
170 *path++ = '\0';
171 path = line;
172 }
173
174 portnum = strchr(host, ':'); /* find portnum */
175 if (portnum != NULL)
176 *portnum++ = '\0';
177
178 if (debug)
179 printf("host %s, port %s, path %s, save as %s.\n",
180 host, portnum, path, savefile);
181
182 memset(&sin, 0, sizeof(sin));
183 sin.sin_family = AF_INET;
184
185 if (isdigit(host[0])) {
186 if (inet_aton(host, &sin.sin_addr) == 0) {
187 warnx("Invalid IP address: %s", host);
188 goto cleanup_url_get;
189 }
190 } else {
191 struct hostent *hp;
192
193 hp = gethostbyname(host);
194 if (hp == NULL) {
195 warnx("%s: %s", host, hstrerror(h_errno));
196 goto cleanup_url_get;
197 }
198 if (hp->h_addrtype != AF_INET) {
199 warnx("%s: not an Internet address?", host);
200 goto cleanup_url_get;
201 }
202 memcpy(&sin.sin_addr, hp->h_addr, hp->h_length);
203 }
204
205 if (! EMPTYSTRING(portnum)) {
206 char *ep;
207 long nport;
208
209 nport = strtol(portnum, &ep, 10);
210 if (nport < 1 || nport > 0xffff || *ep != '\0') {
211 warnx("Invalid port: %s", portnum);
212 goto cleanup_url_get;
213 }
214 port = htons(nport);
215 } else
216 port = httpport;
217 sin.sin_port = port;
218
219 s = socket(AF_INET, SOCK_STREAM, 0);
220 if (s == -1) {
221 warn("Can't create socket");
222 goto cleanup_url_get;
223 }
224
225 if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) == -1) {
226 warn("Can't connect to %s", host);
227 goto cleanup_url_get;
228 }
229
230 /*
231 * Construct and send the request. We're expecting a return
232 * status of "200". Proxy requests don't want leading /.
233 */
234 if (!proxy)
235 printf("Requesting %s\n", origline);
236 else
237 printf("Requesting %s (via %s)\n", origline, proxyenv);
238 snprintf(buf, sizeof(buf), "GET %s%s HTTP/1.0\n\n",
239 proxy ? "" : "/", path);
240 buflen = strlen(buf);
241 if (write(s, buf, buflen) < buflen) {
242 warn("Writing HTTP request");
243 goto cleanup_url_get;
244 }
245 memset(buf, 0, sizeof(buf));
246 for (i = 0, buflen = sizeof(buf), cp = buf; i < buflen; cp++, i++) {
247 if (read(s, cp, 1) != 1)
248 goto improper;
249 if (*cp == '\r')
250 continue;
251 if (*cp == '\n')
252 break;
253 }
254 buf[buflen - 1] = '\0'; /* sanity */
255 cp = strchr(buf, ' ');
256 if (cp == NULL)
257 goto improper;
258 else
259 cp++;
260 if (strncmp(cp, "200", 3)) {
261 warnx("Error retrieving file: %s", cp);
262 goto cleanup_url_get;
263 }
264
265 /*
266 * Read the rest of the header.
267 */
268 memset(buf, 0, sizeof(buf));
269 c = '\0';
270 for (i = 0, buflen = sizeof(buf), cp = buf; i < buflen; cp++, i++) {
271 if (read(s, cp, 1) != 1)
272 goto improper;
273 if (*cp == '\r')
274 continue;
275 if (*cp == '\n' && c == '\n')
276 break;
277 c = *cp;
278 }
279 buf[buflen - 1] = '\0'; /* sanity */
280
281 /*
282 * Look for the "Content-length: " header.
283 */
284 #define CONTENTLEN "Content-Length: "
285 for (cp = buf; *cp != '\0'; cp++) {
286 if (tolower(*cp) == 'c' &&
287 strncasecmp(cp, CONTENTLEN, sizeof(CONTENTLEN) - 1) == 0)
288 break;
289 }
290 if (*cp == '\0')
291 goto improper;
292 cp += sizeof(CONTENTLEN) - 1;
293 ep = strchr(cp, '\n');
294 if (ep == NULL)
295 goto improper;
296 else
297 *ep = '\0';
298 filesize = strtol(cp, &ep, 10);
299 if (filesize < 1 || *ep != '\0')
300 goto improper;
301
302 /* Open the output file. */
303 out = open(savefile, O_CREAT | O_WRONLY | O_TRUNC, 0666);
304 if (out < 0) {
305 warn("Can't open %s", savefile);
306 goto cleanup_url_get;
307 }
308
309 /* Trap signals */
310 oldintr = NULL;
311 if (setjmp(httpabort)) {
312 if (oldintr)
313 (void)signal(SIGINT, oldintr);
314 goto cleanup_url_get;
315 }
316 oldintr = signal(SIGINT, aborthttp);
317
318 bytes = 0;
319 hashbytes = mark;
320 progressmeter(-1);
321
322 /* Finally, suck down the file. */
323 i = 0;
324 while ((len = read(s, buf, sizeof(buf))) > 0) {
325 bytes += len;
326 for (cp = buf; len > 0; len -= i, cp += i) {
327 if ((i = write(out, cp, len)) == -1) {
328 warn("Writing %s", savefile);
329 goto cleanup_url_get;
330 }
331 else if (i == 0)
332 break;
333 }
334 if (hash && !progress) {
335 while (bytes >= hashbytes) {
336 (void)putchar('#');
337 hashbytes += mark;
338 }
339 (void)fflush(stdout);
340 }
341 }
342 if (hash && !progress && bytes > 0) {
343 if (bytes < mark)
344 (void)putchar('#');
345 (void)putchar('\n');
346 (void)fflush(stdout);
347 }
348 if (len != 0) {
349 warn("Reading from socket");
350 goto cleanup_url_get;
351 }
352 progressmeter(1);
353 if (verbose)
354 puts("Successfully retrieved file.");
355 (void)signal(SIGINT, oldintr);
356
357 close(s);
358 close(out);
359 if (proxy)
360 free(proxy);
361 free(line);
362 return (0);
363
364 noftpautologin:
365 warnx(
366 "Auto-login using ftp URLs isn't supported when using $ftp_proxy");
367 goto cleanup_url_get;
368
369 improper:
370 warnx("Improper response from %s", host);
371
372 cleanup_url_get:
373 if (s != -1)
374 close(s);
375 if (proxy)
376 free(proxy);
377 free(line);
378 return (-1);
379 }
380
381 /*
382 * Abort a http retrieval
383 */
384 void
385 aborthttp(notused)
386 int notused;
387 {
388
389 alarmtimer(0);
390 puts("\nhttp fetch aborted.");
391 (void)fflush(stdout);
392 longjmp(httpabort, 1);
393 }
394
395 /*
396 * Retrieve multiple files from the command line, transferring
397 * files of the form "host:path", "ftp://host/path" using the
398 * ftp protocol, and files of the form "http://host/path" using
399 * the http protocol.
400 * If path has a trailing "/", then return (-1);
401 * the path will be cd-ed into and the connection remains open,
402 * and the function will return -1 (to indicate the connection
403 * is alive).
404 * If an error occurs the return value will be the offset+1 in
405 * argv[] of the file that caused a problem (i.e, argv[x]
406 * returns x+1)
407 * Otherwise, 0 is returned if all files retrieved successfully.
408 */
409 int
410 auto_fetch(argc, argv)
411 int argc;
412 char *argv[];
413 {
414 static char lasthost[MAXHOSTNAMELEN];
415 char *xargv[5];
416 char *cp, *line, *host, *dir, *file, *portnum;
417 char *user, *pass;
418 char *ftpproxy, *httpproxy;
419 int rval, xargc;
420 volatile int argpos;
421 int dirhasglob, filehasglob;
422 char rempath[MAXPATHLEN];
423
424 argpos = 0;
425
426 if (setjmp(toplevel)) {
427 if (connected)
428 disconnect(0, NULL);
429 return (argpos + 1);
430 }
431 (void)signal(SIGINT, (sig_t)intr);
432 (void)signal(SIGPIPE, (sig_t)lostpeer);
433
434 ftpproxy = getenv(FTP_PROXY);
435 httpproxy = getenv(HTTP_PROXY);
436
437 /*
438 * Loop through as long as there's files to fetch.
439 */
440 for (rval = 0; (rval == 0) && (argpos < argc); free(line), argpos++) {
441 if (strchr(argv[argpos], ':') == NULL)
442 break;
443 host = dir = file = portnum = user = pass = NULL;
444
445 /*
446 * We muck with the string, so we make a copy.
447 */
448 line = strdup(argv[argpos]);
449 if (line == NULL)
450 errx(1, "Can't allocate memory for auto-fetch.");
451
452 /*
453 * Try HTTP URL-style arguments first.
454 */
455 if (strncasecmp(line, HTTP_URL, sizeof(HTTP_URL) - 1) == 0) {
456 if (url_get(line, httpproxy) == -1)
457 rval = argpos + 1;
458 continue;
459 }
460
461 /*
462 * Try FTP URL-style arguments next. If ftpproxy is
463 * set, use url_get() instead of standard ftp.
464 * Finally, try host:file.
465 */
466 host = line;
467 if (strncasecmp(line, FTP_URL, sizeof(FTP_URL) - 1) == 0) {
468 if (ftpproxy) {
469 if (url_get(line, ftpproxy) == -1)
470 rval = argpos + 1;
471 continue;
472 }
473 host += sizeof(FTP_URL) - 1;
474 dir = strchr(host, '/');
475
476 /* look for [user:pass@]host[:port] */
477 pass = strpbrk(host, ":@/");
478 if (pass == NULL || *pass == '/') {
479 pass = NULL;
480 goto parsed_url;
481 }
482 if (pass == host || *pass == '@') {
483 bad_ftp_url:
484 warnx("Invalid URL: %s", argv[argpos]);
485 rval = argpos + 1;
486 continue;
487 }
488 *pass++ = '\0';
489 cp = strpbrk(pass, ":@/");
490 if (cp == NULL || *cp == '/') {
491 portnum = pass;
492 pass = NULL;
493 goto parsed_url;
494 }
495 if (EMPTYSTRING(cp) || *cp == ':')
496 goto bad_ftp_url;
497 *cp++ = '\0';
498 user = host;
499 if (EMPTYSTRING(user))
500 goto bad_ftp_url;
501 host = cp;
502 portnum = strchr(host, ':');
503 if (portnum != NULL)
504 *portnum++ = '\0';
505 parsed_url:
506 } else { /* classic style `host:file' */
507 dir = strchr(host, ':');
508 }
509 if (EMPTYSTRING(host)) {
510 rval = argpos + 1;
511 continue;
512 }
513
514 /*
515 * If cp is NULL, the file wasn't specified
516 * (URL looked something like ftp://host)
517 */
518 if (dir != NULL)
519 *dir++ = '\0';
520
521 /*
522 * Extract the file and (if present) directory name.
523 */
524 if (! EMPTYSTRING(dir)) {
525 cp = strrchr(dir, '/');
526 if (cp != NULL) {
527 *cp++ = '\0';
528 file = cp;
529 } else {
530 file = dir;
531 dir = NULL;
532 }
533 }
534 if (debug)
535 printf("user %s:%s host %s port %s dir %s file %s\n",
536 user, pass, host, portnum, dir, file);
537
538 /*
539 * Set up the connection if we don't have one.
540 */
541 if (strcmp(host, lasthost) != 0) {
542 int oautologin;
543
544 (void)strcpy(lasthost, host);
545 if (connected)
546 disconnect(0, NULL);
547 xargv[0] = __progname;
548 xargv[1] = host;
549 xargv[2] = NULL;
550 xargc = 2;
551 if (! EMPTYSTRING(portnum)) {
552 xargv[2] = portnum;
553 xargv[3] = NULL;
554 xargc = 3;
555 }
556 oautologin = autologin;
557 if (user != NULL)
558 autologin = 0;
559 setpeer(xargc, xargv);
560 autologin = oautologin;
561 if ((connected == 0)
562 || ((connected == 1) && !login(host, user, pass)) ) {
563 warnx("Can't connect or login to host `%s'",
564 host);
565 rval = argpos + 1;
566 continue;
567 }
568
569 /* Always use binary transfers. */
570 setbinary(0, NULL);
571 }
572 /* cd back to '/' */
573 xargv[0] = "cd";
574 xargv[1] = "/";
575 xargv[2] = NULL;
576 cd(2, xargv);
577 if (! dirchange) {
578 rval = argpos + 1;
579 continue;
580 }
581
582 dirhasglob = filehasglob = 0;
583 if (doglob) {
584 if (! EMPTYSTRING(dir) &&
585 strpbrk(dir, "*?[]{}") != NULL)
586 dirhasglob = 1;
587 if (! EMPTYSTRING(file) &&
588 strpbrk(file, "*?[]{}") != NULL)
589 filehasglob = 1;
590 }
591
592 /* Change directories, if necessary. */
593 if (! EMPTYSTRING(dir) && !dirhasglob) {
594 xargv[0] = "cd";
595 xargv[1] = dir;
596 xargv[2] = NULL;
597 cd(2, xargv);
598 if (! dirchange) {
599 rval = argpos + 1;
600 continue;
601 }
602 }
603
604 if (EMPTYSTRING(file)) {
605 rval = -1;
606 continue;
607 }
608
609 if (!verbose)
610 printf("Retrieving %s/%s\n", dir ? dir : "", file);
611
612 if (dirhasglob) {
613 snprintf(rempath, sizeof(rempath), "%s/%s", dir, file);
614 file = rempath;
615 }
616
617 /* Fetch the file(s). */
618 xargv[0] = "get";
619 xargv[1] = file;
620 xargv[2] = NULL;
621 if (dirhasglob || filehasglob) {
622 int ointeractive;
623
624 ointeractive = interactive;
625 interactive = 0;
626 xargv[0] = "mget";
627 mget(2, xargv);
628 interactive = ointeractive;
629 } else
630 get(2, xargv);
631
632 if ((code / 100) != COMPLETE)
633 rval = argpos + 1;
634 }
635 if (connected && rval != -1)
636 disconnect(0, NULL);
637 return (rval);
638 }
639