2 * nanoftp.c: basic FTP client support
11 #define HAVE_SYS_SOCKET_H
12 #define HAVE_NETINET_IN_H
14 #define HAVE_SYS_TIME_H
22 #ifdef LIBXML_FTP_ENABLED
31 #ifdef HAVE_SYS_SOCKET_H
32 #include <sys/socket.h>
34 #ifdef HAVE_NETINET_IN_H
35 #include <netinet/in.h>
37 #ifdef HAVE_ARPA_INET_H
38 #include <arpa/inet.h>
49 #ifdef HAVE_SYS_TIME_H
52 #ifdef HAVE_SYS_SELECT_H
53 #include <sys/select.h>
59 #include <libxml/xmlmemory.h>
60 #include <libxml/parser.h>
61 #include <libxml/xmlerror.h>
62 #include <libxml/uri.h>
63 #include <libxml/nanoftp.h>
64 #include <libxml/globals.h>
66 /* #define DEBUG_FTP 1 */
74 * A couple portability macros
77 #define closesocket(s) close(s)
80 #if defined(VMS) || defined(__VMS)
81 #define SOCKLEN_T unsigned int
84 #define FTP_COMMAND_OK 200
85 #define FTP_SYNTAX_ERROR 500
86 #define FTP_GET_PASSWD 331
87 #define FTP_BUF_SIZE 512
89 typedef struct xmlNanoFTPCtxt {
90 char *protocol; /* the protocol name */
91 char *hostname; /* the host name */
92 int port; /* the port */
93 char *path; /* the path within the URL */
94 char *user; /* user string */
95 char *passwd; /* passwd string */
96 struct sockaddr_in ftpAddr; /* the socket address struct */
97 int passive; /* currently we support only passive !!! */
98 SOCKET controlFd; /* the file descriptor for the control socket */
99 SOCKET dataFd; /* the file descriptor for the data socket */
100 int state; /* WRITE / READ / CLOSED */
101 int returnValue; /* the protocol return value */
102 /* buffer for data received from the control connection */
103 char controlBuf[FTP_BUF_SIZE + 1];
106 int controlBufAnswer;
107 } xmlNanoFTPCtxt, *xmlNanoFTPCtxtPtr;
109 static int initialized = 0;
110 static char *proxy = NULL; /* the proxy name if any */
111 static int proxyPort = 0; /* the proxy port if any */
112 static char *proxyUser = NULL; /* user for proxy authentication */
113 static char *proxyPasswd = NULL;/* passwd for proxy authentication */
114 static int proxyType = 0; /* uses TYPE or a@b ? */
119 * Initialize the FTP protocol layer.
120 * Currently it just checks for proxy informations,
121 * and get the hostname
125 xmlNanoFTPInit(void) {
135 if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
140 env = getenv("no_proxy");
143 env = getenv("ftp_proxy");
145 xmlNanoFTPScanProxy(env);
147 env = getenv("FTP_PROXY");
149 xmlNanoFTPScanProxy(env);
152 env = getenv("ftp_proxy_user");
154 proxyUser = xmlMemStrdup(env);
156 env = getenv("ftp_proxy_password");
158 proxyPasswd = xmlMemStrdup(env);
166 * Cleanup the FTP protocol layer. This cleanup proxy informations.
170 xmlNanoFTPCleanup(void) {
175 if (proxyUser != NULL) {
179 if (proxyPasswd != NULL) {
180 xmlFree(proxyPasswd);
192 * @host: the proxy host name
193 * @port: the proxy port
194 * @user: the proxy user name
195 * @passwd: the proxy password
196 * @type: the type of proxy 1 for using SITE, 2 for USER a@b
198 * Setup the FTP proxy informations.
199 * This can also be done by using ftp_proxy ftp_proxy_user and
200 * ftp_proxy_password environment variables.
204 xmlNanoFTPProxy(const char *host, int port, const char *user,
205 const char *passwd, int type) {
208 if (proxyUser != NULL)
210 if (proxyPasswd != NULL)
211 xmlFree(proxyPasswd);
213 proxy = xmlMemStrdup(host);
215 proxyUser = xmlMemStrdup(user);
217 proxyPasswd = xmlMemStrdup(passwd);
224 * @ctx: an FTP context
225 * @URL: The URL used to initialize the context
227 * (Re)Initialize an FTP context by parsing the URL and finding
228 * the protocol host port and path it indicates.
232 xmlNanoFTPScanURL(void *ctx, const char *URL) {
233 xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
234 const char *cur = URL;
239 if (ctxt->protocol != NULL) {
240 xmlFree(ctxt->protocol);
241 ctxt->protocol = NULL;
243 if (ctxt->hostname != NULL) {
244 xmlFree(ctxt->hostname);
245 ctxt->hostname = NULL;
247 if (ctxt->path != NULL) {
251 if (URL == NULL) return;
254 if ((cur[0] == ':') && (cur[1] == '/') && (cur[2] == '/')) {
256 ctxt->protocol = xmlMemStrdup(buf);
261 buf[indx++] = *cur++;
263 if (*cur == 0) return;
266 /* allow user@ and user:pass@ forms */
268 const char *p = strchr(cur, '@');
271 if(cur[0] == ':' || cur[0] == '@') break;
272 buf[indx++] = *cur++;
275 ctxt->user = xmlMemStrdup(buf);
280 if(cur[0] == '@') break;
281 buf[indx++] = *cur++;
284 ctxt->passwd = xmlMemStrdup(buf);
294 ctxt->hostname = xmlMemStrdup(buf);
297 while ((*cur >= '0') && (*cur <= '9')) {
302 if (port != 0) ctxt->port = port;
303 while ((cur[0] != '/') && (*cur != 0))
307 if ((*cur == '/') || (*cur == 0)) {
309 ctxt->hostname = xmlMemStrdup(buf);
313 buf[indx++] = *cur++;
316 ctxt->path = xmlMemStrdup("/");
321 buf[indx++] = *cur++;
323 ctxt->path = xmlMemStrdup(buf);
328 * xmlNanoFTPUpdateURL:
329 * @ctx: an FTP context
330 * @URL: The URL used to update the context
332 * Update an FTP context by parsing the URL and finding
333 * new path it indicates. If there is an error in the
334 * protocol, hostname, port or other information, the
335 * error is raised. It indicates a new connection has to
338 * Returns 0 if Ok, -1 in case of error (other host).
342 xmlNanoFTPUpdateURL(void *ctx, const char *URL) {
343 xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
344 const char *cur = URL;
353 if (ctxt->protocol == NULL)
355 if (ctxt->hostname == NULL)
359 if ((cur[0] == ':') && (cur[1] == '/') && (cur[2] == '/')) {
361 if (strcmp(ctxt->protocol, buf))
367 buf[indx++] = *cur++;
376 if (strcmp(ctxt->hostname, buf))
380 while ((*cur >= '0') && (*cur <= '9')) {
385 if (port != ctxt->port)
387 while ((cur[0] != '/') && (*cur != 0))
391 if ((*cur == '/') || (*cur == 0)) {
393 if (strcmp(ctxt->hostname, buf))
398 buf[indx++] = *cur++;
400 if (ctxt->path != NULL) {
406 ctxt->path = xmlMemStrdup("/");
411 buf[indx++] = *cur++;
413 ctxt->path = xmlMemStrdup(buf);
419 * xmlNanoFTPScanProxy:
420 * @URL: The proxy URL used to initialize the proxy context
422 * (Re)Initialize the FTP Proxy context by parsing the URL and finding
423 * the protocol host port it indicates.
424 * Should be like ftp://myproxy/ or ftp://myproxy:3128/
425 * A NULL URL cleans up proxy informations.
429 xmlNanoFTPScanProxy(const char *URL) {
430 const char *cur = URL;
439 if (proxyPort != 0) {
444 xmlGenericError(xmlGenericErrorContext, "Removing FTP proxy info\n");
446 xmlGenericError(xmlGenericErrorContext, "Using FTP proxy %s\n", URL);
448 if (URL == NULL) return;
451 if ((cur[0] == ':') && (cur[1] == '/') && (cur[2] == '/')) {
457 buf[indx++] = *cur++;
459 if (*cur == 0) return;
465 proxy = xmlMemStrdup(buf);
468 while ((*cur >= '0') && (*cur <= '9')) {
473 if (port != 0) proxyPort = port;
474 while ((cur[0] != '/') && (*cur != 0))
478 if ((*cur == '/') || (*cur == 0)) {
480 proxy = xmlMemStrdup(buf);
484 buf[indx++] = *cur++;
490 * @URL: The URL used to initialize the context
492 * Allocate and initialize a new FTP context.
494 * Returns an FTP context or NULL in case of error.
498 xmlNanoFTPNewCtxt(const char *URL) {
499 xmlNanoFTPCtxtPtr ret;
502 ret = (xmlNanoFTPCtxtPtr) xmlMalloc(sizeof(xmlNanoFTPCtxt));
503 if (ret == NULL) return(NULL);
505 memset(ret, 0, sizeof(xmlNanoFTPCtxt));
508 ret->returnValue = 0;
509 ret->controlBufIndex = 0;
510 ret->controlBufUsed = 0;
513 unescaped = xmlURIUnescapeString(URL, 0, NULL);
514 if (unescaped != NULL)
515 xmlNanoFTPScanURL(ret, unescaped);
516 else if (URL != NULL)
517 xmlNanoFTPScanURL(ret, URL);
524 * xmlNanoFTPFreeCtxt:
525 * @ctx: an FTP context
527 * Frees the context after closing the connection.
531 xmlNanoFTPFreeCtxt(void * ctx) {
532 xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
533 if (ctxt == NULL) return;
534 if (ctxt->hostname != NULL) xmlFree(ctxt->hostname);
535 if (ctxt->protocol != NULL) xmlFree(ctxt->protocol);
536 if (ctxt->path != NULL) xmlFree(ctxt->path);
538 if (ctxt->controlFd >= 0) closesocket(ctxt->controlFd);
539 ctxt->controlFd = -1;
540 ctxt->controlBufIndex = -1;
541 ctxt->controlBufUsed = -1;
546 * xmlNanoFTPParseResponse:
547 * @buf: the buffer containing the response
548 * @len: the buffer length
550 * Parsing of the server answer, we just extract the code.
552 * returns 0 for errors
553 * +XXX for last line of response
554 * -XXX for response to be continued
557 xmlNanoFTPParseResponse(char *buf, int len) {
560 if (len < 3) return(-1);
561 if ((*buf >= '0') && (*buf <= '9'))
562 val = val * 10 + (*buf - '0');
566 if ((*buf >= '0') && (*buf <= '9'))
567 val = val * 10 + (*buf - '0');
571 if ((*buf >= '0') && (*buf <= '9'))
572 val = val * 10 + (*buf - '0');
583 * @ctx: an FTP context
585 * Read more information from the FTP control connection
586 * Returns the number of bytes read, < 0 indicates an error
589 xmlNanoFTPGetMore(void *ctx) {
590 xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
594 if ((ctxt->controlBufIndex < 0) || (ctxt->controlBufIndex > FTP_BUF_SIZE)) {
596 xmlGenericError(xmlGenericErrorContext,
597 "xmlNanoFTPGetMore : controlBufIndex = %d\n",
598 ctxt->controlBufIndex);
603 if ((ctxt->controlBufUsed < 0) || (ctxt->controlBufUsed > FTP_BUF_SIZE)) {
605 xmlGenericError(xmlGenericErrorContext,
606 "xmlNanoFTPGetMore : controlBufUsed = %d\n",
607 ctxt->controlBufUsed);
611 if (ctxt->controlBufIndex > ctxt->controlBufUsed) {
613 xmlGenericError(xmlGenericErrorContext,
614 "xmlNanoFTPGetMore : controlBufIndex > controlBufUsed %d > %d\n",
615 ctxt->controlBufIndex, ctxt->controlBufUsed);
621 * First pack the control buffer
623 if (ctxt->controlBufIndex > 0) {
624 memmove(&ctxt->controlBuf[0], &ctxt->controlBuf[ctxt->controlBufIndex],
625 ctxt->controlBufUsed - ctxt->controlBufIndex);
626 ctxt->controlBufUsed -= ctxt->controlBufIndex;
627 ctxt->controlBufIndex = 0;
629 size = FTP_BUF_SIZE - ctxt->controlBufUsed;
632 xmlGenericError(xmlGenericErrorContext,
633 "xmlNanoFTPGetMore : buffer full %d \n", ctxt->controlBufUsed);
639 * Read the amount left on the control connection
641 if ((len = recv(ctxt->controlFd, &ctxt->controlBuf[ctxt->controlBufIndex],
643 closesocket(ctxt->controlFd); ctxt->controlFd = -1;
644 ctxt->controlFd = -1;
648 xmlGenericError(xmlGenericErrorContext,
649 "xmlNanoFTPGetMore : read %d [%d - %d]\n", len,
650 ctxt->controlBufUsed, ctxt->controlBufUsed + len);
652 ctxt->controlBufUsed += len;
653 ctxt->controlBuf[ctxt->controlBufUsed] = 0;
659 * xmlNanoFTPReadResponse:
660 * @ctx: an FTP context
662 * Read the response from the FTP server after a command.
663 * Returns the code number
666 xmlNanoFTPReadResponse(void *ctx) {
667 xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
670 int res = -1, cur = -1;
674 * Assumes everything up to controlBuf[controlBufIndex] has been read
677 len = xmlNanoFTPGetMore(ctx);
681 if ((ctxt->controlBufUsed == 0) && (len == 0)) {
684 ptr = &ctxt->controlBuf[ctxt->controlBufIndex];
685 end = &ctxt->controlBuf[ctxt->controlBufUsed];
688 xmlGenericError(xmlGenericErrorContext,
689 "\n<<<\n%s\n--\n", ptr);
692 cur = xmlNanoFTPParseResponse(ptr, end - ptr);
695 * Successfully scanned the control code, scratch
696 * till the end of the line, but keep the index to be
697 * able to analyze the result if needed.
701 ctxt->controlBufAnswer = ptr - ctxt->controlBuf;
702 while ((ptr < end) && (*ptr != '\n')) ptr++;
703 if (*ptr == '\n') ptr++;
704 if (*ptr == '\r') ptr++;
707 while ((ptr < end) && (*ptr != '\n')) ptr++;
709 ctxt->controlBufIndex = ctxt->controlBufUsed;
712 if (*ptr != '\r') ptr++;
715 if (res < 0) goto get_more;
716 ctxt->controlBufIndex = ptr - ctxt->controlBuf;
718 ptr = &ctxt->controlBuf[ctxt->controlBufIndex];
719 xmlGenericError(xmlGenericErrorContext, "\n---\n%s\n--\n", ptr);
723 xmlGenericError(xmlGenericErrorContext, "Got %d\n", res);
729 * xmlNanoFTPGetResponse:
730 * @ctx: an FTP context
732 * Get the response from the FTP server after a command.
733 * Returns the code number
737 xmlNanoFTPGetResponse(void *ctx) {
740 res = xmlNanoFTPReadResponse(ctx);
746 * xmlNanoFTPCheckResponse:
747 * @ctx: an FTP context
749 * Check if there is a response from the FTP server after a command.
750 * Returns the code number, or 0
754 xmlNanoFTPCheckResponse(void *ctx) {
755 xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
762 FD_SET(ctxt->controlFd, &rfd);
763 switch(select(ctxt->controlFd + 1, &rfd, NULL, NULL, &tv)) {
774 return(xmlNanoFTPReadResponse(ctx));
778 * Send the user authentication
782 xmlNanoFTPSendUser(void *ctx) {
783 xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
788 if (ctxt->user == NULL)
789 snprintf(buf, sizeof(buf), "USER anonymous\r\n");
791 snprintf(buf, sizeof(buf), "USER %s\r\n", ctxt->user);
792 buf[sizeof(buf) - 1] = 0;
795 xmlGenericError(xmlGenericErrorContext, "%s", buf);
797 res = send(ctxt->controlFd, buf, len, 0);
798 if (res < 0) return(res);
803 * Send the password authentication
807 xmlNanoFTPSendPasswd(void *ctx) {
808 xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
813 if (ctxt->passwd == NULL)
814 snprintf(buf, sizeof(buf), "PASS anonymous@\r\n");
816 snprintf(buf, sizeof(buf), "PASS %s\r\n", ctxt->passwd);
817 buf[sizeof(buf) - 1] = 0;
820 xmlGenericError(xmlGenericErrorContext, "%s", buf);
822 res = send(ctxt->controlFd, buf, len, 0);
823 if (res < 0) return(res);
829 * @ctx: an FTP context
831 * Send a QUIT command to the server
833 * Returns -1 in case of error, 0 otherwise
838 xmlNanoFTPQuit(void *ctx) {
839 xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
844 snprintf(buf, sizeof(buf), "QUIT\r\n");
847 xmlGenericError(xmlGenericErrorContext, "%s", buf); /* Just to be consistent, even though we know it can't have a % in it */
849 res = send(ctxt->controlFd, buf, len, 0);
855 * @ctx: an FTP context
857 * Tries to open a control connection
859 * Returns -1 in case of error, 0 otherwise
863 xmlNanoFTPConnect(void *ctx) {
864 xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
871 if (ctxt->hostname == NULL)
875 * do the blocking DNS query.
878 hp = gethostbyname(proxy);
880 hp = gethostbyname(ctxt->hostname);
887 memset(&ctxt->ftpAddr, 0, sizeof(ctxt->ftpAddr));
888 ctxt->ftpAddr.sin_family = AF_INET;
889 memcpy(&ctxt->ftpAddr.sin_addr, hp->h_addr_list[0], hp->h_length);
897 ctxt->ftpAddr.sin_port = htons(port);
898 ctxt->controlFd = socket(AF_INET, SOCK_STREAM, 0);
899 if (ctxt->controlFd < 0)
905 if (connect(ctxt->controlFd, (struct sockaddr *) &ctxt->ftpAddr,
906 sizeof(struct sockaddr_in)) < 0) {
907 closesocket(ctxt->controlFd); ctxt->controlFd = -1;
908 ctxt->controlFd = -1;
913 * Wait for the HELLO from the server.
915 res = xmlNanoFTPGetResponse(ctxt);
917 closesocket(ctxt->controlFd); ctxt->controlFd = -1;
918 ctxt->controlFd = -1;
923 * State diagram for the login operation on the FTP server
928 * +---+ USER +---+------------->+---+
929 * | B |---------->| W | 2 ---->| E |
930 * +---+ +---+------ | -->+---+
933 * -------------- ----- | | |
939 * +---+ PASS +---+ 2 | ------>+---+
940 * | |---------->| W |------------->| S |
941 * +---+ +---+ ---------->+---+
944 * -------------- -------- |
950 * +---+ ACCT +---+-- | ----->+---+
951 * | |---------->| W | 4,5 -------->| F |
952 * +---+ +---+------------->+---+
954 * Of course in case of using a proxy this get really nasty and is not
955 * standardized at all :-(
961 if (proxyUser != NULL) {
965 snprintf(buf, sizeof(buf), "USER %s\r\n", proxyUser);
966 buf[sizeof(buf) - 1] = 0;
969 xmlGenericError(xmlGenericErrorContext, "%s", buf);
971 res = send(ctxt->controlFd, buf, len, 0);
973 closesocket(ctxt->controlFd);
974 ctxt->controlFd = -1;
977 res = xmlNanoFTPGetResponse(ctxt);
980 if (proxyPasswd == NULL)
983 if (proxyPasswd != NULL)
984 snprintf(buf, sizeof(buf), "PASS %s\r\n", proxyPasswd);
986 snprintf(buf, sizeof(buf), "PASS anonymous@\r\n");
987 buf[sizeof(buf) - 1] = 0;
990 xmlGenericError(xmlGenericErrorContext, "%s", buf);
992 res = send(ctxt->controlFd, buf, len, 0);
994 closesocket(ctxt->controlFd);
995 ctxt->controlFd = -1;
998 res = xmlNanoFTPGetResponse(ctxt);
1000 closesocket(ctxt->controlFd);
1001 ctxt->controlFd = -1;
1011 closesocket(ctxt->controlFd);
1012 ctxt->controlFd = -1;
1018 * We assume we don't need more authentication to the proxy
1019 * and that it succeeded :-\
1021 switch (proxyType) {
1023 /* we will try in sequence */
1025 /* Using SITE command */
1026 snprintf(buf, sizeof(buf), "SITE %s\r\n", ctxt->hostname);
1027 buf[sizeof(buf) - 1] = 0;
1030 xmlGenericError(xmlGenericErrorContext, "%s", buf);
1032 res = send(ctxt->controlFd, buf, len, 0);
1034 closesocket(ctxt->controlFd); ctxt->controlFd = -1;
1035 ctxt->controlFd = -1;
1038 res = xmlNanoFTPGetResponse(ctxt);
1040 /* we assume it worked :-\ 1 is error for SITE command */
1044 if (proxyType == 1) {
1045 closesocket(ctxt->controlFd); ctxt->controlFd = -1;
1046 ctxt->controlFd = -1;
1050 /* USER user@host command */
1051 if (ctxt->user == NULL)
1052 snprintf(buf, sizeof(buf), "USER anonymous@%s\r\n",
1055 snprintf(buf, sizeof(buf), "USER %s@%s\r\n",
1056 ctxt->user, ctxt->hostname);
1057 buf[sizeof(buf) - 1] = 0;
1060 xmlGenericError(xmlGenericErrorContext, "%s", buf);
1062 res = send(ctxt->controlFd, buf, len, 0);
1064 closesocket(ctxt->controlFd); ctxt->controlFd = -1;
1065 ctxt->controlFd = -1;
1068 res = xmlNanoFTPGetResponse(ctxt);
1069 if ((res == 1) || (res == 2)) {
1070 /* we assume it worked :-\ */
1074 if (ctxt->passwd == NULL)
1075 snprintf(buf, sizeof(buf), "PASS anonymous@\r\n");
1077 snprintf(buf, sizeof(buf), "PASS %s\r\n", ctxt->passwd);
1078 buf[sizeof(buf) - 1] = 0;
1081 xmlGenericError(xmlGenericErrorContext, "%s", buf);
1083 res = send(ctxt->controlFd, buf, len, 0);
1085 closesocket(ctxt->controlFd); ctxt->controlFd = -1;
1086 ctxt->controlFd = -1;
1089 res = xmlNanoFTPGetResponse(ctxt);
1090 if ((res == 1) || (res == 2)) {
1091 /* we assume it worked :-\ */
1095 if (proxyType == 2) {
1096 closesocket(ctxt->controlFd); ctxt->controlFd = -1;
1097 ctxt->controlFd = -1;
1102 * If you need support for other Proxy authentication scheme
1103 * send the code or at least the sequence in use.
1106 closesocket(ctxt->controlFd); ctxt->controlFd = -1;
1107 ctxt->controlFd = -1;
1112 * Non-proxy handling.
1114 res = xmlNanoFTPSendUser(ctxt);
1116 closesocket(ctxt->controlFd); ctxt->controlFd = -1;
1117 ctxt->controlFd = -1;
1120 res = xmlNanoFTPGetResponse(ctxt);
1131 closesocket(ctxt->controlFd); ctxt->controlFd = -1;
1132 ctxt->controlFd = -1;
1135 res = xmlNanoFTPSendPasswd(ctxt);
1137 closesocket(ctxt->controlFd); ctxt->controlFd = -1;
1138 ctxt->controlFd = -1;
1141 res = xmlNanoFTPGetResponse(ctxt);
1146 xmlGenericError(xmlGenericErrorContext,
1147 "FTP server asking for ACCNT on anonymous\n");
1153 closesocket(ctxt->controlFd); ctxt->controlFd = -1;
1154 ctxt->controlFd = -1;
1162 * xmlNanoFTPConnectTo:
1163 * @server: an FTP server name
1164 * @port: the port (use 21 if 0)
1166 * Tries to open a control connection to the given server/port
1168 * Returns an fTP context or NULL if it failed
1172 xmlNanoFTPConnectTo(const char *server, int port) {
1173 xmlNanoFTPCtxtPtr ctxt;
1179 ctxt = (xmlNanoFTPCtxtPtr) xmlNanoFTPNewCtxt(NULL);
1180 ctxt->hostname = xmlMemStrdup(server);
1183 res = xmlNanoFTPConnect(ctxt);
1185 xmlNanoFTPFreeCtxt(ctxt);
1193 * @ctx: an FTP context
1194 * @directory: a directory on the server
1196 * Tries to change the remote directory
1198 * Returns -1 incase of error, 1 if CWD worked, 0 if it failed
1202 xmlNanoFTPCwd(void *ctx, char *directory) {
1203 xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
1209 * Expected response code for CWD:
1213 * 500, 501, 502, 421, 530, 550
1215 snprintf(buf, sizeof(buf), "CWD %s\r\n", directory);
1216 buf[sizeof(buf) - 1] = 0;
1219 xmlGenericError(xmlGenericErrorContext, "%s", buf);
1221 res = send(ctxt->controlFd, buf, len, 0);
1222 if (res < 0) return(res);
1223 res = xmlNanoFTPGetResponse(ctxt);
1227 if (res == 2) return(1);
1235 * xmlNanoFTPGetConnection:
1236 * @ctx: an FTP context
1238 * Try to open a data connection to the server. Currently only
1239 * passive mode is supported.
1241 * Returns -1 incase of error, 0 otherwise
1245 xmlNanoFTPGetConnection(void *ctx) {
1246 xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
1247 char buf[200], *cur;
1250 unsigned char ad[6], *adp, *portp;
1251 unsigned int temp[6];
1252 struct sockaddr_in dataAddr;
1253 SOCKLEN_T dataAddrLen;
1255 ctxt->dataFd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1256 if (ctxt->dataFd < 0) {
1257 xmlGenericError(xmlGenericErrorContext,
1258 "xmlNanoFTPGetConnection: failed to create socket\n");
1261 dataAddrLen = sizeof(dataAddr);
1262 memset(&dataAddr, 0, dataAddrLen);
1263 dataAddr.sin_family = AF_INET;
1265 if (ctxt->passive) {
1266 snprintf(buf, sizeof(buf), "PASV\r\n");
1269 xmlGenericError(xmlGenericErrorContext, "%s", buf);
1271 res = send(ctxt->controlFd, buf, len, 0);
1273 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1276 res = xmlNanoFTPReadResponse(ctx);
1279 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1283 * retry with an active connection
1285 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1289 cur = &ctxt->controlBuf[ctxt->controlBufAnswer];
1290 while (((*cur < '0') || (*cur > '9')) && *cur != '\0') cur++;
1291 if (sscanf(cur, "%u,%u,%u,%u,%u,%u", &temp[0], &temp[1], &temp[2],
1292 &temp[3], &temp[4], &temp[5]) != 6) {
1293 xmlGenericError(xmlGenericErrorContext,
1294 "Invalid answer to PASV\n");
1295 if (ctxt->dataFd != -1) {
1296 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1300 for (i=0; i<6; i++) ad[i] = (unsigned char) (temp[i] & 0xff);
1301 memcpy(&dataAddr.sin_addr, &ad[0], 4);
1302 memcpy(&dataAddr.sin_port, &ad[4], 2);
1303 if (connect(ctxt->dataFd, (struct sockaddr *) &dataAddr, dataAddrLen) < 0) {
1304 xmlGenericError(xmlGenericErrorContext,
1305 "Failed to create a data connection\n");
1306 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1310 getsockname(ctxt->dataFd, (struct sockaddr *) &dataAddr, &dataAddrLen);
1311 dataAddr.sin_port = 0;
1312 if (bind(ctxt->dataFd, (struct sockaddr *) &dataAddr, dataAddrLen) < 0) {
1313 xmlGenericError(xmlGenericErrorContext,
1314 "Failed to bind a port\n");
1315 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1318 getsockname(ctxt->dataFd, (struct sockaddr *) &dataAddr, &dataAddrLen);
1320 if (listen(ctxt->dataFd, 1) < 0) {
1321 xmlGenericError(xmlGenericErrorContext,
1322 "Could not listen on port %d\n",
1323 ntohs(dataAddr.sin_port));
1324 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1327 adp = (unsigned char *) &dataAddr.sin_addr;
1328 portp = (unsigned char *) &dataAddr.sin_port;
1329 snprintf(buf, sizeof(buf), "PORT %d,%d,%d,%d,%d,%d\r\n",
1330 adp[0] & 0xff, adp[1] & 0xff, adp[2] & 0xff, adp[3] & 0xff,
1331 portp[0] & 0xff, portp[1] & 0xff);
1332 buf[sizeof(buf) - 1] = 0;
1335 xmlGenericError(xmlGenericErrorContext, "%s", buf);
1338 res = send(ctxt->controlFd, buf, len, 0);
1340 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1343 res = xmlNanoFTPGetResponse(ctxt);
1345 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1349 return(ctxt->dataFd);
1354 * xmlNanoFTPCloseConnection:
1355 * @ctx: an FTP context
1357 * Close the data connection from the server
1359 * Returns -1 incase of error, 0 otherwise
1363 xmlNanoFTPCloseConnection(void *ctx) {
1364 xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
1369 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1373 FD_SET(ctxt->controlFd, &rfd);
1375 FD_SET(ctxt->controlFd, &efd);
1376 res = select(ctxt->controlFd + 1, &rfd, NULL, &efd, &tv);
1381 closesocket(ctxt->controlFd); ctxt->controlFd = -1;
1386 xmlGenericError(xmlGenericErrorContext,
1387 "xmlNanoFTPCloseConnection: timeout\n");
1389 closesocket(ctxt->controlFd); ctxt->controlFd = -1;
1391 res = xmlNanoFTPGetResponse(ctxt);
1393 closesocket(ctxt->controlFd); ctxt->controlFd = -1;
1401 * xmlNanoFTPParseList:
1402 * @list: some data listing received from the server
1403 * @callback: the user callback
1404 * @userData: the user callback data
1406 * Parse at most one entry from the listing.
1408 * Returns -1 incase of error, the length of data parsed otherwise
1412 xmlNanoFTPParseList(const char *list, ftpListCallback callback, void *userData) {
1413 const char *cur = list;
1423 unsigned long size = 0;
1427 if (!strncmp(cur, "total", 5)) {
1429 while (*cur == ' ') cur++;
1430 while ((*cur >= '0') && (*cur <= '9'))
1431 links = (links * 10) + (*cur++ - '0');
1432 while ((*cur == ' ') || (*cur == '\n') || (*cur == '\r'))
1435 } else if (*list == '+') {
1438 while ((*cur == ' ') || (*cur == '\n') || (*cur == '\r'))
1440 if (*cur == 0) return(0);
1442 while (*cur != ' ') {
1446 if (*cur == 0) return(0);
1449 while (*cur == ' ') cur++;
1450 if (*cur == 0) return(0);
1451 while ((*cur >= '0') && (*cur <= '9'))
1452 links = (links * 10) + (*cur++ - '0');
1453 while (*cur == ' ') cur++;
1454 if (*cur == 0) return(0);
1456 while (*cur != ' ') {
1460 if (*cur == 0) return(0);
1463 while (*cur == ' ') cur++;
1464 if (*cur == 0) return(0);
1466 while (*cur != ' ') {
1470 if (*cur == 0) return(0);
1473 while (*cur == ' ') cur++;
1474 if (*cur == 0) return(0);
1475 while ((*cur >= '0') && (*cur <= '9'))
1476 size = (size * 10) + (*cur++ - '0');
1477 while (*cur == ' ') cur++;
1478 if (*cur == 0) return(0);
1480 while (*cur != ' ') {
1484 if (*cur == 0) return(0);
1487 while (*cur == ' ') cur++;
1488 if (*cur == 0) return(0);
1489 while ((*cur >= '0') && (*cur <= '9'))
1490 day = (day * 10) + (*cur++ - '0');
1491 while (*cur == ' ') cur++;
1492 if (*cur == 0) return(0);
1493 if ((cur[1] == 0) || (cur[2] == 0)) return(0);
1494 if ((cur[1] == ':') || (cur[2] == ':')) {
1495 while ((*cur >= '0') && (*cur <= '9'))
1496 hour = (hour * 10) + (*cur++ - '0');
1497 if (*cur == ':') cur++;
1498 while ((*cur >= '0') && (*cur <= '9'))
1499 minute = (minute * 10) + (*cur++ - '0');
1501 while ((*cur >= '0') && (*cur <= '9'))
1502 year = (year * 10) + (*cur++ - '0');
1504 while (*cur == ' ') cur++;
1505 if (*cur == 0) return(0);
1507 while ((*cur != '\n') && (*cur != '\r')) {
1509 filename[i++] = *cur;
1511 if (*cur == 0) return(0);
1514 if ((*cur != '\n') && (*cur != '\r'))
1516 while ((*cur == '\n') || (*cur == '\r'))
1519 if (callback != NULL) {
1520 callback(userData, filename, attrib, owner, group, size, links,
1521 year, month, day, hour, minute);
1528 * @ctx: an FTP context
1529 * @callback: the user callback
1530 * @userData: the user callback data
1531 * @filename: optional files to list
1533 * Do a listing on the server. All files info are passed back
1536 * Returns -1 incase of error, 0 otherwise
1540 xmlNanoFTPList(void *ctx, ftpListCallback callback, void *userData,
1542 xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
1549 if (filename == NULL) {
1550 if (xmlNanoFTPCwd(ctxt, ctxt->path) < 1)
1552 ctxt->dataFd = xmlNanoFTPGetConnection(ctxt);
1553 if (ctxt->dataFd == -1)
1555 snprintf(buf, sizeof(buf), "LIST -L\r\n");
1557 if (filename[0] != '/') {
1558 if (xmlNanoFTPCwd(ctxt, ctxt->path) < 1)
1561 ctxt->dataFd = xmlNanoFTPGetConnection(ctxt);
1562 if (ctxt->dataFd == -1)
1564 snprintf(buf, sizeof(buf), "LIST -L %s\r\n", filename);
1566 buf[sizeof(buf) - 1] = 0;
1569 xmlGenericError(xmlGenericErrorContext, "%s", buf);
1571 res = send(ctxt->controlFd, buf, len, 0);
1573 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1576 res = xmlNanoFTPReadResponse(ctxt);
1578 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1586 FD_SET(ctxt->dataFd, &rfd);
1588 FD_SET(ctxt->dataFd, &efd);
1589 res = select(ctxt->dataFd + 1, &rfd, NULL, &efd, &tv);
1594 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1598 res = xmlNanoFTPCheckResponse(ctxt);
1600 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1605 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1612 if ((len = recv(ctxt->dataFd, &buf[indx], sizeof(buf) - (indx + 1), 0)) < 0) {
1616 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1621 write(1, &buf[indx], len);
1627 res = xmlNanoFTPParseList(&buf[base], callback, userData);
1631 memmove(&buf[0], &buf[base], indx - base);
1634 xmlNanoFTPCloseConnection(ctxt);
1639 * xmlNanoFTPGetSocket:
1640 * @ctx: an FTP context
1641 * @filename: the file to retrieve (or NULL if path is in context).
1643 * Initiate fetch of the given file from the server.
1645 * Returns the socket for the data connection, or <0 in case of error
1650 xmlNanoFTPGetSocket(void *ctx, const char *filename) {
1651 xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
1654 if ((filename == NULL) && (ctxt->path == NULL))
1656 ctxt->dataFd = xmlNanoFTPGetConnection(ctxt);
1657 if (ctxt->dataFd == -1)
1660 snprintf(buf, sizeof(buf), "TYPE I\r\n");
1663 xmlGenericError(xmlGenericErrorContext, "%s", buf);
1665 res = send(ctxt->controlFd, buf, len, 0);
1667 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1670 res = xmlNanoFTPReadResponse(ctxt);
1672 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1675 if (filename == NULL)
1676 snprintf(buf, sizeof(buf), "RETR %s\r\n", ctxt->path);
1678 snprintf(buf, sizeof(buf), "RETR %s\r\n", filename);
1679 buf[sizeof(buf) - 1] = 0;
1682 xmlGenericError(xmlGenericErrorContext, "%s", buf);
1684 res = send(ctxt->controlFd, buf, len, 0);
1686 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1689 res = xmlNanoFTPReadResponse(ctxt);
1691 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1694 return(ctxt->dataFd);
1699 * @ctx: an FTP context
1700 * @callback: the user callback
1701 * @userData: the user callback data
1702 * @filename: the file to retrieve
1704 * Fetch the given file from the server. All data are passed back
1705 * in the callbacks. The last callback has a size of 0 block.
1707 * Returns -1 incase of error, 0 otherwise
1711 xmlNanoFTPGet(void *ctx, ftpDataCallback callback, void *userData,
1712 const char *filename) {
1713 xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
1719 if ((filename == NULL) && (ctxt->path == NULL))
1721 if (callback == NULL)
1723 if (xmlNanoFTPGetSocket(ctxt, filename) < 0)
1730 FD_SET(ctxt->dataFd, &rfd);
1731 res = select(ctxt->dataFd + 1, &rfd, NULL, NULL, &tv);
1736 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1740 res = xmlNanoFTPCheckResponse(ctxt);
1742 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1747 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1753 if ((len = recv(ctxt->dataFd, buf, sizeof(buf), 0)) < 0) {
1754 callback(userData, buf, len);
1755 closesocket(ctxt->dataFd); ctxt->dataFd = -1;
1758 callback(userData, buf, len);
1761 return(xmlNanoFTPCloseConnection(ctxt));
1766 * @ctx: the FTP context
1768 * @len: the buffer length
1770 * This function tries to read @len bytes from the existing FTP connection
1771 * and saves them in @dest. This is a blocking call.
1773 * Returns the number of byte read. 0 is an indication of an end of connection.
1774 * -1 indicates a parameter error.
1777 xmlNanoFTPRead(void *ctx, void *dest, int len) {
1778 xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
1780 if (ctx == NULL) return(-1);
1781 if (ctxt->dataFd < 0) return(0);
1782 if (dest == NULL) return(-1);
1783 if (len <= 0) return(0);
1785 len = recv(ctxt->dataFd, dest, len, 0);
1787 xmlGenericError(xmlGenericErrorContext, "Recvd %d bytes\n", len);
1790 xmlNanoFTPCloseConnection(ctxt);
1797 * @URL: the URL to the resource
1799 * Start to fetch the given ftp:// resource
1801 * Returns an FTP context, or NULL
1805 xmlNanoFTPOpen(const char *URL) {
1806 xmlNanoFTPCtxtPtr ctxt;
1810 if (URL == NULL) return(NULL);
1811 if (strncmp("ftp://", URL, 6)) return(NULL);
1813 ctxt = (xmlNanoFTPCtxtPtr) xmlNanoFTPNewCtxt(URL);
1814 if (ctxt == NULL) return(NULL);
1815 if (xmlNanoFTPConnect(ctxt) < 0) {
1816 xmlNanoFTPFreeCtxt(ctxt);
1819 sock = xmlNanoFTPGetSocket(ctxt, ctxt->path);
1821 xmlNanoFTPFreeCtxt(ctxt);
1829 * @ctx: an FTP context
1831 * Close the connection and both control and transport
1833 * Returns -1 incase of error, 0 otherwise
1837 xmlNanoFTPClose(void *ctx) {
1838 xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
1843 if (ctxt->dataFd >= 0) {
1844 closesocket(ctxt->dataFd);
1847 if (ctxt->controlFd >= 0) {
1848 xmlNanoFTPQuit(ctxt);
1849 closesocket(ctxt->controlFd);
1850 ctxt->controlFd = -1;
1852 xmlNanoFTPFreeCtxt(ctxt);
1857 /************************************************************************
1859 * Basic test in Standalone mode *
1861 ************************************************************************/
1863 void ftpList(void *userData, const char *filename, const char* attrib,
1864 const char *owner, const char *group, unsigned long size, int links,
1865 int year, const char *month, int day, int hour, int minute) {
1866 xmlGenericError(xmlGenericErrorContext,
1867 "%s %s %s %ld %s\n", attrib, owner, group, size, filename);
1870 void ftpData(void *userData, const char *data, int len) {
1871 if (userData == NULL) return;
1876 fwrite(data, len, 1, userData);
1879 int main(int argc, char **argv) {
1882 char *tstfile = NULL;
1886 ctxt = xmlNanoFTPNewCtxt(argv[1]);
1887 if (xmlNanoFTPConnect(ctxt) < 0) {
1888 xmlGenericError(xmlGenericErrorContext,
1889 "Couldn't connect to %s\n", argv[1]);
1895 ctxt = xmlNanoFTPConnectTo("localhost", 0);
1897 xmlGenericError(xmlGenericErrorContext,
1898 "Couldn't connect to localhost\n");
1901 xmlNanoFTPList(ctxt, ftpList, NULL, tstfile);
1902 output = fopen("/tmp/tstdata", "w");
1903 if (output != NULL) {
1904 if (xmlNanoFTPGet(ctxt, ftpData, (void *) output, tstfile) < 0)
1905 xmlGenericError(xmlGenericErrorContext,
1906 "Failed to get file\n");
1909 xmlNanoFTPClose(ctxt);
1913 #endif /* STANDALONE */
1914 #else /* !LIBXML_FTP_ENABLED */
1917 int main(int argc, char **argv) {
1918 xmlGenericError(xmlGenericErrorContext,
1919 "%s : FTP support not compiled in\n", argv[0]);
1922 #endif /* STANDALONE */
1923 #endif /* LIBXML_FTP_ENABLED */