2 * ----------------------------------------------------------------------------
3 * "THE BEER-WARE LICENSE" (Revision 42):
4 * <phk@login.dknet.dk> wrote this file. As long as you retain this notice you
5 * can do whatever you want with this stuff. If we meet some day, and you think
6 * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
7 * ----------------------------------------------------------------------------
14 * Turned inside out. Now returns xfers as new file ids, not as a special
17 * $FreeBSD: src/lib/libftpio/ftpio.c,v 1.33.2.4 2002/07/25 15:25:32 ume Exp $
18 * $DragonFly: src/lib/libftpio/ftpio.c,v 1.8 2005/07/23 20:23:06 joerg Exp $
22 #include <sys/param.h>
23 #include <sys/socket.h>
25 #include <netinet/in.h>
27 #include <arpa/inet.h>
48 /* How to see by a given code whether or not the connection has timed out */
49 #define FTP_TIMEOUT(code) (FtpTimedOut || code == FTP_TIMED_OUT)
51 /* Internal routines - deal only with internal FTP_t type */
52 static FTP_t ftp_new(void);
53 static void check_passive(FILE *fp);
54 static int ftp_read_method(void *n, char *buf, int nbytes);
55 static int ftp_write_method(void *n, const char *buf, int nbytes);
56 static int ftp_close_method(void *n);
57 static int writes(int fd, const char *s);
58 static char *get_a_line(FTP_t ftp);
59 static int get_a_number(FTP_t ftp, char **q);
60 static int botch(const char *func, const char *botch_state);
61 static int cmd(FTP_t ftp, const char *fmt, ...);
62 static int ftp_login_session(FTP_t ftp, const char *host, int af,
63 const char *user, const char *passwd,
64 int port, int verbose);
65 static int ftp_file_op(FTP_t ftp, const char *operation, const char *file,
66 FILE **fp, const char *mode, off_t *seekto);
67 static int ftp_close(FTP_t ftp);
68 static int get_url_info(const char *url_in, char *host_ret,
69 size_t host_len, int *port_ret,
70 char *name_ret, size_t name_len);
71 static void ftp_timeout(int sig);
72 static void ftp_set_timeout(void);
73 static void ftp_clear_timeout(void);
74 static void ai_unmapped(struct addrinfo *);
76 int networkInit(void);
79 /* Global status variable - ick */
82 /* FTP happy status codes */
83 #define FTP_GENERALLY_HAPPY 200
84 #define FTP_ASCII_HAPPY FTP_GENERALLY_HAPPY
85 #define FTP_BINARY_HAPPY FTP_GENERALLY_HAPPY
86 #define FTP_PORT_HAPPY FTP_GENERALLY_HAPPY
87 #define FTP_HAPPY_COMMENT 220
88 #define FTP_QUIT_HAPPY 221
89 #define FTP_TRANSFER_HAPPY 226
90 #define FTP_PASSIVE_HAPPY 227
91 #define FTP_LPASSIVE_HAPPY 228
92 #define FTP_EPASSIVE_HAPPY 229
93 #define FTP_CHDIR_HAPPY 250
95 /* FTP unhappy status codes */
96 #define FTP_TIMED_OUT 421
98 /* Placeholder in case we want to do any pre-init stuff at some point */
102 return SUCCESS; /* XXX dummy function for now XXX */
105 /* Check a return code with some lenience for back-dated garbage that might be in the buffer */
107 check_code(FTP_t ftp, int var, int preferred)
111 if (var == preferred)
113 else if (var == FTP_TRANSFER_HAPPY) /* last operation succeeded */
114 var = get_a_number(ftp, NULL);
115 else if (var == FTP_HAPPY_COMMENT) /* chit-chat */
116 var = get_a_number(ftp, NULL);
117 else if (var == FTP_GENERALLY_HAPPY) /* general success code */
118 var = get_a_number(ftp, NULL);
129 FTP_t ftp = fcookie(fp);
134 i = cmd(ftp, "TYPE A");
135 if (i < 0 || check_code(ftp, i, FTP_ASCII_HAPPY))
137 ftp->is_binary = FALSE;
144 FTP_t ftp = fcookie(fp);
149 i = cmd(ftp, "TYPE I");
150 if (i < 0 || check_code(ftp, i, FTP_BINARY_HAPPY))
152 ftp->is_binary = TRUE;
156 ftpVerbose(FILE *fp, int status)
158 FTP_t ftp = fcookie(fp);
159 ftp->is_verbose = status;
163 ftpChdir(FILE *fp, char *dir)
166 FTP_t ftp = fcookie(fp);
168 i = cmd(ftp, "CWD %s", dir);
169 if (i < 0 || check_code(ftp, i, FTP_CHDIR_HAPPY))
177 FTP_t ftp = fcookie(fp);
182 ftpErrString(int error)
187 return("connection in wrong state");
189 /* XXX soon UNIX errnos will catch up with FTP protocol errnos */
190 return strerror(error);
191 for (k = 0; k < ftpErrListLength; k++)
192 if (ftpErrList[k].num == error)
193 return(ftpErrList[k].string);
194 return("Unknown error");
198 ftpGetSize(FILE *fp, const char *name)
201 char p[BUFSIZ], *cp, *ep;
202 FTP_t ftp = fcookie(fp);
206 if ((size_t)snprintf(p, sizeof(p), "SIZE %s\r\n", name) >= sizeof(p))
209 fprintf(stderr, "Sending %s", p);
210 if (writes(ftp->fd_ctrl, p))
212 i = get_a_number(ftp, &cp);
213 if (check_code(ftp, i, 213))
216 errno = 0; /* to check for ERANGE */
217 size = (off_t)strtoq(cp, &ep, 10);
218 if (*ep != '\0' || errno == ERANGE)
224 ftpGetModtime(FILE *fp, const char *name)
228 time_t t0 = time (0);
229 FTP_t ftp = fcookie(fp);
233 if ((size_t)snprintf(p, sizeof(p), "MDTM %s\r\n", name) >= sizeof(p))
236 fprintf(stderr, "Sending %s", p);
237 if (writes(ftp->fd_ctrl, p))
239 i = get_a_number(ftp, &cp);
240 if (check_code(ftp, i, 213))
242 while (*cp && !isdigit(*cp))
246 t0 = localtime (&t0)->tm_gmtoff;
247 sscanf(cp, "%04d%02d%02d%02d%02d%02d", &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec);
257 ftpGet(FILE *fp, const char *file, off_t *seekto)
260 FTP_t ftp = fcookie(fp);
263 if (ftpBinary(fp) != SUCCESS)
266 if (ftp_file_op(ftp, "RETR", file, &fp2, "r", seekto) == SUCCESS)
271 /* Returns a standard FILE pointer type representing an open control connection */
273 ftpLogin(const char *host, const char *user, const char *passwd, int port,
274 int verbose, int *retcode)
277 return ftpLoginAf(host, AF_UNSPEC, user, passwd, port, verbose, retcode);
279 return ftpLoginAf(host, AF_INET, user, passwd, port, verbose, retcode);
284 ftpLoginAf(const char *host, int af, const char *user, const char *passwd,
285 int port, int verbose, int *retcode)
292 if (networkInit() != SUCCESS)
297 if (n && ftp_login_session(n, host, af, user, passwd, port, verbose) == SUCCESS) {
298 fp = funopen(n, ftp_read_method, ftp_write_method, NULL, ftp_close_method); /* BSD 4.4 function! */
302 *retcode = (FtpTimedOut ? FTP_TIMED_OUT : -1);
303 /* Poor attempt at mapping real errnos to FTP error codes */
304 else switch(n->error) {
306 *retcode = FTP_TIMED_OUT; /* Actually no such host, but we have no way of saying that. :-( */
310 *retcode = FTP_TIMED_OUT;
322 ftpPut(FILE *fp, const char *file)
325 FTP_t ftp = fcookie(fp);
328 if (ftp_file_op(ftp, "STOR", file, &fp2, "w", NULL) == SUCCESS)
334 ftpPassive(FILE *fp, int st)
336 FTP_t ftp = fcookie(fp);
338 ftp->is_passive = !!st; /* normalize "st" to zero or one */
343 ftpGetURL(const char *url, const char *user, const char *passwd, int *retcode)
346 return ftpGetURLAf(url, AF_UNSPEC, user, passwd, retcode);
348 return ftpGetURLAf(url, AF_INET, user, passwd, retcode);
353 ftpGetURLAf(const char *url, int af, const char *user, const char *passwd,
356 char host[255], name[255];
359 static FILE *fp = NULL;
360 static char *prev_host;
364 if (get_url_info(url, host, sizeof(host), &port, name,
365 sizeof(name)) == SUCCESS) {
366 if (fp && prev_host) {
367 if (!strcmp(prev_host, host)) {
368 /* Try to use cached connection */
369 fp2 = ftpGet(fp, name, NULL);
371 /* Connection timed out or was no longer valid */
380 /* It's a different host now, flush old */
386 fp = ftpLoginAf(host, af, user, passwd, port, 0, retcode);
388 fp2 = ftpGet(fp, name, NULL);
390 /* Connection timed out or was no longer valid */
392 *retcode = ftpErrno(fp);
397 prev_host = strdup(host);
405 ftpPutURL(const char *url, const char *user, const char *passwd, int *retcode)
408 return ftpPutURLAf(url, AF_UNSPEC, user, passwd, retcode);
410 return ftpPutURLAf(url, AF_INET, user, passwd, retcode);
416 ftpPutURLAf(const char *url, int af, const char *user, const char *passwd,
419 char host[255], name[255];
421 static FILE *fp = NULL;
426 if (fp) { /* Close previous managed connection */
430 if (get_url_info(url, host, sizeof(host), &port,
431 name, sizeof(name)) == SUCCESS) {
432 fp = ftpLoginAf(host, af, user, passwd, port, 0, retcode);
434 fp2 = ftpPut(fp, name);
437 *retcode = ftpErrno(fp);
447 /* Internal workhorse function for dissecting URLs. Takes a URL as the first argument and returns the
448 result of such disection in the host, user, passwd, port and name variables. */
450 get_url_info(const char *url_in, char *host_ret, size_t host_len,
451 int *port_ret, char *name_ret, size_t name_len)
453 char *name, *host, *cp, url[BUFSIZ];
457 /* XXX add http:// here or somewhere reasonable at some point XXX */
458 if (strncmp("ftp://", url_in, 6) != 0)
460 /* We like to stomp a lot on the URL string in dissecting it, so copy it first */
461 strncpy(url, url_in, BUFSIZ);
463 if ((cp = index(host, ':')) != NULL) {
465 port = strtol(cp, 0, 0);
468 port = 0; /* use default */
472 if ((name = index(cp ? cp : host, '/')) != NULL)
475 if (strlen(host) >= host_len)
477 strcpy(host_ret, host);
479 if (name && name_ret) {
480 if (strlen(name) >= name_len)
482 strcpy(name_ret, name);
492 ftp = (FTP_t)malloc(sizeof *ftp);
495 memset(ftp, 0, sizeof *ftp);
497 ftp->con_state = init;
498 ftp->is_binary = FALSE;
499 ftp->is_passive = FALSE;
500 ftp->is_verbose = FALSE;
506 ftp_read_method(void *vp, char *buf, int nbytes)
512 i = (fd >= 0) ? read(fd, buf, nbytes) : EOF;
517 ftp_write_method(void *vp, const char *buf, int nbytes)
523 i = (fd >= 0) ? write(fd, buf, nbytes) : EOF;
528 ftp_close_method(void *n)
532 i = ftp_close((FTP_t)n);
538 * This function checks whether the FTP_PASSIVE_MODE environment
539 * variable is set, and, if so, enforces the desired mode.
542 check_passive(FILE *fp)
544 const char *cp = getenv("FTP_PASSIVE_MODE");
547 ftpPassive(fp, strncasecmp(cp, "no", 2));
551 ftp_timeout(int sig __unused)
554 /* Debug("ftp_pkg: ftp_timeout called - operation timed out"); */
558 ftp_set_timeout(void)
560 struct sigaction new;
565 sigemptyset(&new.sa_mask);
567 new.sa_handler = ftp_timeout;
568 sigaction(SIGALRM, &new, NULL);
569 cp = getenv("FTP_TIMEOUT");
570 if (!cp || !(ival = atoi(cp)))
576 ftp_clear_timeout(void)
578 struct sigaction new;
581 sigemptyset(&new.sa_mask);
583 new.sa_handler = SIG_DFL;
584 sigaction(SIGALRM, &new, NULL);
588 writes(int fd, const char *s)
590 int n, i = strlen(s);
595 if (FtpTimedOut || i != n)
601 get_a_line(FTP_t ftp)
603 static char buf[BUFSIZ];
606 /* Debug("ftp_pkg: trying to read a line from %d", ftp->fd_ctrl); */
607 for(i = 0; i < BUFSIZ;) {
609 j = read(ftp->fd_ctrl, buf + i, 1);
611 if (FtpTimedOut || j != 1)
613 if (buf[i] == '\r' || buf[i] == '\n') {
617 if (ftp->is_verbose == TRUE)
618 fprintf(stderr, "%s\n",buf+4);
623 /* Debug("ftp_pkg: read string \"%s\" from %d", buf, ftp->fd_ctrl); */
628 get_a_number(FTP_t ftp, char **q)
638 return FTP_TIMED_OUT;
641 if (!(isdigit(p[0]) && isdigit(p[1]) && isdigit(p[2])))
643 if (i == -1 && p[3] == '-') {
647 if (p[3] != ' ' && p[3] != '\t')
652 /* Debug("ftp_pkg: read reply %d from server (%s)", j, p); */
656 /* Debug("ftp_pkg: read reply %d from server (%s)", j, p); */
668 if (ftp->con_state == isopen) {
669 ftp->con_state = quit;
670 /* If last operation timed out, don't try to quit - just close */
671 if (ftp->error != FTP_TIMED_OUT)
672 i = cmd(ftp, "QUIT");
675 if (!check_code(ftp, i, FTP_QUIT_HAPPY))
680 else if (ftp->con_state == quit)
686 botch(const char *func __unused, const char *botch_state __unused)
688 /* Debug("ftp_pkg: botch: %s(%s)", func, botch_state); */
693 cmd(FTP_t ftp, const char *fmt, ...)
700 if ((size_t)vsnprintf(p, sizeof p - 2, fmt, ap) >= sizeof(p) - 2)
704 if (ftp->con_state == init)
705 return botch("cmd", "open");
709 fprintf(stderr, "Sending: %s", p);
710 if (writes(ftp->fd_ctrl, p)) {
712 return FTP_TIMED_OUT;
715 while ((i = get_a_number(ftp, NULL)) == FTP_HAPPY_COMMENT);
720 ftp_login_session(FTP_t ftp, const char *host, int af,
721 const char *user, const char *passwd, int port, int verbose)
724 struct addrinfo hints, *res, *res0;
729 if (networkInit() != SUCCESS)
732 if (ftp->con_state != init) {
747 if ((size_t)snprintf(pbuf, sizeof(pbuf), "%d", port) >= sizeof(pbuf))
749 memset(&hints, 0, sizeof(hints));
750 hints.ai_family = af;
751 hints.ai_socktype = SOCK_STREAM;
752 hints.ai_protocol = 0;
753 err = getaddrinfo(host, pbuf, &hints, &res0);
760 for (res = res0; res; res = res->ai_next) {
762 ftp->addrtype = res->ai_family;
764 if ((s = socket(res->ai_family, res->ai_socktype,
765 res->ai_protocol)) < 0)
768 if (connect(s, res->ai_addr, res->ai_addrlen) < 0) {
783 ftp->con_state = isopen;
784 ftp->is_verbose = verbose;
786 i = cmd(ftp, "USER %s", user);
787 if (i >= 300 && i < 400)
788 i = cmd(ftp, "PASS %s", passwd);
789 if (i >= 299 || i < 0) {
799 ftp_file_op(FTP_t ftp, const char *operation, const char *file, FILE **fp,
800 const char *mode, off_t *seekto)
804 unsigned char addr[64];
806 struct sockaddr_in sin4;
807 struct sockaddr_in6 sin6;
815 if (ftp->con_state != isopen)
816 return botch("ftp_file_op", "open");
818 if ((s = socket(ftp->addrtype, SOCK_STREAM, 0)) < 0) {
823 if (ftp->is_passive) {
824 if (ftp->addrtype == AF_INET) {
826 fprintf(stderr, "Sending PASV\n");
827 if (writes(ftp->fd_ctrl, "PASV\r\n")) {
830 ftp->error = FTP_TIMED_OUT;
831 return FTP_TIMED_OUT;
833 i = get_a_number(ftp, &q);
834 if (check_code(ftp, i, FTP_PASSIVE_HAPPY)) {
841 fprintf(stderr, "Sending EPSV\n");
842 if (writes(ftp->fd_ctrl, "EPSV\r\n")) {
845 ftp->error = FTP_TIMED_OUT;
846 return FTP_TIMED_OUT;
848 i = get_a_number(ftp, &q);
849 if (check_code(ftp, i, FTP_EPASSIVE_HAPPY)) {
851 fprintf(stderr, "Sending LPSV\n");
852 if (writes(ftp->fd_ctrl, "LPSV\r\n")) {
855 ftp->error = FTP_TIMED_OUT;
856 return FTP_TIMED_OUT;
858 i = get_a_number(ftp, &q);
859 if (check_code(ftp, i, FTP_LPASSIVE_HAPPY)) {
867 if (strcmp(cmdstr, "PASV") == 0 || strcmp(cmdstr, "LPSV") == 0) {
868 while (*q && !isdigit(*q))
875 l = (ftp->addrtype == AF_INET ? 6 : 21);
876 for (i = 0; i < l; i++) {
878 addr[i] = strtol(q, &q, 10);
881 sin.sin4.sin_family = ftp->addrtype;
882 if (ftp->addrtype == AF_INET6) {
883 sin.sin6.sin6_len = sizeof(struct sockaddr_in6);
884 bcopy(addr + 2, (char *)&sin.sin6.sin6_addr, 16);
885 bcopy(addr + 19, (char *)&sin.sin6.sin6_port, 2);
887 sin.sin4.sin_len = sizeof(struct sockaddr_in);
888 bcopy(addr, (char *)&sin.sin4.sin_addr, 4);
889 bcopy(addr + 4, (char *)&sin.sin4.sin_port, 2);
891 } else if (strcmp(cmdstr, "EPSV") == 0) {
894 while (*q && *q != '(') /* ) */
901 if (sscanf(q, "%c%c%c%d%c", &addr[0], &addr[1], &addr[2],
902 &port, &addr[3]) != 5
903 || addr[0] != addr[1] || addr[0] != addr[2] || addr[0] != addr[3]) {
907 sinlen = sizeof(sin);
908 if (getpeername(ftp->fd_ctrl, (struct sockaddr *)&sin, &sinlen) < 0) {
912 switch (sin.sin4.sin_family) {
914 sin.sin4.sin_port = htons(port);
917 sin.sin6.sin6_port = htons(port);
925 if (connect(s, (struct sockaddr *)&sin, sin.sin4.sin_len) < 0) {
930 if (seekto && *seekto) {
931 i = cmd(ftp, "REST %d", *seekto);
932 if (i < 0 || FTP_TIMEOUT(i)) {
939 i = cmd(ftp, "%s %s", operation, file);
940 if (i < 0 || i > 299) {
945 *fp = fdopen(s, mode);
950 #ifdef IPV6_PORTRANGE
951 if (ftp->addrtype == AF_INET6) {
952 portrange = IPV6_PORTRANGE_HIGH;
953 if (setsockopt(s, IPPROTO_IPV6, IPV6_PORTRANGE, (char *)
954 &portrange, sizeof(portrange)) < 0) {
961 if (ftp->addrtype == AF_INET) {
962 portrange = IP_PORTRANGE_HIGH;
963 if (setsockopt(s, IPPROTO_IP, IP_PORTRANGE, (char *)
964 &portrange, sizeof(portrange)) < 0) {
972 getsockname(ftp->fd_ctrl, (struct sockaddr *)&sin, &i);
973 sin.sin4.sin_port = 0;
974 i = ((struct sockaddr *)&sin)->sa_len;
975 if (bind(s, (struct sockaddr *)&sin, i) < 0) {
980 getsockname(s,(struct sockaddr *)&sin,&i);
981 if (listen(s, 1) < 0) {
985 if (sin.sin4.sin_family == AF_INET) {
987 a = ntohl(sin.sin4.sin_addr.s_addr);
988 i = cmd(ftp, "PORT %d,%d,%d,%d,%d,%d",
993 (ntohs(sin.sin4.sin_port) >> 8) & 0xff,
994 ntohs(sin.sin4.sin_port) & 0xff);
995 if (check_code(ftp, i, FTP_PORT_HAPPY)) {
1000 #define UC(b) (((int)b)&0xff)
1002 char hname[INET6_ADDRSTRLEN];
1004 sin.sin6.sin6_scope_id = 0;
1005 if (getnameinfo((struct sockaddr *)&sin, sin.sin6.sin6_len,
1006 hname, sizeof(hname),
1007 NULL, 0, NI_NUMERICHOST) != 0) {
1010 i = cmd(ftp, "EPRT |%d|%s|%d|", 2, hname,
1011 htons(sin.sin6.sin6_port));
1012 if (check_code(ftp, i, FTP_PORT_HAPPY)) {
1014 a = (char *)&sin.sin6.sin6_addr;
1016 "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
1018 UC(a[0]),UC(a[1]),UC(a[2]),UC(a[3]),
1019 UC(a[4]),UC(a[5]),UC(a[6]),UC(a[7]),
1020 UC(a[8]),UC(a[9]),UC(a[10]),UC(a[11]),
1021 UC(a[12]),UC(a[13]),UC(a[14]),UC(a[15]),
1023 (ntohs(sin.sin4.sin_port) >> 8) & 0xff,
1024 ntohs(sin.sin4.sin_port) & 0xff);
1025 if (check_code(ftp, i, FTP_PORT_HAPPY)) {
1031 if (seekto && *seekto) {
1032 i = cmd(ftp, "REST %d", *seekto);
1033 if (i < 0 || FTP_TIMEOUT(i)) {
1041 i = cmd(ftp, "%s %s", operation, file);
1042 if (i < 0 || i > 299) {
1047 fd = accept(s, 0, 0);
1054 *fp = fdopen(fd, mode);
1063 ai_unmapped(struct addrinfo *ai)
1065 struct sockaddr_in6 *sin6;
1066 struct sockaddr_in sin;
1068 if (ai->ai_family != AF_INET6)
1070 if (ai->ai_addrlen != sizeof(struct sockaddr_in6) ||
1071 sizeof(sin) > ai->ai_addrlen)
1073 sin6 = (struct sockaddr_in6 *)ai->ai_addr;
1074 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
1077 memset(&sin, 0, sizeof(sin));
1078 sin.sin_family = AF_INET;
1079 sin.sin_len = sizeof(struct sockaddr_in);
1080 memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
1081 sizeof(sin.sin_addr));
1082 sin.sin_port = sin6->sin6_port;
1084 ai->ai_family = AF_INET;
1085 memcpy(ai->ai_addr, &sin, sin.sin_len);
1086 ai->ai_addrlen = sin.sin_len;