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.4 2004/08/16 13:51:20 joerg Exp $
22 #include <sys/types.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, int *port_ret,
70 static void ftp_timeout(int sig);
71 static void ftp_set_timeout(void);
72 static void ftp_clear_timeout(void);
73 static void ai_unmapped(struct addrinfo *);
75 int networkInit(void);
78 /* Global status variable - ick */
81 /* FTP happy status codes */
82 #define FTP_GENERALLY_HAPPY 200
83 #define FTP_ASCII_HAPPY FTP_GENERALLY_HAPPY
84 #define FTP_BINARY_HAPPY FTP_GENERALLY_HAPPY
85 #define FTP_PORT_HAPPY FTP_GENERALLY_HAPPY
86 #define FTP_HAPPY_COMMENT 220
87 #define FTP_QUIT_HAPPY 221
88 #define FTP_TRANSFER_HAPPY 226
89 #define FTP_PASSIVE_HAPPY 227
90 #define FTP_LPASSIVE_HAPPY 228
91 #define FTP_EPASSIVE_HAPPY 229
92 #define FTP_CHDIR_HAPPY 250
94 /* FTP unhappy status codes */
95 #define FTP_TIMED_OUT 421
99 * gross! evil! bad! We really need an access primitive for cookie in stdio
101 * it's too convenient a hook to bury and it's already exported through funopen
105 #define fcookie(fp) ((fp)->_cookie)
107 /* Placeholder in case we want to do any pre-init stuff at some point */
111 return SUCCESS; /* XXX dummy function for now XXX */
114 /* Check a return code with some lenience for back-dated garbage that might be in the buffer */
116 check_code(FTP_t ftp, int var, int preferred)
120 if (var == preferred)
122 else if (var == FTP_TRANSFER_HAPPY) /* last operation succeeded */
123 var = get_a_number(ftp, NULL);
124 else if (var == FTP_HAPPY_COMMENT) /* chit-chat */
125 var = get_a_number(ftp, NULL);
126 else if (var == FTP_GENERALLY_HAPPY) /* general success code */
127 var = get_a_number(ftp, NULL);
138 FTP_t ftp = fcookie(fp);
143 i = cmd(ftp, "TYPE A");
144 if (i < 0 || check_code(ftp, i, FTP_ASCII_HAPPY))
146 ftp->is_binary = FALSE;
153 FTP_t ftp = fcookie(fp);
158 i = cmd(ftp, "TYPE I");
159 if (i < 0 || check_code(ftp, i, FTP_BINARY_HAPPY))
161 ftp->is_binary = TRUE;
165 ftpVerbose(FILE *fp, int status)
167 FTP_t ftp = fcookie(fp);
168 ftp->is_verbose = status;
172 ftpChdir(FILE *fp, char *dir)
175 FTP_t ftp = fcookie(fp);
177 i = cmd(ftp, "CWD %s", dir);
178 if (i < 0 || check_code(ftp, i, FTP_CHDIR_HAPPY))
186 FTP_t ftp = fcookie(fp);
191 ftpErrString(int error)
196 return("connection in wrong state");
198 /* XXX soon UNIX errnos will catch up with FTP protocol errnos */
199 return strerror(error);
200 for (k = 0; k < ftpErrListLength; k++)
201 if (ftpErrList[k].num == error)
202 return(ftpErrList[k].string);
203 return("Unknown error");
207 ftpGetSize(FILE *fp, const char *name)
210 char p[BUFSIZ], *cp, *ep;
211 FTP_t ftp = fcookie(fp);
215 sprintf(p, "SIZE %s\r\n", name);
217 fprintf(stderr, "Sending %s", p);
218 if (writes(ftp->fd_ctrl, p))
220 i = get_a_number(ftp, &cp);
221 if (check_code(ftp, i, 213))
224 errno = 0; /* to check for ERANGE */
225 size = (off_t)strtoq(cp, &ep, 10);
226 if (*ep != '\0' || errno == ERANGE)
232 ftpGetModtime(FILE *fp, const char *name)
236 time_t t0 = time (0);
237 FTP_t ftp = fcookie(fp);
241 sprintf(p, "MDTM %s\r\n", name);
243 fprintf(stderr, "Sending %s", p);
244 if (writes(ftp->fd_ctrl, p))
246 i = get_a_number(ftp, &cp);
247 if (check_code(ftp, i, 213))
249 while (*cp && !isdigit(*cp))
253 t0 = localtime (&t0)->tm_gmtoff;
254 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);
264 ftpGet(FILE *fp, const char *file, off_t *seekto)
267 FTP_t ftp = fcookie(fp);
270 if (ftpBinary(fp) != SUCCESS)
273 if (ftp_file_op(ftp, "RETR", file, &fp2, "r", seekto) == SUCCESS)
278 /* Returns a standard FILE pointer type representing an open control connection */
280 ftpLogin(const char *host, const char *user, const char *passwd, int port,
281 int verbose, int *retcode)
284 return ftpLoginAf(host, AF_UNSPEC, user, passwd, port, verbose, retcode);
286 return ftpLoginAf(host, AF_INET, user, passwd, port, verbose, retcode);
291 ftpLoginAf(const char *host, int af, const char *user, const char *passwd,
292 int port, int verbose, int *retcode)
299 if (networkInit() != SUCCESS)
304 if (n && ftp_login_session(n, host, af, user, passwd, port, verbose) == SUCCESS) {
305 fp = funopen(n, ftp_read_method, ftp_write_method, NULL, ftp_close_method); /* BSD 4.4 function! */
306 fp->_file = n->fd_ctrl;
310 *retcode = (FtpTimedOut ? FTP_TIMED_OUT : -1);
311 /* Poor attempt at mapping real errnos to FTP error codes */
312 else switch(n->error) {
314 *retcode = FTP_TIMED_OUT; /* Actually no such host, but we have no way of saying that. :-( */
318 *retcode = FTP_TIMED_OUT;
330 ftpPut(FILE *fp, const char *file)
333 FTP_t ftp = fcookie(fp);
336 if (ftp_file_op(ftp, "STOR", file, &fp2, "w", NULL) == SUCCESS)
342 ftpPassive(FILE *fp, int st)
344 FTP_t ftp = fcookie(fp);
346 ftp->is_passive = !!st; /* normalize "st" to zero or one */
351 ftpGetURL(const char *url, const char *user, const char *passwd, int *retcode)
354 return ftpGetURLAf(url, AF_UNSPEC, user, passwd, retcode);
356 return ftpGetURLAf(url, AF_INET, user, passwd, retcode);
361 ftpGetURLAf(const char *url, int af, const char *user, const char *passwd,
364 char host[255], name[255];
367 static FILE *fp = NULL;
368 static char *prev_host;
372 if (get_url_info(url, host, &port, name) == SUCCESS) {
373 if (fp && prev_host) {
374 if (!strcmp(prev_host, host)) {
375 /* Try to use cached connection */
376 fp2 = ftpGet(fp, name, NULL);
378 /* Connection timed out or was no longer valid */
387 /* It's a different host now, flush old */
393 fp = ftpLoginAf(host, af, user, passwd, port, 0, retcode);
395 fp2 = ftpGet(fp, name, NULL);
397 /* Connection timed out or was no longer valid */
399 *retcode = ftpErrno(fp);
404 prev_host = strdup(host);
412 ftpPutURL(const char *url, const char *user, const char *passwd, int *retcode)
415 return ftpPutURLAf(url, AF_UNSPEC, user, passwd, retcode);
417 return ftpPutURLAf(url, AF_INET, user, passwd, retcode);
423 ftpPutURLAf(const char *url, int af, const char *user, const char *passwd,
426 char host[255], name[255];
428 static FILE *fp = NULL;
433 if (fp) { /* Close previous managed connection */
437 if (get_url_info(url, host, &port, name) == SUCCESS) {
438 fp = ftpLoginAf(host, af, user, passwd, port, 0, retcode);
440 fp2 = ftpPut(fp, name);
443 *retcode = ftpErrno(fp);
453 /* Internal workhorse function for dissecting URLs. Takes a URL as the first argument and returns the
454 result of such disection in the host, user, passwd, port and name variables. */
456 get_url_info(const char *url_in, char *host_ret, int *port_ret, char *name_ret)
458 char *name, *host, *cp, url[BUFSIZ];
462 /* XXX add http:// here or somewhere reasonable at some point XXX */
463 if (strncmp("ftp://", url_in, 6) != 0)
465 /* We like to stomp a lot on the URL string in dissecting it, so copy it first */
466 strncpy(url, url_in, BUFSIZ);
468 if ((cp = index(host, ':')) != NULL) {
470 port = strtol(cp, 0, 0);
473 port = 0; /* use default */
477 if ((name = index(cp ? cp : host, '/')) != NULL)
480 strcpy(host_ret, host);
481 if (name && name_ret)
482 strcpy(name_ret, name);
491 ftp = (FTP_t)malloc(sizeof *ftp);
494 memset(ftp, 0, sizeof *ftp);
496 ftp->con_state = init;
497 ftp->is_binary = FALSE;
498 ftp->is_passive = FALSE;
499 ftp->is_verbose = FALSE;
505 ftp_read_method(void *vp, char *buf, int nbytes)
511 i = (fd >= 0) ? read(fd, buf, nbytes) : EOF;
516 ftp_write_method(void *vp, const char *buf, int nbytes)
522 i = (fd >= 0) ? write(fd, buf, nbytes) : EOF;
527 ftp_close_method(void *n)
531 i = ftp_close((FTP_t)n);
537 * This function checks whether the FTP_PASSIVE_MODE environment
538 * variable is set, and, if so, enforces the desired mode.
541 check_passive(FILE *fp)
543 const char *cp = getenv("FTP_PASSIVE_MODE");
546 ftpPassive(fp, strncasecmp(cp, "no", 2));
550 ftp_timeout(int sig __unused)
553 /* Debug("ftp_pkg: ftp_timeout called - operation timed out"); */
557 ftp_set_timeout(void)
559 struct sigaction new;
564 sigemptyset(&new.sa_mask);
566 new.sa_handler = ftp_timeout;
567 sigaction(SIGALRM, &new, NULL);
568 cp = getenv("FTP_TIMEOUT");
569 if (!cp || !(ival = atoi(cp)))
575 ftp_clear_timeout(void)
577 struct sigaction new;
580 sigemptyset(&new.sa_mask);
582 new.sa_handler = SIG_DFL;
583 sigaction(SIGALRM, &new, NULL);
587 writes(int fd, const char *s)
589 int n, i = strlen(s);
594 if (FtpTimedOut || i != n)
600 get_a_line(FTP_t ftp)
602 static char buf[BUFSIZ];
605 /* Debug("ftp_pkg: trying to read a line from %d", ftp->fd_ctrl); */
606 for(i = 0; i < BUFSIZ;) {
608 j = read(ftp->fd_ctrl, buf + i, 1);
610 if (FtpTimedOut || j != 1)
612 if (buf[i] == '\r' || buf[i] == '\n') {
616 if (ftp->is_verbose == TRUE)
617 fprintf(stderr, "%s\n",buf+4);
622 /* Debug("ftp_pkg: read string \"%s\" from %d", buf, ftp->fd_ctrl); */
627 get_a_number(FTP_t ftp, char **q)
637 return FTP_TIMED_OUT;
640 if (!(isdigit(p[0]) && isdigit(p[1]) && isdigit(p[2])))
642 if (i == -1 && p[3] == '-') {
646 if (p[3] != ' ' && p[3] != '\t')
651 /* Debug("ftp_pkg: read reply %d from server (%s)", j, p); */
655 /* Debug("ftp_pkg: read reply %d from server (%s)", j, p); */
667 if (ftp->con_state == isopen) {
668 ftp->con_state = quit;
669 /* If last operation timed out, don't try to quit - just close */
670 if (ftp->error != FTP_TIMED_OUT)
671 i = cmd(ftp, "QUIT");
674 if (!check_code(ftp, i, FTP_QUIT_HAPPY))
679 else if (ftp->con_state == quit)
685 botch(const char *func __unused, const char *botch_state __unused)
687 /* Debug("ftp_pkg: botch: %s(%s)", func, botch_state); */
692 cmd(FTP_t ftp, const char *fmt, ...)
699 (void)vsnprintf(p, sizeof p, fmt, ap);
702 if (ftp->con_state == init)
703 return botch("cmd", "open");
707 fprintf(stderr, "Sending: %s", p);
708 if (writes(ftp->fd_ctrl, p)) {
710 return FTP_TIMED_OUT;
713 while ((i = get_a_number(ftp, NULL)) == FTP_HAPPY_COMMENT);
718 ftp_login_session(FTP_t ftp, const char *host, int af,
719 const char *user, const char *passwd, int port, int verbose)
722 struct addrinfo hints, *res, *res0;
727 if (networkInit() != SUCCESS)
730 if (ftp->con_state != init) {
745 snprintf(pbuf, sizeof(pbuf), "%d", port);
746 memset(&hints, 0, sizeof(hints));
747 hints.ai_family = af;
748 hints.ai_socktype = SOCK_STREAM;
749 hints.ai_protocol = 0;
750 err = getaddrinfo(host, pbuf, &hints, &res0);
757 for (res = res0; res; res = res->ai_next) {
759 ftp->addrtype = res->ai_family;
761 if ((s = socket(res->ai_family, res->ai_socktype,
762 res->ai_protocol)) < 0)
765 if (connect(s, res->ai_addr, res->ai_addrlen) < 0) {
780 ftp->con_state = isopen;
781 ftp->is_verbose = verbose;
783 i = cmd(ftp, "USER %s", user);
784 if (i >= 300 && i < 400)
785 i = cmd(ftp, "PASS %s", passwd);
786 if (i >= 299 || i < 0) {
796 ftp_file_op(FTP_t ftp, const char *operation, const char *file, FILE **fp,
797 const char *mode, off_t *seekto)
801 unsigned char addr[64];
803 struct sockaddr_in sin4;
804 struct sockaddr_in6 sin6;
812 if (ftp->con_state != isopen)
813 return botch("ftp_file_op", "open");
815 if ((s = socket(ftp->addrtype, SOCK_STREAM, 0)) < 0) {
820 if (ftp->is_passive) {
821 if (ftp->addrtype == AF_INET) {
823 fprintf(stderr, "Sending PASV\n");
824 if (writes(ftp->fd_ctrl, "PASV\r\n")) {
827 ftp->error = FTP_TIMED_OUT;
828 return FTP_TIMED_OUT;
830 i = get_a_number(ftp, &q);
831 if (check_code(ftp, i, FTP_PASSIVE_HAPPY)) {
838 fprintf(stderr, "Sending EPSV\n");
839 if (writes(ftp->fd_ctrl, "EPSV\r\n")) {
842 ftp->error = FTP_TIMED_OUT;
843 return FTP_TIMED_OUT;
845 i = get_a_number(ftp, &q);
846 if (check_code(ftp, i, FTP_EPASSIVE_HAPPY)) {
848 fprintf(stderr, "Sending LPSV\n");
849 if (writes(ftp->fd_ctrl, "LPSV\r\n")) {
852 ftp->error = FTP_TIMED_OUT;
853 return FTP_TIMED_OUT;
855 i = get_a_number(ftp, &q);
856 if (check_code(ftp, i, FTP_LPASSIVE_HAPPY)) {
864 if (strcmp(cmdstr, "PASV") == 0 || strcmp(cmdstr, "LPSV") == 0) {
865 while (*q && !isdigit(*q))
872 l = (ftp->addrtype == AF_INET ? 6 : 21);
873 for (i = 0; i < l; i++) {
875 addr[i] = strtol(q, &q, 10);
878 sin.sin4.sin_family = ftp->addrtype;
879 if (ftp->addrtype == AF_INET6) {
880 sin.sin6.sin6_len = sizeof(struct sockaddr_in6);
881 bcopy(addr + 2, (char *)&sin.sin6.sin6_addr, 16);
882 bcopy(addr + 19, (char *)&sin.sin6.sin6_port, 2);
884 sin.sin4.sin_len = sizeof(struct sockaddr_in);
885 bcopy(addr, (char *)&sin.sin4.sin_addr, 4);
886 bcopy(addr + 4, (char *)&sin.sin4.sin_port, 2);
888 } else if (strcmp(cmdstr, "EPSV") == 0) {
891 while (*q && *q != '(') /* ) */
898 if (sscanf(q, "%c%c%c%d%c", &addr[0], &addr[1], &addr[2],
899 &port, &addr[3]) != 5
900 || addr[0] != addr[1] || addr[0] != addr[2] || addr[0] != addr[3]) {
904 sinlen = sizeof(sin);
905 if (getpeername(ftp->fd_ctrl, (struct sockaddr *)&sin, &sinlen) < 0) {
909 switch (sin.sin4.sin_family) {
911 sin.sin4.sin_port = htons(port);
914 sin.sin6.sin6_port = htons(port);
922 if (connect(s, (struct sockaddr *)&sin, sin.sin4.sin_len) < 0) {
927 if (seekto && *seekto) {
928 i = cmd(ftp, "REST %d", *seekto);
929 if (i < 0 || FTP_TIMEOUT(i)) {
936 i = cmd(ftp, "%s %s", operation, file);
937 if (i < 0 || i > 299) {
942 *fp = fdopen(s, mode);
947 #ifdef IPV6_PORTRANGE
948 if (ftp->addrtype == AF_INET6) {
949 portrange = IPV6_PORTRANGE_HIGH;
950 if (setsockopt(s, IPPROTO_IPV6, IPV6_PORTRANGE, (char *)
951 &portrange, sizeof(portrange)) < 0) {
958 if (ftp->addrtype == AF_INET) {
959 portrange = IP_PORTRANGE_HIGH;
960 if (setsockopt(s, IPPROTO_IP, IP_PORTRANGE, (char *)
961 &portrange, sizeof(portrange)) < 0) {
969 getsockname(ftp->fd_ctrl, (struct sockaddr *)&sin, &i);
970 sin.sin4.sin_port = 0;
971 i = ((struct sockaddr *)&sin)->sa_len;
972 if (bind(s, (struct sockaddr *)&sin, i) < 0) {
977 getsockname(s,(struct sockaddr *)&sin,&i);
978 if (listen(s, 1) < 0) {
982 if (sin.sin4.sin_family == AF_INET) {
984 a = ntohl(sin.sin4.sin_addr.s_addr);
985 i = cmd(ftp, "PORT %d,%d,%d,%d,%d,%d",
990 (ntohs(sin.sin4.sin_port) >> 8) & 0xff,
991 ntohs(sin.sin4.sin_port) & 0xff);
992 if (check_code(ftp, i, FTP_PORT_HAPPY)) {
997 #define UC(b) (((int)b)&0xff)
999 char hname[INET6_ADDRSTRLEN];
1001 sin.sin6.sin6_scope_id = 0;
1002 if (getnameinfo((struct sockaddr *)&sin, sin.sin6.sin6_len,
1003 hname, sizeof(hname),
1004 NULL, 0, NI_NUMERICHOST) != 0) {
1007 i = cmd(ftp, "EPRT |%d|%s|%d|", 2, hname,
1008 htons(sin.sin6.sin6_port));
1009 if (check_code(ftp, i, FTP_PORT_HAPPY)) {
1011 a = (char *)&sin.sin6.sin6_addr;
1013 "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
1015 UC(a[0]),UC(a[1]),UC(a[2]),UC(a[3]),
1016 UC(a[4]),UC(a[5]),UC(a[6]),UC(a[7]),
1017 UC(a[8]),UC(a[9]),UC(a[10]),UC(a[11]),
1018 UC(a[12]),UC(a[13]),UC(a[14]),UC(a[15]),
1020 (ntohs(sin.sin4.sin_port) >> 8) & 0xff,
1021 ntohs(sin.sin4.sin_port) & 0xff);
1022 if (check_code(ftp, i, FTP_PORT_HAPPY)) {
1028 if (seekto && *seekto) {
1029 i = cmd(ftp, "REST %d", *seekto);
1030 if (i < 0 || FTP_TIMEOUT(i)) {
1038 i = cmd(ftp, "%s %s", operation, file);
1039 if (i < 0 || i > 299) {
1044 fd = accept(s, 0, 0);
1051 *fp = fdopen(fd, mode);
1060 ai_unmapped(struct addrinfo *ai)
1062 struct sockaddr_in6 *sin6;
1063 struct sockaddr_in sin;
1065 if (ai->ai_family != AF_INET6)
1067 if (ai->ai_addrlen != sizeof(struct sockaddr_in6) ||
1068 sizeof(sin) > ai->ai_addrlen)
1070 sin6 = (struct sockaddr_in6 *)ai->ai_addr;
1071 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
1074 memset(&sin, 0, sizeof(sin));
1075 sin.sin_family = AF_INET;
1076 sin.sin_len = sizeof(struct sockaddr_in);
1077 memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
1078 sizeof(sin.sin_addr));
1079 sin.sin_port = sin6->sin6_port;
1081 ai->ai_family = AF_INET;
1082 memcpy(ai->ai_addr, &sin, sin.sin_len);
1083 ai->ai_addrlen = sin.sin_len;