Merge branch 'vendor/CVS'
[dragonfly.git] / lib / libfetch / ftp.c
1 /*-
2  * Copyright (c) 1998-2004 Dag-Erling Coïdan Smørgrav
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer
10  *    in this position and unchanged.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
18  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
19  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
20  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
21  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
22  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
26  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27  *
28  * $FreeBSD: src/lib/libfetch/ftp.c,v 1.102 2008/02/08 09:48:48 des Exp $
29  * $DragonFly: src/lib/libfetch/ftp.c,v 1.4 2007/08/05 21:48:12 swildner Exp $
30  */
31
32 /*
33  * Portions of this code were taken from or based on ftpio.c:
34  *
35  * ----------------------------------------------------------------------------
36  * "THE BEER-WARE LICENSE" (Revision 42):
37  * <phk@FreeBSD.org> wrote this file.  As long as you retain this notice you
38  * can do whatever you want with this stuff. If we meet some day, and you think
39  * this stuff is worth it, you can buy me a beer in return.   Poul-Henning Kamp
40  * ----------------------------------------------------------------------------
41  *
42  * Major Changelog:
43  *
44  * Dag-Erling Coïdan Smørgrav
45  * 9 Jun 1998
46  *
47  * Incorporated into libfetch
48  *
49  * Jordan K. Hubbard
50  * 17 Jan 1996
51  *
52  * Turned inside out. Now returns xfers as new file ids, not as a special
53  * `state' of FTP_t
54  *
55  * $ftpioId: ftpio.c,v 1.30 1998/04/11 07:28:53 phk Exp $
56  *
57  */
58
59 #include <sys/param.h>
60 #include <sys/socket.h>
61 #include <netinet/in.h>
62
63 #include <ctype.h>
64 #include <err.h>
65 #include <errno.h>
66 #include <fcntl.h>
67 #include <netdb.h>
68 #include <stdarg.h>
69 #include <stdint.h>
70 #include <stdio.h>
71 #include <stdlib.h>
72 #include <string.h>
73 #include <time.h>
74 #include <unistd.h>
75
76 #include "fetch.h"
77 #include "common.h"
78 #include "ftperr.h"
79
80 #define FTP_ANONYMOUS_USER      "anonymous"
81
82 #define FTP_CONNECTION_ALREADY_OPEN     125
83 #define FTP_OPEN_DATA_CONNECTION        150
84 #define FTP_OK                          200
85 #define FTP_FILE_STATUS                 213
86 #define FTP_SERVICE_READY               220
87 #define FTP_TRANSFER_COMPLETE           226
88 #define FTP_PASSIVE_MODE                227
89 #define FTP_LPASSIVE_MODE               228
90 #define FTP_EPASSIVE_MODE               229
91 #define FTP_LOGGED_IN                   230
92 #define FTP_FILE_ACTION_OK              250
93 #define FTP_DIRECTORY_CREATED           257 /* multiple meanings */
94 #define FTP_FILE_CREATED                257 /* multiple meanings */
95 #define FTP_WORKING_DIRECTORY           257 /* multiple meanings */
96 #define FTP_NEED_PASSWORD               331
97 #define FTP_NEED_ACCOUNT                332
98 #define FTP_FILE_OK                     350
99 #define FTP_SYNTAX_ERROR                500
100 #define FTP_PROTOCOL_ERROR              999
101
102 static int ftp_cmd(conn_t *, const char *, ...) __printflike(2, 3);
103 static struct url cached_host;
104 static conn_t   *cached_connection;
105
106 #define isftpreply(foo)                         \
107         (isdigit((unsigned char)foo[0]) &&      \
108             isdigit((unsigned char)foo[1]) &&   \
109             isdigit((unsigned char)foo[2]) &&   \
110             (foo[3] == ' ' || foo[3] == '\0'))
111 #define isftpinfo(foo) \
112         (isdigit((unsigned char)foo[0]) &&      \
113             isdigit((unsigned char)foo[1]) &&   \
114             isdigit((unsigned char)foo[2]) &&   \
115             foo[3] == '-')
116
117 /*
118  * Translate IPv4 mapped IPv6 address to IPv4 address
119  */
120 static void
121 unmappedaddr(struct sockaddr_in6 *sin6)
122 {
123         struct sockaddr_in *sin4;
124         u_int32_t addr;
125         int port;
126
127         if (sin6->sin6_family != AF_INET6 ||
128             !IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
129                 return;
130         sin4 = (struct sockaddr_in *)sin6;
131         addr = *(u_int32_t *)&sin6->sin6_addr.s6_addr[12];
132         port = sin6->sin6_port;
133         memset(sin4, 0, sizeof(struct sockaddr_in));
134         sin4->sin_addr.s_addr = addr;
135         sin4->sin_port = port;
136         sin4->sin_family = AF_INET;
137         sin4->sin_len = sizeof(struct sockaddr_in);
138 }
139
140 /*
141  * Get server response
142  */
143 static int
144 ftp_chkerr(conn_t *conn)
145 {
146         if (fetch_getln(conn) == -1) {
147                 fetch_syserr();
148                 return (-1);
149         }
150         if (isftpinfo(conn->buf)) {
151                 while (conn->buflen && !isftpreply(conn->buf)) {
152                         if (fetch_getln(conn) == -1) {
153                                 fetch_syserr();
154                                 return (-1);
155                         }
156                 }
157         }
158
159         while (conn->buflen &&
160             isspace((unsigned char)conn->buf[conn->buflen - 1]))
161                 conn->buflen--;
162         conn->buf[conn->buflen] = '\0';
163
164         if (!isftpreply(conn->buf)) {
165                 ftp_seterr(FTP_PROTOCOL_ERROR);
166                 return (-1);
167         }
168
169         conn->err = (conn->buf[0] - '0') * 100
170             + (conn->buf[1] - '0') * 10
171             + (conn->buf[2] - '0');
172
173         return (conn->err);
174 }
175
176 /*
177  * Send a command and check reply
178  */
179 static int
180 ftp_cmd(conn_t *conn, const char *fmt, ...)
181 {
182         va_list ap;
183         size_t len;
184         char *msg;
185         int r;
186
187         va_start(ap, fmt);
188         len = vasprintf(&msg, fmt, ap);
189         va_end(ap);
190
191         if (msg == NULL) {
192                 errno = ENOMEM;
193                 fetch_syserr();
194                 return (-1);
195         }
196
197         r = fetch_putln(conn, msg, len);
198         free(msg);
199
200         if (r == -1) {
201                 fetch_syserr();
202                 return (-1);
203         }
204
205         return (ftp_chkerr(conn));
206 }
207
208 /*
209  * Return a pointer to the filename part of a path
210  */
211 static const char *
212 ftp_filename(const char *file, int *len, int *type)
213 {
214         const char *s;
215
216         if ((s = strrchr(file, '/')) == NULL)
217                 s = file;
218         else
219                 s = s + 1;
220         *len = strlen(s);
221         if (*len > 7 && strncmp(s + *len - 7, ";type=", 6) == 0) {
222                 *type = s[*len - 1];
223                 *len -= 7;
224         } else {
225                 *type = '\0';
226         }
227         return (s);
228 }
229
230 /*
231  * Get current working directory from the reply to a CWD, PWD or CDUP
232  * command.
233  */
234 static int
235 ftp_pwd(conn_t *conn, char *pwd, size_t pwdlen)
236 {
237         char *src, *dst, *end;
238         int q;
239
240         if (conn->err != FTP_WORKING_DIRECTORY &&
241             conn->err != FTP_FILE_ACTION_OK)
242                 return (FTP_PROTOCOL_ERROR);
243         end = conn->buf + conn->buflen;
244         src = conn->buf + 4;
245         if (src >= end || *src++ != '"')
246                 return (FTP_PROTOCOL_ERROR);
247         for (q = 0, dst = pwd; src < end && pwdlen--; ++src) {
248                 if (!q && *src == '"')
249                         q = 1;
250                 else if (q && *src != '"')
251                         break;
252                 else if (q)
253                         *dst++ = '"', q = 0;
254                 else
255                         *dst++ = *src;
256         }
257         if (!pwdlen)
258                 return (FTP_PROTOCOL_ERROR);
259         *dst = '\0';
260 #if 0
261         DEBUG(fprintf(stderr, "pwd: [%s]\n", pwd));
262 #endif
263         return (FTP_OK);
264 }
265
266 /*
267  * Change working directory to the directory that contains the specified
268  * file.
269  */
270 static int
271 ftp_cwd(conn_t *conn, const char *file)
272 {
273         const char *beg, *end;
274         char pwd[PATH_MAX];
275         int e, i, len;
276
277         /* If no slashes in name, no need to change dirs. */
278         if ((end = strrchr(file, '/')) == NULL)
279                 return (0);
280         if ((e = ftp_cmd(conn, "PWD")) != FTP_WORKING_DIRECTORY ||
281             (e = ftp_pwd(conn, pwd, sizeof(pwd))) != FTP_OK) {
282                 ftp_seterr(e);
283                 return (-1);
284         }
285         for (;;) {
286                 len = strlen(pwd);
287
288                 /* Look for a common prefix between PWD and dir to fetch. */
289                 for (i = 0; i <= len && i <= end - file; ++i)
290                         if (pwd[i] != file[i])
291                                 break;
292 #if 0
293                 DEBUG(fprintf(stderr, "have: [%.*s|%s]\n", i, pwd, pwd + i));
294                 DEBUG(fprintf(stderr, "want: [%.*s|%s]\n", i, file, file + i));
295 #endif
296                 /* Keep going up a dir until we have a matching prefix. */
297                 if (pwd[i] == '\0' && (file[i - 1] == '/' || file[i] == '/'))
298                         break;
299                 if ((e = ftp_cmd(conn, "CDUP")) != FTP_FILE_ACTION_OK ||
300                     (e = ftp_cmd(conn, "PWD")) != FTP_WORKING_DIRECTORY ||
301                     (e = ftp_pwd(conn, pwd, sizeof(pwd))) != FTP_OK) {
302                         ftp_seterr(e);
303                         return (-1);
304                 }
305         }
306
307 #ifdef FTP_COMBINE_CWDS
308         /* Skip leading slashes, even "////". */
309         for (beg = file + i; beg < end && *beg == '/'; ++beg, ++i)
310                 /* nothing */ ;
311
312         /* If there is no trailing dir, we're already there. */
313         if (beg >= end)
314                 return (0);
315
316         /* Change to the directory all in one chunk (e.g., foo/bar/baz). */
317         e = ftp_cmd(conn, "CWD %.*s", (int)(end - beg), beg);
318         if (e == FTP_FILE_ACTION_OK)
319                 return (0);
320 #endif /* FTP_COMBINE_CWDS */
321
322         /* That didn't work so go back to legacy behavior (multiple CWDs). */
323         for (beg = file + i; beg < end; beg = file + i + 1) {
324                 while (*beg == '/')
325                         ++beg, ++i;
326                 for (++i; file + i < end && file[i] != '/'; ++i)
327                         /* nothing */ ;
328                 e = ftp_cmd(conn, "CWD %.*s", (int)(file + i - beg), beg);
329                 if (e != FTP_FILE_ACTION_OK) {
330                         ftp_seterr(e);
331                         return (-1);
332                 }
333         }
334         return (0);
335 }
336
337 /*
338  * Set transfer mode and data type
339  */
340 static int
341 ftp_mode_type(conn_t *conn, int mode, int type)
342 {
343         int e;
344
345         switch (mode) {
346         case 0:
347         case 's':
348                 mode = 'S';
349         case 'S':
350                 break;
351         default:
352                 return (FTP_PROTOCOL_ERROR);
353         }
354         if ((e = ftp_cmd(conn, "MODE %c", mode)) != FTP_OK) {
355                 if (mode == 'S') {
356                         /*
357                          * Stream mode is supposed to be the default - so
358                          * much so that some servers not only do not
359                          * support any other mode, but do not support the
360                          * MODE command at all.
361                          *
362                          * If "MODE S" fails, it is unlikely that we
363                          * previously succeeded in setting a different
364                          * mode.  Therefore, we simply hope that the
365                          * server is already in the correct mode, and
366                          * silently ignore the failure.
367                          */
368                 } else {
369                         return (e);
370                 }
371         }
372
373         switch (type) {
374         case 0:
375         case 'i':
376                 type = 'I';
377         case 'I':
378                 break;
379         case 'a':
380                 type = 'A';
381         case 'A':
382                 break;
383         case 'd':
384                 type = 'D';
385         case 'D':
386                 /* can't handle yet */
387         default:
388                 return (FTP_PROTOCOL_ERROR);
389         }
390         if ((e = ftp_cmd(conn, "TYPE %c", type)) != FTP_OK)
391                 return (e);
392
393         return (FTP_OK);
394 }
395
396 /*
397  * Request and parse file stats
398  */
399 static int
400 ftp_stat(conn_t *conn, const char *file, struct url_stat *us)
401 {
402         char *ln;
403         const char *filename;
404         int filenamelen, type;
405         struct tm tm;
406         time_t t;
407         int e;
408
409         us->size = -1;
410         us->atime = us->mtime = 0;
411
412         filename = ftp_filename(file, &filenamelen, &type);
413
414         if ((e = ftp_mode_type(conn, 0, type)) != FTP_OK) {
415                 ftp_seterr(e);
416                 return (-1);
417         }
418
419         e = ftp_cmd(conn, "SIZE %.*s", filenamelen, filename);
420         if (e != FTP_FILE_STATUS) {
421                 ftp_seterr(e);
422                 return (-1);
423         }
424         for (ln = conn->buf + 4; *ln && isspace((unsigned char)*ln); ln++)
425                 /* nothing */ ;
426         for (us->size = 0; *ln && isdigit((unsigned char)*ln); ln++)
427                 us->size = us->size * 10 + *ln - '0';
428         if (*ln && !isspace((unsigned char)*ln)) {
429                 ftp_seterr(FTP_PROTOCOL_ERROR);
430                 us->size = -1;
431                 return (-1);
432         }
433         if (us->size == 0)
434                 us->size = -1;
435         DEBUG(fprintf(stderr, "size: [%lld]\n", (long long)us->size));
436
437         e = ftp_cmd(conn, "MDTM %.*s", filenamelen, filename);
438         if (e != FTP_FILE_STATUS) {
439                 ftp_seterr(e);
440                 return (-1);
441         }
442         for (ln = conn->buf + 4; *ln && isspace((unsigned char)*ln); ln++)
443                 /* nothing */ ;
444         switch (strspn(ln, "0123456789")) {
445         case 14:
446                 break;
447         case 15:
448                 ln++;
449                 ln[0] = '2';
450                 ln[1] = '0';
451                 break;
452         default:
453                 ftp_seterr(FTP_PROTOCOL_ERROR);
454                 return (-1);
455         }
456         if (sscanf(ln, "%04d%02d%02d%02d%02d%02d",
457             &tm.tm_year, &tm.tm_mon, &tm.tm_mday,
458             &tm.tm_hour, &tm.tm_min, &tm.tm_sec) != 6) {
459                 ftp_seterr(FTP_PROTOCOL_ERROR);
460                 return (-1);
461         }
462         tm.tm_mon--;
463         tm.tm_year -= 1900;
464         tm.tm_isdst = -1;
465         t = timegm(&tm);
466         if (t == (time_t)-1)
467                 t = time(NULL);
468         us->mtime = t;
469         us->atime = t;
470         DEBUG(fprintf(stderr,
471             "last modified: [%04d-%02d-%02d %02d:%02d:%02d]\n",
472             tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
473             tm.tm_hour, tm.tm_min, tm.tm_sec));
474         return (0);
475 }
476
477 /*
478  * I/O functions for FTP
479  */
480 struct ftpio {
481         conn_t  *cconn;         /* Control connection */
482         conn_t  *dconn;         /* Data connection */
483         int      dir;           /* Direction */
484         int      eof;           /* EOF reached */
485         int      err;           /* Error code */
486 };
487
488 static int       ftp_readfn(void *, char *, int);
489 static int       ftp_writefn(void *, const char *, int);
490 static fpos_t    ftp_seekfn(void *, fpos_t, int);
491 static int       ftp_closefn(void *);
492
493 static int
494 ftp_readfn(void *v, char *buf, int len)
495 {
496         struct ftpio *io;
497         int r;
498
499         io = (struct ftpio *)v;
500         if (io == NULL) {
501                 errno = EBADF;
502                 return (-1);
503         }
504         if (io->cconn == NULL || io->dconn == NULL || io->dir == O_WRONLY) {
505                 errno = EBADF;
506                 return (-1);
507         }
508         if (io->err) {
509                 errno = io->err;
510                 return (-1);
511         }
512         if (io->eof)
513                 return (0);
514         r = fetch_read(io->dconn, buf, len);
515         if (r > 0)
516                 return (r);
517         if (r == 0) {
518                 io->eof = 1;
519                 return (0);
520         }
521         if (errno != EINTR)
522                 io->err = errno;
523         return (-1);
524 }
525
526 static int
527 ftp_writefn(void *v, const char *buf, int len)
528 {
529         struct ftpio *io;
530         int w;
531
532         io = (struct ftpio *)v;
533         if (io == NULL) {
534                 errno = EBADF;
535                 return (-1);
536         }
537         if (io->cconn == NULL || io->dconn == NULL || io->dir == O_RDONLY) {
538                 errno = EBADF;
539                 return (-1);
540         }
541         if (io->err) {
542                 errno = io->err;
543                 return (-1);
544         }
545         w = fetch_write(io->dconn, buf, len);
546         if (w >= 0)
547                 return (w);
548         if (errno != EINTR)
549                 io->err = errno;
550         return (-1);
551 }
552
553 static fpos_t
554 ftp_seekfn(void *v, fpos_t pos __unused, int whence __unused)
555 {
556         struct ftpio *io;
557
558         io = (struct ftpio *)v;
559         if (io == NULL) {
560                 errno = EBADF;
561                 return (-1);
562         }
563         errno = ESPIPE;
564         return (-1);
565 }
566
567 static int
568 ftp_closefn(void *v)
569 {
570         struct ftpio *io;
571         int r;
572
573         io = (struct ftpio *)v;
574         if (io == NULL) {
575                 errno = EBADF;
576                 return (-1);
577         }
578         if (io->dir == -1)
579                 return (0);
580         if (io->cconn == NULL || io->dconn == NULL) {
581                 errno = EBADF;
582                 return (-1);
583         }
584         fetch_close(io->dconn);
585         io->dir = -1;
586         io->dconn = NULL;
587         DEBUG(fprintf(stderr, "Waiting for final status\n"));
588         r = ftp_chkerr(io->cconn);
589         if (io->cconn == cached_connection && io->cconn->ref == 1)
590                 cached_connection = NULL;
591         fetch_close(io->cconn);
592         free(io);
593         return (r == FTP_TRANSFER_COMPLETE) ? 0 : -1;
594 }
595
596 static FILE *
597 ftp_setup(conn_t *cconn, conn_t *dconn, int mode)
598 {
599         struct ftpio *io;
600         FILE *f;
601
602         if (cconn == NULL || dconn == NULL)
603                 return (NULL);
604         if ((io = malloc(sizeof(*io))) == NULL)
605                 return (NULL);
606         io->cconn = cconn;
607         io->dconn = dconn;
608         io->dir = mode;
609         io->eof = io->err = 0;
610         f = funopen(io, ftp_readfn, ftp_writefn, ftp_seekfn, ftp_closefn);
611         if (f == NULL)
612                 free(io);
613         return (f);
614 }
615
616 /*
617  * Transfer file
618  */
619 static FILE *
620 ftp_transfer(conn_t *conn, const char *oper, const char *file,
621     int mode, off_t offset, const char *flags)
622 {
623         struct sockaddr_storage sa;
624         struct sockaddr_in6 *sin6;
625         struct sockaddr_in *sin4;
626         const char *bindaddr;
627         const char *filename;
628         int filenamelen, type;
629         int low, pasv, verbose;
630         int e, sd = -1;
631         socklen_t l;
632         char *s;
633         FILE *df;
634
635         /* check flags */
636         low = CHECK_FLAG('l');
637         pasv = CHECK_FLAG('p');
638         verbose = CHECK_FLAG('v');
639
640         /* passive mode */
641         if (!pasv)
642                 pasv = ((s = getenv("FTP_PASSIVE_MODE")) != NULL &&
643                     strncasecmp(s, "no", 2) != 0);
644
645         /* isolate filename */
646         filename = ftp_filename(file, &filenamelen, &type);
647
648         /* set transfer mode and data type */
649         if ((e = ftp_mode_type(conn, 0, type)) != FTP_OK)
650                 goto ouch;
651
652         /* find our own address, bind, and listen */
653         l = sizeof(sa);
654         if (getsockname(conn->sd, (struct sockaddr *)&sa, &l) == -1)
655                 goto sysouch;
656         if (sa.ss_family == AF_INET6)
657                 unmappedaddr((struct sockaddr_in6 *)&sa);
658
659         /* open data socket */
660         if ((sd = socket(sa.ss_family, SOCK_STREAM, IPPROTO_TCP)) == -1) {
661                 fetch_syserr();
662                 return (NULL);
663         }
664
665         if (pasv) {
666                 u_char addr[64];
667                 char *ln, *p;
668                 unsigned int i;
669                 int port;
670
671                 /* send PASV command */
672                 if (verbose)
673                         fetch_info("setting passive mode");
674                 switch (sa.ss_family) {
675                 case AF_INET:
676                         if ((e = ftp_cmd(conn, "PASV")) != FTP_PASSIVE_MODE)
677                                 goto ouch;
678                         break;
679                 case AF_INET6:
680                         if ((e = ftp_cmd(conn, "EPSV")) != FTP_EPASSIVE_MODE) {
681                                 if (e == -1)
682                                         goto ouch;
683                                 if ((e = ftp_cmd(conn, "LPSV")) !=
684                                     FTP_LPASSIVE_MODE)
685                                         goto ouch;
686                         }
687                         break;
688                 default:
689                         e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
690                         goto ouch;
691                 }
692
693                 /*
694                  * Find address and port number. The reply to the PASV command
695                  * is IMHO the one and only weak point in the FTP protocol.
696                  */
697                 ln = conn->buf;
698                 switch (e) {
699                 case FTP_PASSIVE_MODE:
700                 case FTP_LPASSIVE_MODE:
701                         for (p = ln + 3; *p && !isdigit((unsigned char)*p); p++)
702                                 /* nothing */ ;
703                         if (!*p) {
704                                 e = FTP_PROTOCOL_ERROR;
705                                 goto ouch;
706                         }
707                         l = (e == FTP_PASSIVE_MODE ? 6 : 21);
708                         for (i = 0; *p && i < l; i++, p++)
709                                 addr[i] = strtol(p, &p, 10);
710                         if (i < l) {
711                                 e = FTP_PROTOCOL_ERROR;
712                                 goto ouch;
713                         }
714                         break;
715                 case FTP_EPASSIVE_MODE:
716                         for (p = ln + 3; *p && *p != '('; p++)
717                                 /* nothing */ ;
718                         if (!*p) {
719                                 e = FTP_PROTOCOL_ERROR;
720                                 goto ouch;
721                         }
722                         ++p;
723                         if (sscanf(p, "%c%c%c%d%c", &addr[0], &addr[1], &addr[2],
724                                 &port, &addr[3]) != 5 ||
725                             addr[0] != addr[1] ||
726                             addr[0] != addr[2] || addr[0] != addr[3]) {
727                                 e = FTP_PROTOCOL_ERROR;
728                                 goto ouch;
729                         }
730                         break;
731                 }
732
733                 /* seek to required offset */
734                 if (offset)
735                         if (ftp_cmd(conn, "REST %lu", (u_long)offset) != FTP_FILE_OK)
736                                 goto sysouch;
737
738                 /* construct sockaddr for data socket */
739                 l = sizeof(sa);
740                 if (getpeername(conn->sd, (struct sockaddr *)&sa, &l) == -1)
741                         goto sysouch;
742                 if (sa.ss_family == AF_INET6)
743                         unmappedaddr((struct sockaddr_in6 *)&sa);
744                 switch (sa.ss_family) {
745                 case AF_INET6:
746                         sin6 = (struct sockaddr_in6 *)&sa;
747                         if (e == FTP_EPASSIVE_MODE)
748                                 sin6->sin6_port = htons(port);
749                         else {
750                                 memcpy(&sin6->sin6_addr, addr + 2, 16);
751                                 memcpy(&sin6->sin6_port, addr + 19, 2);
752                         }
753                         break;
754                 case AF_INET:
755                         sin4 = (struct sockaddr_in *)&sa;
756                         if (e == FTP_EPASSIVE_MODE)
757                                 sin4->sin_port = htons(port);
758                         else {
759                                 memcpy(&sin4->sin_addr, addr, 4);
760                                 memcpy(&sin4->sin_port, addr + 4, 2);
761                         }
762                         break;
763                 default:
764                         e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
765                         break;
766                 }
767
768                 /* connect to data port */
769                 if (verbose)
770                         fetch_info("opening data connection");
771                 bindaddr = getenv("FETCH_BIND_ADDRESS");
772                 if (bindaddr != NULL && *bindaddr != '\0' &&
773                     fetch_bind(sd, sa.ss_family, bindaddr) != 0)
774                         goto sysouch;
775                 if (connect(sd, (struct sockaddr *)&sa, sa.ss_len) == -1)
776                         goto sysouch;
777
778                 /* make the server initiate the transfer */
779                 if (verbose)
780                         fetch_info("initiating transfer");
781                 e = ftp_cmd(conn, "%s %.*s", oper, filenamelen, filename);
782                 if (e != FTP_CONNECTION_ALREADY_OPEN && e != FTP_OPEN_DATA_CONNECTION)
783                         goto ouch;
784
785         } else {
786                 u_int32_t a;
787                 u_short p;
788                 int arg, d;
789                 char *ap;
790                 char hname[INET6_ADDRSTRLEN];
791
792                 switch (sa.ss_family) {
793                 case AF_INET6:
794                         ((struct sockaddr_in6 *)&sa)->sin6_port = 0;
795 #ifdef IPV6_PORTRANGE
796                         arg = low ? IPV6_PORTRANGE_DEFAULT : IPV6_PORTRANGE_HIGH;
797                         if (setsockopt(sd, IPPROTO_IPV6, IPV6_PORTRANGE,
798                                 (char *)&arg, sizeof(arg)) == -1)
799                                 goto sysouch;
800 #endif
801                         break;
802                 case AF_INET:
803                         ((struct sockaddr_in *)&sa)->sin_port = 0;
804                         arg = low ? IP_PORTRANGE_DEFAULT : IP_PORTRANGE_HIGH;
805                         if (setsockopt(sd, IPPROTO_IP, IP_PORTRANGE,
806                                 (char *)&arg, sizeof(arg)) == -1)
807                                 goto sysouch;
808                         break;
809                 }
810                 if (verbose)
811                         fetch_info("binding data socket");
812                 if (bind(sd, (struct sockaddr *)&sa, sa.ss_len) == -1)
813                         goto sysouch;
814                 if (listen(sd, 1) == -1)
815                         goto sysouch;
816
817                 /* find what port we're on and tell the server */
818                 if (getsockname(sd, (struct sockaddr *)&sa, &l) == -1)
819                         goto sysouch;
820                 switch (sa.ss_family) {
821                 case AF_INET:
822                         sin4 = (struct sockaddr_in *)&sa;
823                         a = ntohl(sin4->sin_addr.s_addr);
824                         p = ntohs(sin4->sin_port);
825                         e = ftp_cmd(conn, "PORT %d,%d,%d,%d,%d,%d",
826                             (a >> 24) & 0xff, (a >> 16) & 0xff,
827                             (a >> 8) & 0xff, a & 0xff,
828                             (p >> 8) & 0xff, p & 0xff);
829                         break;
830                 case AF_INET6:
831 #define UC(b)   (((int)b)&0xff)
832                         e = -1;
833                         sin6 = (struct sockaddr_in6 *)&sa;
834                         sin6->sin6_scope_id = 0;
835                         if (getnameinfo((struct sockaddr *)&sa, sa.ss_len,
836                                 hname, sizeof(hname),
837                                 NULL, 0, NI_NUMERICHOST) == 0) {
838                                 e = ftp_cmd(conn, "EPRT |%d|%s|%d|", 2, hname,
839                                     htons(sin6->sin6_port));
840                                 if (e == -1)
841                                         goto ouch;
842                         }
843                         if (e != FTP_OK) {
844                                 ap = (char *)&sin6->sin6_addr;
845                                 e = ftp_cmd(conn,
846                                     "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
847                                     6, 16,
848                                     UC(ap[0]), UC(ap[1]), UC(ap[2]), UC(ap[3]),
849                                     UC(ap[4]), UC(ap[5]), UC(ap[6]), UC(ap[7]),
850                                     UC(ap[8]), UC(ap[9]), UC(ap[10]), UC(ap[11]),
851                                     UC(ap[12]), UC(ap[13]), UC(ap[14]), UC(ap[15]),
852                                     2,
853                                     (ntohs(sin6->sin6_port) >> 8) & 0xff,
854                                     ntohs(sin6->sin6_port)        & 0xff);
855                         }
856                         break;
857                 default:
858                         e = FTP_PROTOCOL_ERROR; /* XXX: error code should be prepared */
859                         goto ouch;
860                 }
861                 if (e != FTP_OK)
862                         goto ouch;
863
864                 /* seek to required offset */
865                 if (offset)
866                         if (ftp_cmd(conn, "REST %ju", (uintmax_t)offset) != FTP_FILE_OK)
867                                 goto sysouch;
868
869                 /* make the server initiate the transfer */
870                 if (verbose)
871                         fetch_info("initiating transfer");
872                 e = ftp_cmd(conn, "%s %.*s", oper, filenamelen, filename);
873                 if (e != FTP_CONNECTION_ALREADY_OPEN && e != FTP_OPEN_DATA_CONNECTION)
874                         goto ouch;
875
876                 /* accept the incoming connection and go to town */
877                 if ((d = accept(sd, NULL, NULL)) == -1)
878                         goto sysouch;
879                 close(sd);
880                 sd = d;
881         }
882
883         if ((df = ftp_setup(conn, fetch_reopen(sd), mode)) == NULL)
884                 goto sysouch;
885         return (df);
886
887 sysouch:
888         fetch_syserr();
889         if (sd >= 0)
890                 close(sd);
891         return (NULL);
892
893 ouch:
894         if (e != -1)
895                 ftp_seterr(e);
896         if (sd >= 0)
897                 close(sd);
898         return (NULL);
899 }
900
901 /*
902  * Authenticate
903  */
904 static int
905 ftp_authenticate(conn_t *conn, struct url *url, struct url *purl)
906 {
907         const char *user, *pwd, *logname;
908         char pbuf[MAXHOSTNAMELEN + MAXLOGNAME + 1];
909         int e, len;
910
911         /* XXX FTP_AUTH, and maybe .netrc */
912
913         /* send user name and password */
914         if (url->user[0] == '\0')
915                 fetch_netrc_auth(url);
916         user = url->user;
917         if (*user == '\0')
918                 user = getenv("FTP_LOGIN");
919         if (user == NULL || *user == '\0')
920                 user = FTP_ANONYMOUS_USER;
921         if (purl && url->port == fetch_default_port(url->scheme))
922                 e = ftp_cmd(conn, "USER %s@%s", user, url->host);
923         else if (purl)
924                 e = ftp_cmd(conn, "USER %s@%s@%d", user, url->host, url->port);
925         else
926                 e = ftp_cmd(conn, "USER %s", user);
927
928         /* did the server request a password? */
929         if (e == FTP_NEED_PASSWORD) {
930                 pwd = url->pwd;
931                 if (*pwd == '\0')
932                         pwd = getenv("FTP_PASSWORD");
933                 if (pwd == NULL || *pwd == '\0') {
934                         if ((logname = getlogin()) == 0)
935                                 logname = FTP_ANONYMOUS_USER;
936                         if ((len = snprintf(pbuf, MAXLOGNAME + 1, "%s@", logname)) < 0)
937                                 len = 0;
938                         else if (len > MAXLOGNAME)
939                                 len = MAXLOGNAME;
940                         gethostname(pbuf + len, sizeof(pbuf) - len);
941                         pwd = pbuf;
942                 }
943                 e = ftp_cmd(conn, "PASS %s", pwd);
944         }
945
946         return (e);
947 }
948
949 /*
950  * Log on to FTP server
951  */
952 static conn_t *
953 ftp_connect(struct url *url, struct url *purl, const char *flags)
954 {
955         conn_t *conn;
956         int e, direct, verbose;
957 #ifdef INET6
958         int af = AF_UNSPEC;
959 #else
960         int af = AF_INET;
961 #endif
962
963         direct = CHECK_FLAG('d');
964         verbose = CHECK_FLAG('v');
965         if (CHECK_FLAG('4'))
966                 af = AF_INET;
967         else if (CHECK_FLAG('6'))
968                 af = AF_INET6;
969
970         if (direct)
971                 purl = NULL;
972
973         /* check for proxy */
974         if (purl) {
975                 /* XXX proxy authentication! */
976                 conn = fetch_connect(purl->host, purl->port, af, verbose);
977         } else {
978                 /* no proxy, go straight to target */
979                 conn = fetch_connect(url->host, url->port, af, verbose);
980                 purl = NULL;
981         }
982
983         /* check connection */
984         if (conn == NULL)
985                 /* fetch_connect() has already set an error code */
986                 return (NULL);
987
988         /* expect welcome message */
989         if ((e = ftp_chkerr(conn)) != FTP_SERVICE_READY)
990                 goto fouch;
991
992         /* authenticate */
993         if ((e = ftp_authenticate(conn, url, purl)) != FTP_LOGGED_IN)
994                 goto fouch;
995
996         /* TODO: Request extended features supported, if any (RFC 3659). */
997
998         /* done */
999         return (conn);
1000
1001 fouch:
1002         if (e != -1)
1003                 ftp_seterr(e);
1004         fetch_close(conn);
1005         return (NULL);
1006 }
1007
1008 /*
1009  * Disconnect from server
1010  */
1011 static void
1012 ftp_disconnect(conn_t *conn)
1013 {
1014         (void)ftp_cmd(conn, "QUIT");
1015         if (conn == cached_connection && conn->ref == 1)
1016                 cached_connection = NULL;
1017         fetch_close(conn);
1018 }
1019
1020 /*
1021  * Check if we're already connected
1022  */
1023 static int
1024 ftp_isconnected(struct url *url)
1025 {
1026         return (cached_connection
1027             && (strcmp(url->host, cached_host.host) == 0)
1028             && (strcmp(url->user, cached_host.user) == 0)
1029             && (strcmp(url->pwd, cached_host.pwd) == 0)
1030             && (url->port == cached_host.port));
1031 }
1032
1033 /*
1034  * Check the cache, reconnect if no luck
1035  */
1036 static conn_t *
1037 ftp_cached_connect(struct url *url, struct url *purl, const char *flags)
1038 {
1039         conn_t *conn;
1040         int e;
1041
1042         /* set default port */
1043         if (!url->port)
1044                 url->port = fetch_default_port(url->scheme);
1045
1046         /* try to use previously cached connection */
1047         if (ftp_isconnected(url)) {
1048                 e = ftp_cmd(cached_connection, "NOOP");
1049                 if (e == FTP_OK || e == FTP_SYNTAX_ERROR)
1050                         return (fetch_ref(cached_connection));
1051         }
1052
1053         /* connect to server */
1054         if ((conn = ftp_connect(url, purl, flags)) == NULL)
1055                 return (NULL);
1056         if (cached_connection)
1057                 ftp_disconnect(cached_connection);
1058         cached_connection = fetch_ref(conn);
1059         memcpy(&cached_host, url, sizeof(*url));
1060         return (conn);
1061 }
1062
1063 /*
1064  * Check the proxy settings
1065  */
1066 static struct url *
1067 ftp_get_proxy(struct url * url, const char *flags)
1068 {
1069         struct url *purl;
1070         char *p;
1071
1072         if (flags != NULL && strchr(flags, 'd') != NULL)
1073                 return (NULL);
1074         if (fetch_no_proxy_match(url->host))
1075                 return (NULL);
1076         if (((p = getenv("FTP_PROXY")) || (p = getenv("ftp_proxy")) ||
1077                 (p = getenv("HTTP_PROXY")) || (p = getenv("http_proxy"))) &&
1078             *p && (purl = fetchParseURL(p)) != NULL) {
1079                 if (!*purl->scheme) {
1080                         if (getenv("FTP_PROXY") || getenv("ftp_proxy"))
1081                                 strcpy(purl->scheme, SCHEME_FTP);
1082                         else
1083                                 strcpy(purl->scheme, SCHEME_HTTP);
1084                 }
1085                 if (!purl->port)
1086                         purl->port = fetch_default_proxy_port(purl->scheme);
1087                 if (strcasecmp(purl->scheme, SCHEME_FTP) == 0 ||
1088                     strcasecmp(purl->scheme, SCHEME_HTTP) == 0)
1089                         return (purl);
1090                 fetchFreeURL(purl);
1091         }
1092         return (NULL);
1093 }
1094
1095 /*
1096  * Process an FTP request
1097  */
1098 FILE *
1099 ftp_request(struct url *url, const char *op, struct url_stat *us,
1100     struct url *purl, const char *flags)
1101 {
1102         conn_t *conn;
1103         int oflag;
1104
1105         /* check if we should use HTTP instead */
1106         if (purl && strcasecmp(purl->scheme, SCHEME_HTTP) == 0) {
1107                 if (strcmp(op, "STAT") == 0)
1108                         return (http_request(url, "HEAD", us, purl, flags));
1109                 else if (strcmp(op, "RETR") == 0)
1110                         return (http_request(url, "GET", us, purl, flags));
1111                 /*
1112                  * Our HTTP code doesn't support PUT requests yet, so try
1113                  * a direct connection.
1114                  */
1115         }
1116
1117         /* connect to server */
1118         conn = ftp_cached_connect(url, purl, flags);
1119         if (purl)
1120                 fetchFreeURL(purl);
1121         if (conn == NULL)
1122                 return (NULL);
1123
1124         /* change directory */
1125         if (ftp_cwd(conn, url->doc) == -1)
1126                 return (NULL);
1127
1128         /* stat file */
1129         if (us && ftp_stat(conn, url->doc, us) == -1
1130             && fetchLastErrCode != FETCH_PROTO
1131             && fetchLastErrCode != FETCH_UNAVAIL)
1132                 return (NULL);
1133
1134         /* just a stat */
1135         if (strcmp(op, "STAT") == 0)
1136                 return (FILE *)1; /* bogus return value */
1137         if (strcmp(op, "STOR") == 0 || strcmp(op, "APPE") == 0)
1138                 oflag = O_WRONLY;
1139         else
1140                 oflag = O_RDONLY;
1141
1142         /* initiate the transfer */
1143         return (ftp_transfer(conn, op, url->doc, oflag, url->offset, flags));
1144 }
1145
1146 /*
1147  * Get and stat file
1148  */
1149 FILE *
1150 fetchXGetFTP(struct url *url, struct url_stat *us, const char *flags)
1151 {
1152         return (ftp_request(url, "RETR", us, ftp_get_proxy(url, flags), flags));
1153 }
1154
1155 /*
1156  * Get file
1157  */
1158 FILE *
1159 fetchGetFTP(struct url *url, const char *flags)
1160 {
1161         return (fetchXGetFTP(url, NULL, flags));
1162 }
1163
1164 /*
1165  * Put file
1166  */
1167 FILE *
1168 fetchPutFTP(struct url *url, const char *flags)
1169 {
1170         return (ftp_request(url, CHECK_FLAG('a') ? "APPE" : "STOR", NULL,
1171             ftp_get_proxy(url, flags), flags));
1172 }
1173
1174 /*
1175  * Get file stats
1176  */
1177 int
1178 fetchStatFTP(struct url *url, struct url_stat *us, const char *flags)
1179 {
1180         FILE *f;
1181
1182         f = ftp_request(url, "STAT", us, ftp_get_proxy(url, flags), flags);
1183         if (f == NULL)
1184                 return (-1);
1185         /*
1186          * When op is "STAT", ftp_request() will return either NULL or
1187          * (FILE *)1, never a valid FILE *, so we mustn't fclose(f) before
1188          * returning, as it would cause a segfault.
1189          */
1190         return (0);
1191 }
1192
1193 /*
1194  * List a directory
1195  */
1196 struct url_ent *
1197 fetchListFTP(struct url *url __unused, const char *flags __unused)
1198 {
1199         warnx("fetchListFTP(): not implemented");
1200         return (NULL);
1201 }