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.2 2003/06/17 04:26:49 dillon 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, char *s);
58 static __inline char *get_a_line(FTP_t ftp);
59 static int get_a_number(FTP_t ftp, char **q);
60 static int botch(char *func, char *botch_state);
61 static int cmd(FTP_t ftp, const char *fmt, ...);
62 static int ftp_login_session(FTP_t ftp, char *host, int af, char *user, char *passwd, int port, int verbose);
63 static int ftp_file_op(FTP_t ftp, char *operation, char *file, FILE **fp, char *mode, off_t *seekto);
64 static int ftp_close(FTP_t ftp);
65 static int get_url_info(char *url_in, char *host_ret, int *port_ret, char *name_ret);
66 static void ftp_timeout(int sig);
67 static void ftp_set_timeout(void);
68 static void ftp_clear_timeout(void);
69 static void ai_unmapped(struct addrinfo *);
72 /* Global status variable - ick */
75 /* FTP happy status codes */
76 #define FTP_GENERALLY_HAPPY 200
77 #define FTP_ASCII_HAPPY FTP_GENERALLY_HAPPY
78 #define FTP_BINARY_HAPPY FTP_GENERALLY_HAPPY
79 #define FTP_PORT_HAPPY FTP_GENERALLY_HAPPY
80 #define FTP_HAPPY_COMMENT 220
81 #define FTP_QUIT_HAPPY 221
82 #define FTP_TRANSFER_HAPPY 226
83 #define FTP_PASSIVE_HAPPY 227
84 #define FTP_LPASSIVE_HAPPY 228
85 #define FTP_EPASSIVE_HAPPY 229
86 #define FTP_CHDIR_HAPPY 250
88 /* FTP unhappy status codes */
89 #define FTP_TIMED_OUT 421
93 * gross! evil! bad! We really need an access primitive for cookie in stdio itself.
94 * it's too convenient a hook to bury and it's already exported through funopen as it is, so...
97 #define fcookie(fp) ((fp)->_cookie)
99 /* Placeholder in case we want to do any pre-init stuff at some point */
103 return SUCCESS; /* XXX dummy function for now XXX */
106 /* Check a return code with some lenience for back-dated garbage that might be in the buffer */
108 check_code(FTP_t ftp, int var, int preferred)
112 if (var == preferred)
114 else if (var == FTP_TRANSFER_HAPPY) /* last operation succeeded */
115 var = get_a_number(ftp, NULL);
116 else if (var == FTP_HAPPY_COMMENT) /* chit-chat */
117 var = get_a_number(ftp, NULL);
118 else if (var == FTP_GENERALLY_HAPPY) /* general success code */
119 var = get_a_number(ftp, NULL);
130 FTP_t ftp = fcookie(fp);
135 i = cmd(ftp, "TYPE A");
136 if (i < 0 || check_code(ftp, i, FTP_ASCII_HAPPY))
138 ftp->is_binary = FALSE;
145 FTP_t ftp = fcookie(fp);
150 i = cmd(ftp, "TYPE I");
151 if (i < 0 || check_code(ftp, i, FTP_BINARY_HAPPY))
153 ftp->is_binary = TRUE;
157 ftpVerbose(FILE *fp, int status)
159 FTP_t ftp = fcookie(fp);
160 ftp->is_verbose = status;
164 ftpChdir(FILE *fp, char *dir)
167 FTP_t ftp = fcookie(fp);
169 i = cmd(ftp, "CWD %s", dir);
170 if (i < 0 || check_code(ftp, i, FTP_CHDIR_HAPPY))
178 FTP_t ftp = fcookie(fp);
183 ftpErrString(int error)
188 return("connection in wrong state");
190 /* XXX soon UNIX errnos will catch up with FTP protocol errnos */
191 return strerror(error);
192 for (k = 0; k < ftpErrListLength; k++)
193 if (ftpErrList[k].num == error)
194 return(ftpErrList[k].string);
195 return("Unknown error");
199 ftpGetSize(FILE *fp, char *name)
202 char p[BUFSIZ], *cp, *ep;
203 FTP_t ftp = fcookie(fp);
207 sprintf(p, "SIZE %s\r\n", name);
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, char *name)
228 time_t t0 = time (0);
229 FTP_t ftp = fcookie(fp);
233 sprintf(p, "MDTM %s\r\n", name);
235 fprintf(stderr, "Sending %s", p);
236 if (writes(ftp->fd_ctrl, p))
238 i = get_a_number(ftp, &cp);
239 if (check_code(ftp, i, 213))
241 while (*cp && !isdigit(*cp))
245 t0 = localtime (&t0)->tm_gmtoff;
246 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);
256 ftpGet(FILE *fp, char *file, off_t *seekto)
259 FTP_t ftp = fcookie(fp);
262 if (ftpBinary(fp) != SUCCESS)
265 if (ftp_file_op(ftp, "RETR", file, &fp2, "r", seekto) == SUCCESS)
270 /* Returns a standard FILE pointer type representing an open control connection */
272 ftpLogin(char *host, char *user, char *passwd, int port, int verbose, int *retcode)
275 return ftpLoginAf(host, AF_UNSPEC, user, passwd, port, verbose, retcode);
277 return ftpLoginAf(host, AF_INET, user, passwd, port, verbose, retcode);
282 ftpLoginAf(char *host, int af, char *user, char *passwd, int port, int verbose, int *retcode)
289 if (networkInit() != SUCCESS)
294 if (n && ftp_login_session(n, host, af, user, passwd, port, verbose) == SUCCESS) {
295 fp = funopen(n, ftp_read_method, ftp_write_method, NULL, ftp_close_method); /* BSD 4.4 function! */
296 fp->_file = n->fd_ctrl;
300 *retcode = (FtpTimedOut ? FTP_TIMED_OUT : -1);
301 /* Poor attempt at mapping real errnos to FTP error codes */
302 else switch(n->error) {
304 *retcode = FTP_TIMED_OUT; /* Actually no such host, but we have no way of saying that. :-( */
308 *retcode = FTP_TIMED_OUT;
320 ftpPut(FILE *fp, char *file)
323 FTP_t ftp = fcookie(fp);
326 if (ftp_file_op(ftp, "STOR", file, &fp2, "w", NULL) == SUCCESS)
332 ftpPassive(FILE *fp, int st)
334 FTP_t ftp = fcookie(fp);
336 ftp->is_passive = !!st; /* normalize "st" to zero or one */
341 ftpGetURL(char *url, char *user, char *passwd, int *retcode)
344 return ftpGetURLAf(url, AF_UNSPEC, user, passwd, retcode);
346 return ftpGetURLAf(url, AF_INET, user, passwd, retcode);
351 ftpGetURLAf(char *url, int af, char *user, char *passwd, int *retcode)
353 char host[255], name[255];
356 static FILE *fp = NULL;
357 static char *prev_host;
361 if (get_url_info(url, host, &port, name) == SUCCESS) {
362 if (fp && prev_host) {
363 if (!strcmp(prev_host, host)) {
364 /* Try to use cached connection */
365 fp2 = ftpGet(fp, name, NULL);
367 /* Connection timed out or was no longer valid */
376 /* It's a different host now, flush old */
382 fp = ftpLoginAf(host, af, user, passwd, port, 0, retcode);
384 fp2 = ftpGet(fp, name, NULL);
386 /* Connection timed out or was no longer valid */
388 *retcode = ftpErrno(fp);
393 prev_host = strdup(host);
401 ftpPutURL(char *url, char *user, char *passwd, int *retcode)
404 return ftpPutURLAf(url, AF_UNSPEC, user, passwd, retcode);
406 return ftpPutURLAf(url, AF_INET, user, passwd, retcode);
412 ftpPutURLAf(char *url, int af, char *user, char *passwd, int *retcode)
414 char host[255], name[255];
416 static FILE *fp = NULL;
421 if (fp) { /* Close previous managed connection */
425 if (get_url_info(url, host, &port, name) == SUCCESS) {
426 fp = ftpLoginAf(host, af, user, passwd, port, 0, retcode);
428 fp2 = ftpPut(fp, name);
431 *retcode = ftpErrno(fp);
441 /* Internal workhorse function for dissecting URLs. Takes a URL as the first argument and returns the
442 result of such disection in the host, user, passwd, port and name variables. */
444 get_url_info(char *url_in, char *host_ret, int *port_ret, char *name_ret)
446 char *name, *host, *cp, url[BUFSIZ];
450 /* XXX add http:// here or somewhere reasonable at some point XXX */
451 if (strncmp("ftp://", url_in, 6) != 0)
453 /* We like to stomp a lot on the URL string in dissecting it, so copy it first */
454 strncpy(url, url_in, BUFSIZ);
456 if ((cp = index(host, ':')) != NULL) {
458 port = strtol(cp, 0, 0);
461 port = 0; /* use default */
465 if ((name = index(cp ? cp : host, '/')) != NULL)
468 strcpy(host_ret, host);
469 if (name && name_ret)
470 strcpy(name_ret, name);
479 ftp = (FTP_t)malloc(sizeof *ftp);
482 memset(ftp, 0, sizeof *ftp);
484 ftp->con_state = init;
485 ftp->is_binary = FALSE;
486 ftp->is_passive = FALSE;
487 ftp->is_verbose = FALSE;
493 ftp_read_method(void *vp, char *buf, int nbytes)
499 i = (fd >= 0) ? read(fd, buf, nbytes) : EOF;
504 ftp_write_method(void *vp, const char *buf, int nbytes)
510 i = (fd >= 0) ? write(fd, buf, nbytes) : EOF;
515 ftp_close_method(void *n)
519 i = ftp_close((FTP_t)n);
525 * This function checks whether the FTP_PASSIVE_MODE environment
526 * variable is set, and, if so, enforces the desired mode.
529 check_passive(FILE *fp)
531 const char *cp = getenv("FTP_PASSIVE_MODE");
534 ftpPassive(fp, strncasecmp(cp, "no", 2));
541 /* Debug("ftp_pkg: ftp_timeout called - operation timed out"); */
545 ftp_set_timeout(void)
547 struct sigaction new;
552 sigemptyset(&new.sa_mask);
554 new.sa_handler = ftp_timeout;
555 sigaction(SIGALRM, &new, NULL);
556 cp = getenv("FTP_TIMEOUT");
557 if (!cp || !(ival = atoi(cp)))
563 ftp_clear_timeout(void)
565 struct sigaction new;
568 sigemptyset(&new.sa_mask);
570 new.sa_handler = SIG_DFL;
571 sigaction(SIGALRM, &new, NULL);
575 writes(int fd, char *s)
577 int n, i = strlen(s);
582 if (FtpTimedOut || i != n)
587 static __inline char *
588 get_a_line(FTP_t ftp)
590 static char buf[BUFSIZ];
593 /* Debug("ftp_pkg: trying to read a line from %d", ftp->fd_ctrl); */
594 for(i = 0; i < BUFSIZ;) {
596 j = read(ftp->fd_ctrl, buf + i, 1);
598 if (FtpTimedOut || j != 1)
600 if (buf[i] == '\r' || buf[i] == '\n') {
604 if (ftp->is_verbose == TRUE)
605 fprintf(stderr, "%s\n",buf+4);
610 /* Debug("ftp_pkg: read string \"%s\" from %d", buf, ftp->fd_ctrl); */
615 get_a_number(FTP_t ftp, char **q)
625 return FTP_TIMED_OUT;
628 if (!(isdigit(p[0]) && isdigit(p[1]) && isdigit(p[2])))
630 if (i == -1 && p[3] == '-') {
634 if (p[3] != ' ' && p[3] != '\t')
639 /* Debug("ftp_pkg: read reply %d from server (%s)", j, p); */
643 /* Debug("ftp_pkg: read reply %d from server (%s)", j, p); */
655 if (ftp->con_state == isopen) {
656 ftp->con_state = quit;
657 /* If last operation timed out, don't try to quit - just close */
658 if (ftp->error != FTP_TIMED_OUT)
659 i = cmd(ftp, "QUIT");
662 if (!check_code(ftp, i, FTP_QUIT_HAPPY))
667 else if (ftp->con_state == quit)
673 botch(char *func, char *botch_state)
675 /* Debug("ftp_pkg: botch: %s(%s)", func, botch_state); */
680 cmd(FTP_t ftp, const char *fmt, ...)
687 (void)vsnprintf(p, sizeof p, fmt, ap);
690 if (ftp->con_state == init)
691 return botch("cmd", "open");
695 fprintf(stderr, "Sending: %s", p);
696 if (writes(ftp->fd_ctrl, p)) {
698 return FTP_TIMED_OUT;
701 while ((i = get_a_number(ftp, NULL)) == FTP_HAPPY_COMMENT);
706 ftp_login_session(FTP_t ftp, char *host, int af,
707 char *user, char *passwd, int port, int verbose)
710 struct addrinfo hints, *res, *res0;
715 if (networkInit() != SUCCESS)
718 if (ftp->con_state != init) {
733 snprintf(pbuf, sizeof(pbuf), "%d", port);
734 memset(&hints, 0, sizeof(hints));
735 hints.ai_family = af;
736 hints.ai_socktype = SOCK_STREAM;
737 hints.ai_protocol = 0;
738 err = getaddrinfo(host, pbuf, &hints, &res0);
745 for (res = res0; res; res = res->ai_next) {
747 ftp->addrtype = res->ai_family;
749 if ((s = socket(res->ai_family, res->ai_socktype,
750 res->ai_protocol)) < 0)
753 if (connect(s, res->ai_addr, res->ai_addrlen) < 0) {
768 ftp->con_state = isopen;
769 ftp->is_verbose = verbose;
771 i = cmd(ftp, "USER %s", user);
772 if (i >= 300 && i < 400)
773 i = cmd(ftp, "PASS %s", passwd);
774 if (i >= 299 || i < 0) {
784 ftp_file_op(FTP_t ftp, char *operation, char *file, FILE **fp, char *mode, off_t *seekto)
788 unsigned char addr[64];
790 struct sockaddr_in sin4;
791 struct sockaddr_in6 sin6;
799 if (ftp->con_state != isopen)
800 return botch("ftp_file_op", "open");
802 if ((s = socket(ftp->addrtype, SOCK_STREAM, 0)) < 0) {
807 if (ftp->is_passive) {
808 if (ftp->addrtype == AF_INET) {
810 fprintf(stderr, "Sending PASV\n");
811 if (writes(ftp->fd_ctrl, "PASV\r\n")) {
814 ftp->error = FTP_TIMED_OUT;
815 return FTP_TIMED_OUT;
817 i = get_a_number(ftp, &q);
818 if (check_code(ftp, i, FTP_PASSIVE_HAPPY)) {
825 fprintf(stderr, "Sending EPSV\n");
826 if (writes(ftp->fd_ctrl, "EPSV\r\n")) {
829 ftp->error = FTP_TIMED_OUT;
830 return FTP_TIMED_OUT;
832 i = get_a_number(ftp, &q);
833 if (check_code(ftp, i, FTP_EPASSIVE_HAPPY)) {
835 fprintf(stderr, "Sending LPSV\n");
836 if (writes(ftp->fd_ctrl, "LPSV\r\n")) {
839 ftp->error = FTP_TIMED_OUT;
840 return FTP_TIMED_OUT;
842 i = get_a_number(ftp, &q);
843 if (check_code(ftp, i, FTP_LPASSIVE_HAPPY)) {
851 if (strcmp(cmdstr, "PASV") == 0 || strcmp(cmdstr, "LPSV") == 0) {
852 while (*q && !isdigit(*q))
859 l = (ftp->addrtype == AF_INET ? 6 : 21);
860 for (i = 0; i < l; i++) {
862 addr[i] = strtol(q, &q, 10);
865 sin.sin4.sin_family = ftp->addrtype;
866 if (ftp->addrtype == AF_INET6) {
867 sin.sin6.sin6_len = sizeof(struct sockaddr_in6);
868 bcopy(addr + 2, (char *)&sin.sin6.sin6_addr, 16);
869 bcopy(addr + 19, (char *)&sin.sin6.sin6_port, 2);
871 sin.sin4.sin_len = sizeof(struct sockaddr_in);
872 bcopy(addr, (char *)&sin.sin4.sin_addr, 4);
873 bcopy(addr + 4, (char *)&sin.sin4.sin_port, 2);
875 } else if (strcmp(cmdstr, "EPSV") == 0) {
878 while (*q && *q != '(') /* ) */
885 if (sscanf(q, "%c%c%c%d%c", &addr[0], &addr[1], &addr[2],
886 &port, &addr[3]) != 5
887 || addr[0] != addr[1] || addr[0] != addr[2] || addr[0] != addr[3]) {
891 sinlen = sizeof(sin);
892 if (getpeername(ftp->fd_ctrl, (struct sockaddr *)&sin, &sinlen) < 0) {
896 switch (sin.sin4.sin_family) {
898 sin.sin4.sin_port = htons(port);
901 sin.sin6.sin6_port = htons(port);
909 if (connect(s, (struct sockaddr *)&sin, sin.sin4.sin_len) < 0) {
914 if (seekto && *seekto) {
915 i = cmd(ftp, "REST %d", *seekto);
916 if (i < 0 || FTP_TIMEOUT(i)) {
923 i = cmd(ftp, "%s %s", operation, file);
924 if (i < 0 || i > 299) {
929 *fp = fdopen(s, mode);
934 #ifdef IPV6_PORTRANGE
935 if (ftp->addrtype == AF_INET6) {
936 portrange = IPV6_PORTRANGE_HIGH;
937 if (setsockopt(s, IPPROTO_IPV6, IPV6_PORTRANGE, (char *)
938 &portrange, sizeof(portrange)) < 0) {
945 if (ftp->addrtype == AF_INET) {
946 portrange = IP_PORTRANGE_HIGH;
947 if (setsockopt(s, IPPROTO_IP, IP_PORTRANGE, (char *)
948 &portrange, sizeof(portrange)) < 0) {
956 getsockname(ftp->fd_ctrl, (struct sockaddr *)&sin, &i);
957 sin.sin4.sin_port = 0;
958 i = ((struct sockaddr *)&sin)->sa_len;
959 if (bind(s, (struct sockaddr *)&sin, i) < 0) {
964 getsockname(s,(struct sockaddr *)&sin,&i);
965 if (listen(s, 1) < 0) {
969 if (sin.sin4.sin_family == AF_INET) {
971 a = ntohl(sin.sin4.sin_addr.s_addr);
972 i = cmd(ftp, "PORT %d,%d,%d,%d,%d,%d",
977 (ntohs(sin.sin4.sin_port) >> 8) & 0xff,
978 ntohs(sin.sin4.sin_port) & 0xff);
979 if (check_code(ftp, i, FTP_PORT_HAPPY)) {
984 #define UC(b) (((int)b)&0xff)
986 char hname[INET6_ADDRSTRLEN];
988 sin.sin6.sin6_scope_id = 0;
989 if (getnameinfo((struct sockaddr *)&sin, sin.sin6.sin6_len,
990 hname, sizeof(hname),
991 NULL, 0, NI_NUMERICHOST) != 0) {
994 i = cmd(ftp, "EPRT |%d|%s|%d|", 2, hname,
995 htons(sin.sin6.sin6_port));
996 if (check_code(ftp, i, FTP_PORT_HAPPY)) {
998 a = (char *)&sin.sin6.sin6_addr;
1000 "LPRT %d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d,%d",
1002 UC(a[0]),UC(a[1]),UC(a[2]),UC(a[3]),
1003 UC(a[4]),UC(a[5]),UC(a[6]),UC(a[7]),
1004 UC(a[8]),UC(a[9]),UC(a[10]),UC(a[11]),
1005 UC(a[12]),UC(a[13]),UC(a[14]),UC(a[15]),
1007 (ntohs(sin.sin4.sin_port) >> 8) & 0xff,
1008 ntohs(sin.sin4.sin_port) & 0xff);
1009 if (check_code(ftp, i, FTP_PORT_HAPPY)) {
1015 if (seekto && *seekto) {
1016 i = cmd(ftp, "REST %d", *seekto);
1017 if (i < 0 || FTP_TIMEOUT(i)) {
1025 i = cmd(ftp, "%s %s", operation, file);
1026 if (i < 0 || i > 299) {
1031 fd = accept(s, 0, 0);
1038 *fp = fdopen(fd, mode);
1047 ai_unmapped(struct addrinfo *ai)
1049 struct sockaddr_in6 *sin6;
1050 struct sockaddr_in sin;
1052 if (ai->ai_family != AF_INET6)
1054 if (ai->ai_addrlen != sizeof(struct sockaddr_in6) ||
1055 sizeof(sin) > ai->ai_addrlen)
1057 sin6 = (struct sockaddr_in6 *)ai->ai_addr;
1058 if (!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr))
1061 memset(&sin, 0, sizeof(sin));
1062 sin.sin_family = AF_INET;
1063 sin.sin_len = sizeof(struct sockaddr_in);
1064 memcpy(&sin.sin_addr, &sin6->sin6_addr.s6_addr[12],
1065 sizeof(sin.sin_addr));
1066 sin.sin_port = sin6->sin6_port;
1068 ai->ai_family = AF_INET;
1069 memcpy(ai->ai_addr, &sin, sin.sin_len);
1070 ai->ai_addrlen = sin.sin_len;