5bc6555af5ec14fae6085ee2496efc1fb87413fb
[platform/upstream/libxml2.git] / nanoftp.c
1 /*
2  * nanoftp.c: basic FTP client support
3  *
4  *  Reference: RFC 959
5  */
6
7 #ifdef TESTING
8 #define STANDALONE
9 #define HAVE_STDLIB_H
10 #define HAVE_UNISTD_H
11 #define HAVE_SYS_SOCKET_H
12 #define HAVE_NETINET_IN_H
13 #define HAVE_NETDB_H
14 #define HAVE_SYS_TIME_H
15 #else /* TESTING */
16 #define NEED_SOCKETS
17 #endif /* TESTING */
18
19 #define IN_LIBXML
20 #include "libxml.h"
21
22 #ifdef LIBXML_FTP_ENABLED
23 #include <string.h>
24
25 #ifdef HAVE_STDLIB_H
26 #include <stdlib.h>
27 #endif
28 #ifdef HAVE_UNISTD_H
29 #include <unistd.h>
30 #endif
31 #ifdef HAVE_SYS_SOCKET_H
32 #include <sys/socket.h>
33 #endif
34 #ifdef HAVE_NETINET_IN_H
35 #include <netinet/in.h>
36 #endif
37 #ifdef HAVE_ARPA_INET_H
38 #include <arpa/inet.h>
39 #endif
40 #ifdef HAVE_NETDB_H
41 #include <netdb.h>
42 #endif
43 #ifdef HAVE_FCNTL_H
44 #include <fcntl.h>
45 #endif
46 #ifdef HAVE_ERRNO_H
47 #include <errno.h>
48 #endif
49 #ifdef HAVE_SYS_TIME_H
50 #include <sys/time.h>
51 #endif
52 #ifdef HAVE_SYS_SELECT_H
53 #include <sys/select.h>
54 #endif
55 #ifdef HAVE_SYS_SOCKET_H
56 #include <sys/socket.h>
57 #endif
58 #ifdef HAVE_SYS_TYPES_H
59 #include <sys/types.h>
60 #endif
61 #ifdef HAVE_STRINGS_H
62 #include <strings.h>
63 #endif
64
65 #include <libxml/xmlmemory.h>
66 #include <libxml/parser.h>
67 #include <libxml/xmlerror.h>
68 #include <libxml/uri.h>
69 #include <libxml/nanoftp.h>
70 #include <libxml/globals.h>
71
72 /* #define DEBUG_FTP 1  */
73 #ifdef STANDALONE
74 #ifndef DEBUG_FTP
75 #define DEBUG_FTP 1
76 #endif
77 #endif
78
79
80 #if defined(__MINGW32__) || defined(_WIN32_WCE)
81 #ifndef _WINSOCKAPI_
82 #define _WINSOCKAPI_
83 #endif
84 #include <wsockcompat.h>
85 #include <winsock2.h>
86 #undef XML_SOCKLEN_T
87 #define XML_SOCKLEN_T unsigned int
88 #endif
89
90 /**
91  * A couple portability macros
92  */
93 #ifndef _WINSOCKAPI_
94 #if !defined(__BEOS__) || defined(__HAIKU__)
95 #define closesocket(s) close(s)
96 #endif
97 #endif
98
99 #ifdef __BEOS__
100 #ifndef PF_INET
101 #define PF_INET AF_INET
102 #endif
103 #endif
104
105 #ifdef _AIX
106 #ifdef HAVE_BROKEN_SS_FAMILY
107 #define ss_family __ss_family
108 #endif
109 #endif
110
111 #ifndef XML_SOCKLEN_T
112 #define XML_SOCKLEN_T unsigned int
113 #endif
114
115 #define FTP_COMMAND_OK          200
116 #define FTP_SYNTAX_ERROR        500
117 #define FTP_GET_PASSWD          331
118 #define FTP_BUF_SIZE            1024
119
120 #define XML_NANO_MAX_URLBUF     4096
121
122 typedef struct xmlNanoFTPCtxt {
123     char *protocol;     /* the protocol name */
124     char *hostname;     /* the host name */
125     int port;           /* the port */
126     char *path;         /* the path within the URL */
127     char *user;         /* user string */
128     char *passwd;       /* passwd string */
129 #ifdef SUPPORT_IP6
130     struct sockaddr_storage ftpAddr; /* this is large enough to hold IPv6 address*/
131 #else
132     struct sockaddr_in ftpAddr; /* the socket address struct */
133 #endif
134     int passive;        /* currently we support only passive !!! */
135     SOCKET controlFd;   /* the file descriptor for the control socket */
136     SOCKET dataFd;      /* the file descriptor for the data socket */
137     int state;          /* WRITE / READ / CLOSED */
138     int returnValue;    /* the protocol return value */
139     /* buffer for data received from the control connection */
140     char controlBuf[FTP_BUF_SIZE + 1];
141     int controlBufIndex;
142     int controlBufUsed;
143     int controlBufAnswer;
144 } xmlNanoFTPCtxt, *xmlNanoFTPCtxtPtr;
145
146 static int initialized = 0;
147 static char *proxy = NULL;      /* the proxy name if any */
148 static int proxyPort = 0;       /* the proxy port if any */
149 static char *proxyUser = NULL;  /* user for proxy authentication */
150 static char *proxyPasswd = NULL;/* passwd for proxy authentication */
151 static int proxyType = 0;       /* uses TYPE or a@b ? */
152
153 #ifdef SUPPORT_IP6
154 static
155 int have_ipv6(void) {
156     int s;
157
158     s = socket (AF_INET6, SOCK_STREAM, 0);
159     if (s != -1) {
160         close (s);
161         return (1);
162     }
163     return (0);
164 }
165 #endif
166
167 /**
168  * xmlFTPErrMemory:
169  * @extra:  extra informations
170  *
171  * Handle an out of memory condition
172  */
173 static void
174 xmlFTPErrMemory(const char *extra)
175 {
176     __xmlSimpleError(XML_FROM_FTP, XML_ERR_NO_MEMORY, NULL, NULL, extra);
177 }
178
179 /**
180  * xmlNanoFTPInit:
181  *
182  * Initialize the FTP protocol layer.
183  * Currently it just checks for proxy informations,
184  * and get the hostname
185  */
186
187 void
188 xmlNanoFTPInit(void) {
189     const char *env;
190 #ifdef _WINSOCKAPI_
191     WSADATA wsaData;
192 #endif
193
194     if (initialized)
195         return;
196
197 #ifdef _WINSOCKAPI_
198     if (WSAStartup(MAKEWORD(1, 1), &wsaData) != 0)
199         return;
200 #endif
201
202     proxyPort = 21;
203     env = getenv("no_proxy");
204     if (env && ((env[0] == '*' ) && (env[1] == 0)))
205         return;
206     env = getenv("ftp_proxy");
207     if (env != NULL) {
208         xmlNanoFTPScanProxy(env);
209     } else {
210         env = getenv("FTP_PROXY");
211         if (env != NULL) {
212             xmlNanoFTPScanProxy(env);
213         }
214     }
215     env = getenv("ftp_proxy_user");
216     if (env != NULL) {
217         proxyUser = xmlMemStrdup(env);
218     }
219     env = getenv("ftp_proxy_password");
220     if (env != NULL) {
221         proxyPasswd = xmlMemStrdup(env);
222     }
223     initialized = 1;
224 }
225
226 /**
227  * xmlNanoFTPCleanup:
228  *
229  * Cleanup the FTP protocol layer. This cleanup proxy informations.
230  */
231
232 void
233 xmlNanoFTPCleanup(void) {
234     if (proxy != NULL) {
235         xmlFree(proxy);
236         proxy = NULL;
237     }
238     if (proxyUser != NULL) {
239         xmlFree(proxyUser);
240         proxyUser = NULL;
241     }
242     if (proxyPasswd != NULL) {
243         xmlFree(proxyPasswd);
244         proxyPasswd = NULL;
245     }
246 #ifdef _WINSOCKAPI_
247     if (initialized)
248         WSACleanup();
249 #endif
250     initialized = 0;
251 }
252
253 /**
254  * xmlNanoFTPProxy:
255  * @host:  the proxy host name
256  * @port:  the proxy port
257  * @user:  the proxy user name
258  * @passwd:  the proxy password
259  * @type:  the type of proxy 1 for using SITE, 2 for USER a@b
260  *
261  * Setup the FTP proxy informations.
262  * This can also be done by using ftp_proxy ftp_proxy_user and
263  * ftp_proxy_password environment variables.
264  */
265
266 void
267 xmlNanoFTPProxy(const char *host, int port, const char *user,
268                 const char *passwd, int type) {
269     if (proxy != NULL) {
270         xmlFree(proxy);
271         proxy = NULL;
272     }
273     if (proxyUser != NULL) {
274         xmlFree(proxyUser);
275         proxyUser = NULL;
276     }
277     if (proxyPasswd != NULL) {
278         xmlFree(proxyPasswd);
279         proxyPasswd = NULL;
280     }
281     if (host)
282         proxy = xmlMemStrdup(host);
283     if (user)
284         proxyUser = xmlMemStrdup(user);
285     if (passwd)
286         proxyPasswd = xmlMemStrdup(passwd);
287     proxyPort = port;
288     proxyType = type;
289 }
290
291 /**
292  * xmlNanoFTPScanURL:
293  * @ctx:  an FTP context
294  * @URL:  The URL used to initialize the context
295  *
296  * (Re)Initialize an FTP context by parsing the URL and finding
297  * the protocol host port and path it indicates.
298  */
299
300 static void
301 xmlNanoFTPScanURL(void *ctx, const char *URL) {
302     xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
303     xmlURIPtr uri;
304
305     /*
306      * Clear any existing data from the context
307      */
308     if (ctxt->protocol != NULL) {
309         xmlFree(ctxt->protocol);
310         ctxt->protocol = NULL;
311     }
312     if (ctxt->hostname != NULL) {
313         xmlFree(ctxt->hostname);
314         ctxt->hostname = NULL;
315     }
316     if (ctxt->path != NULL) {
317         xmlFree(ctxt->path);
318         ctxt->path = NULL;
319     }
320     if (URL == NULL) return;
321
322     uri = xmlParseURIRaw(URL, 1);
323     if (uri == NULL)
324         return;
325
326     if ((uri->scheme == NULL) || (uri->server == NULL)) {
327         xmlFreeURI(uri);
328         return;
329     }
330
331     ctxt->protocol = xmlMemStrdup(uri->scheme);
332     ctxt->hostname = xmlMemStrdup(uri->server);
333     if (uri->path != NULL)
334         ctxt->path = xmlMemStrdup(uri->path);
335     else
336         ctxt->path = xmlMemStrdup("/");
337     if (uri->port != 0)
338         ctxt->port = uri->port;
339
340     if (uri->user != NULL) {
341         char *cptr;
342         if ((cptr=strchr(uri->user, ':')) == NULL)
343             ctxt->user = xmlMemStrdup(uri->user);
344         else {
345             ctxt->user = (char *)xmlStrndup((xmlChar *)uri->user,
346                             (cptr - uri->user));
347             ctxt->passwd = xmlMemStrdup(cptr+1);
348         }
349     }
350
351     xmlFreeURI(uri);
352
353 }
354
355 /**
356  * xmlNanoFTPUpdateURL:
357  * @ctx:  an FTP context
358  * @URL:  The URL used to update the context
359  *
360  * Update an FTP context by parsing the URL and finding
361  * new path it indicates. If there is an error in the
362  * protocol, hostname, port or other information, the
363  * error is raised. It indicates a new connection has to
364  * be established.
365  *
366  * Returns 0 if Ok, -1 in case of error (other host).
367  */
368
369 int
370 xmlNanoFTPUpdateURL(void *ctx, const char *URL) {
371     xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
372     xmlURIPtr uri;
373
374     if (URL == NULL)
375         return(-1);
376     if (ctxt == NULL)
377         return(-1);
378     if (ctxt->protocol == NULL)
379         return(-1);
380     if (ctxt->hostname == NULL)
381         return(-1);
382
383     uri = xmlParseURIRaw(URL, 1);
384     if (uri == NULL)
385         return(-1);
386
387     if ((uri->scheme == NULL) || (uri->server == NULL)) {
388         xmlFreeURI(uri);
389         return(-1);
390     }
391     if ((strcmp(ctxt->protocol, uri->scheme)) ||
392         (strcmp(ctxt->hostname, uri->server)) ||
393         ((uri->port != 0) && (ctxt->port != uri->port))) {
394         xmlFreeURI(uri);
395         return(-1);
396     }
397
398     if (uri->port != 0)
399         ctxt->port = uri->port;
400
401     if (ctxt->path != NULL) {
402         xmlFree(ctxt->path);
403         ctxt->path = NULL;
404     }
405
406     if (uri->path == NULL)
407         ctxt->path = xmlMemStrdup("/");
408     else
409         ctxt->path = xmlMemStrdup(uri->path);
410
411     xmlFreeURI(uri);
412
413     return(0);
414 }
415
416 /**
417  * xmlNanoFTPScanProxy:
418  * @URL:  The proxy URL used to initialize the proxy context
419  *
420  * (Re)Initialize the FTP Proxy context by parsing the URL and finding
421  * the protocol host port it indicates.
422  * Should be like ftp://myproxy/ or ftp://myproxy:3128/
423  * A NULL URL cleans up proxy informations.
424  */
425
426 void
427 xmlNanoFTPScanProxy(const char *URL) {
428     xmlURIPtr uri;
429
430     if (proxy != NULL) {
431         xmlFree(proxy);
432         proxy = NULL;
433     }
434     proxyPort = 0;
435
436 #ifdef DEBUG_FTP
437     if (URL == NULL)
438         xmlGenericError(xmlGenericErrorContext,
439                 "Removing FTP proxy info\n");
440     else
441         xmlGenericError(xmlGenericErrorContext,
442                 "Using FTP proxy %s\n", URL);
443 #endif
444     if (URL == NULL) return;
445
446     uri = xmlParseURIRaw(URL, 1);
447     if ((uri == NULL) || (uri->scheme == NULL) ||
448         (strcmp(uri->scheme, "ftp")) || (uri->server == NULL)) {
449         __xmlIOErr(XML_FROM_FTP, XML_FTP_URL_SYNTAX, "Syntax Error\n");
450         if (uri != NULL)
451             xmlFreeURI(uri);
452         return;
453     }
454
455     proxy = xmlMemStrdup(uri->server);
456     if (uri->port != 0)
457         proxyPort = uri->port;
458
459     xmlFreeURI(uri);
460 }
461
462 /**
463  * xmlNanoFTPNewCtxt:
464  * @URL:  The URL used to initialize the context
465  *
466  * Allocate and initialize a new FTP context.
467  *
468  * Returns an FTP context or NULL in case of error.
469  */
470
471 void*
472 xmlNanoFTPNewCtxt(const char *URL) {
473     xmlNanoFTPCtxtPtr ret;
474     char *unescaped;
475
476     ret = (xmlNanoFTPCtxtPtr) xmlMalloc(sizeof(xmlNanoFTPCtxt));
477     if (ret == NULL) {
478         xmlFTPErrMemory("allocating FTP context");
479         return(NULL);
480     }
481
482     memset(ret, 0, sizeof(xmlNanoFTPCtxt));
483     ret->port = 21;
484     ret->passive = 1;
485     ret->returnValue = 0;
486     ret->controlBufIndex = 0;
487     ret->controlBufUsed = 0;
488     ret->controlFd = INVALID_SOCKET;
489
490     unescaped = xmlURIUnescapeString(URL, 0, NULL);
491     if (unescaped != NULL) {
492         xmlNanoFTPScanURL(ret, unescaped);
493         xmlFree(unescaped);
494     } else if (URL != NULL)
495         xmlNanoFTPScanURL(ret, URL);
496
497     return(ret);
498 }
499
500 /**
501  * xmlNanoFTPFreeCtxt:
502  * @ctx:  an FTP context
503  *
504  * Frees the context after closing the connection.
505  */
506
507 void
508 xmlNanoFTPFreeCtxt(void * ctx) {
509     xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
510     if (ctxt == NULL) return;
511     if (ctxt->hostname != NULL) xmlFree(ctxt->hostname);
512     if (ctxt->protocol != NULL) xmlFree(ctxt->protocol);
513     if (ctxt->path != NULL) xmlFree(ctxt->path);
514     if (ctxt->user != NULL) xmlFree(ctxt->user);
515     if (ctxt->passwd != NULL) xmlFree(ctxt->passwd);
516     ctxt->passive = 1;
517     if (ctxt->controlFd != INVALID_SOCKET) closesocket(ctxt->controlFd);
518     ctxt->controlFd = INVALID_SOCKET;
519     ctxt->controlBufIndex = -1;
520     ctxt->controlBufUsed = -1;
521     xmlFree(ctxt);
522 }
523
524 /**
525  * xmlNanoFTPParseResponse:
526  * @buf:  the buffer containing the response
527  * @len:  the buffer length
528  *
529  * Parsing of the server answer, we just extract the code.
530  *
531  * returns 0 for errors
532  *     +XXX for last line of response
533  *     -XXX for response to be continued
534  */
535 static int
536 xmlNanoFTPParseResponse(char *buf, int len) {
537     int val = 0;
538
539     if (len < 3) return(-1);
540     if ((*buf >= '0') && (*buf <= '9'))
541         val = val * 10 + (*buf - '0');
542     else
543         return(0);
544     buf++;
545     if ((*buf >= '0') && (*buf <= '9'))
546         val = val * 10 + (*buf - '0');
547     else
548         return(0);
549     buf++;
550     if ((*buf >= '0') && (*buf <= '9'))
551         val = val * 10 + (*buf - '0');
552     else
553         return(0);
554     buf++;
555     if (*buf == '-')
556         return(-val);
557     return(val);
558 }
559
560 /**
561  * xmlNanoFTPGetMore:
562  * @ctx:  an FTP context
563  *
564  * Read more information from the FTP control connection
565  * Returns the number of bytes read, < 0 indicates an error
566  */
567 static int
568 xmlNanoFTPGetMore(void *ctx) {
569     xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
570     int len;
571     int size;
572
573     if ((ctxt == NULL) || (ctxt->controlFd == INVALID_SOCKET)) return(-1);
574
575     if ((ctxt->controlBufIndex < 0) || (ctxt->controlBufIndex > FTP_BUF_SIZE)) {
576 #ifdef DEBUG_FTP
577         xmlGenericError(xmlGenericErrorContext,
578                 "xmlNanoFTPGetMore : controlBufIndex = %d\n",
579                 ctxt->controlBufIndex);
580 #endif
581         return(-1);
582     }
583
584     if ((ctxt->controlBufUsed < 0) || (ctxt->controlBufUsed > FTP_BUF_SIZE)) {
585 #ifdef DEBUG_FTP
586         xmlGenericError(xmlGenericErrorContext,
587                 "xmlNanoFTPGetMore : controlBufUsed = %d\n",
588                 ctxt->controlBufUsed);
589 #endif
590         return(-1);
591     }
592     if (ctxt->controlBufIndex > ctxt->controlBufUsed) {
593 #ifdef DEBUG_FTP
594         xmlGenericError(xmlGenericErrorContext,
595                 "xmlNanoFTPGetMore : controlBufIndex > controlBufUsed %d > %d\n",
596                ctxt->controlBufIndex, ctxt->controlBufUsed);
597 #endif
598         return(-1);
599     }
600
601     /*
602      * First pack the control buffer
603      */
604     if (ctxt->controlBufIndex > 0) {
605         memmove(&ctxt->controlBuf[0], &ctxt->controlBuf[ctxt->controlBufIndex],
606                 ctxt->controlBufUsed - ctxt->controlBufIndex);
607         ctxt->controlBufUsed -= ctxt->controlBufIndex;
608         ctxt->controlBufIndex = 0;
609     }
610     size = FTP_BUF_SIZE - ctxt->controlBufUsed;
611     if (size == 0) {
612 #ifdef DEBUG_FTP
613         xmlGenericError(xmlGenericErrorContext,
614                 "xmlNanoFTPGetMore : buffer full %d \n", ctxt->controlBufUsed);
615 #endif
616         return(0);
617     }
618
619     /*
620      * Read the amount left on the control connection
621      */
622     if ((len = recv(ctxt->controlFd, &ctxt->controlBuf[ctxt->controlBufIndex],
623                     size, 0)) < 0) {
624         __xmlIOErr(XML_FROM_FTP, 0, "recv failed");
625         closesocket(ctxt->controlFd); ctxt->controlFd = INVALID_SOCKET;
626         ctxt->controlFd = INVALID_SOCKET;
627         return(-1);
628     }
629 #ifdef DEBUG_FTP
630     xmlGenericError(xmlGenericErrorContext,
631             "xmlNanoFTPGetMore : read %d [%d - %d]\n", len,
632            ctxt->controlBufUsed, ctxt->controlBufUsed + len);
633 #endif
634     ctxt->controlBufUsed += len;
635     ctxt->controlBuf[ctxt->controlBufUsed] = 0;
636
637     return(len);
638 }
639
640 /**
641  * xmlNanoFTPReadResponse:
642  * @ctx:  an FTP context
643  *
644  * Read the response from the FTP server after a command.
645  * Returns the code number
646  */
647 static int
648 xmlNanoFTPReadResponse(void *ctx) {
649     xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
650     char *ptr, *end;
651     int len;
652     int res = -1, cur = -1;
653
654     if ((ctxt == NULL) || (ctxt->controlFd == INVALID_SOCKET)) return(-1);
655
656 get_more:
657     /*
658      * Assumes everything up to controlBuf[controlBufIndex] has been read
659      * and analyzed.
660      */
661     len = xmlNanoFTPGetMore(ctx);
662     if (len < 0) {
663         return(-1);
664     }
665     if ((ctxt->controlBufUsed == 0) && (len == 0)) {
666         return(-1);
667     }
668     ptr = &ctxt->controlBuf[ctxt->controlBufIndex];
669     end = &ctxt->controlBuf[ctxt->controlBufUsed];
670
671 #ifdef DEBUG_FTP
672     xmlGenericError(xmlGenericErrorContext,
673             "\n<<<\n%s\n--\n", ptr);
674 #endif
675     while (ptr < end) {
676         cur = xmlNanoFTPParseResponse(ptr, end - ptr);
677         if (cur > 0) {
678             /*
679              * Successfully scanned the control code, scratch
680              * till the end of the line, but keep the index to be
681              * able to analyze the result if needed.
682              */
683             res = cur;
684             ptr += 3;
685             ctxt->controlBufAnswer = ptr - ctxt->controlBuf;
686             while ((ptr < end) && (*ptr != '\n')) ptr++;
687             if (*ptr == '\n') ptr++;
688             if (*ptr == '\r') ptr++;
689             break;
690         }
691         while ((ptr < end) && (*ptr != '\n')) ptr++;
692         if (ptr >= end) {
693             ctxt->controlBufIndex = ctxt->controlBufUsed;
694             goto get_more;
695         }
696         if (*ptr != '\r') ptr++;
697     }
698
699     if (res < 0) goto get_more;
700     ctxt->controlBufIndex = ptr - ctxt->controlBuf;
701 #ifdef DEBUG_FTP
702     ptr = &ctxt->controlBuf[ctxt->controlBufIndex];
703     xmlGenericError(xmlGenericErrorContext, "\n---\n%s\n--\n", ptr);
704 #endif
705
706 #ifdef DEBUG_FTP
707     xmlGenericError(xmlGenericErrorContext, "Got %d\n", res);
708 #endif
709     return(res / 100);
710 }
711
712 /**
713  * xmlNanoFTPGetResponse:
714  * @ctx:  an FTP context
715  *
716  * Get the response from the FTP server after a command.
717  * Returns the code number
718  */
719
720 int
721 xmlNanoFTPGetResponse(void *ctx) {
722     int res;
723
724     res = xmlNanoFTPReadResponse(ctx);
725
726     return(res);
727 }
728
729 /**
730  * xmlNanoFTPCheckResponse:
731  * @ctx:  an FTP context
732  *
733  * Check if there is a response from the FTP server after a command.
734  * Returns the code number, or 0
735  */
736
737 int
738 xmlNanoFTPCheckResponse(void *ctx) {
739     xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
740     fd_set rfd;
741     struct timeval tv;
742
743     if ((ctxt == NULL) || (ctxt->controlFd == INVALID_SOCKET)) return(-1);
744     tv.tv_sec = 0;
745     tv.tv_usec = 0;
746     FD_ZERO(&rfd);
747     FD_SET(ctxt->controlFd, &rfd);
748     switch(select(ctxt->controlFd + 1, &rfd, NULL, NULL, &tv)) {
749         case 0:
750             return(0);
751         case -1:
752             __xmlIOErr(XML_FROM_FTP, 0, "select");
753             return(-1);
754
755     }
756
757     return(xmlNanoFTPReadResponse(ctx));
758 }
759
760 /**
761  * Send the user authentication
762  */
763
764 static int
765 xmlNanoFTPSendUser(void *ctx) {
766     xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
767     char buf[200];
768     int len;
769     int res;
770
771     if (ctxt->user == NULL)
772         snprintf(buf, sizeof(buf), "USER anonymous\r\n");
773     else
774         snprintf(buf, sizeof(buf), "USER %s\r\n", ctxt->user);
775     buf[sizeof(buf) - 1] = 0;
776     len = strlen(buf);
777 #ifdef DEBUG_FTP
778     xmlGenericError(xmlGenericErrorContext, "%s", buf);
779 #endif
780     res = send(ctxt->controlFd, SEND_ARG2_CAST buf, len, 0);
781     if (res < 0) {
782         __xmlIOErr(XML_FROM_FTP, 0, "send failed");
783         return(res);
784     }
785     return(0);
786 }
787
788 /**
789  * Send the password authentication
790  */
791
792 static int
793 xmlNanoFTPSendPasswd(void *ctx) {
794     xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
795     char buf[200];
796     int len;
797     int res;
798
799     if (ctxt->passwd == NULL)
800         snprintf(buf, sizeof(buf), "PASS anonymous@\r\n");
801     else
802         snprintf(buf, sizeof(buf), "PASS %s\r\n", ctxt->passwd);
803     buf[sizeof(buf) - 1] = 0;
804     len = strlen(buf);
805 #ifdef DEBUG_FTP
806     xmlGenericError(xmlGenericErrorContext, "%s", buf);
807 #endif
808     res = send(ctxt->controlFd, SEND_ARG2_CAST buf, len, 0);
809     if (res < 0) {
810         __xmlIOErr(XML_FROM_FTP, 0, "send failed");
811         return(res);
812     }
813     return(0);
814 }
815
816 /**
817  * xmlNanoFTPQuit:
818  * @ctx:  an FTP context
819  *
820  * Send a QUIT command to the server
821  *
822  * Returns -1 in case of error, 0 otherwise
823  */
824
825
826 int
827 xmlNanoFTPQuit(void *ctx) {
828     xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
829     char buf[200];
830     int len, res;
831
832     if ((ctxt == NULL) || (ctxt->controlFd == INVALID_SOCKET)) return(-1);
833
834     snprintf(buf, sizeof(buf), "QUIT\r\n");
835     len = strlen(buf);
836 #ifdef DEBUG_FTP
837     xmlGenericError(xmlGenericErrorContext, "%s", buf); /* Just to be consistent, even though we know it can't have a % in it */
838 #endif
839     res = send(ctxt->controlFd, SEND_ARG2_CAST buf, len, 0);
840     if (res < 0) {
841         __xmlIOErr(XML_FROM_FTP, 0, "send failed");
842         return(res);
843     }
844     return(0);
845 }
846
847 /**
848  * xmlNanoFTPConnect:
849  * @ctx:  an FTP context
850  *
851  * Tries to open a control connection
852  *
853  * Returns -1 in case of error, 0 otherwise
854  */
855
856 int
857 xmlNanoFTPConnect(void *ctx) {
858     xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
859     struct hostent *hp;
860     int port;
861     int res;
862     int addrlen = sizeof (struct sockaddr_in);
863
864     if (ctxt == NULL)
865         return(-1);
866     if (ctxt->hostname == NULL)
867         return(-1);
868
869     /*
870      * do the blocking DNS query.
871      */
872     if (proxy) {
873         port = proxyPort;
874     } else {
875         port = ctxt->port;
876     }
877     if (port == 0)
878         port = 21;
879
880     memset (&ctxt->ftpAddr, 0, sizeof(ctxt->ftpAddr));
881
882 #ifdef SUPPORT_IP6
883     if (have_ipv6 ()) {
884         struct addrinfo hints, *tmp, *result;
885
886         result = NULL;
887         memset (&hints, 0, sizeof(hints));
888         hints.ai_socktype = SOCK_STREAM;
889
890         if (proxy) {
891             if (getaddrinfo (proxy, NULL, &hints, &result) != 0) {
892                 __xmlIOErr(XML_FROM_FTP, 0, "getaddrinfo failed");
893                 return (-1);
894             }
895         }
896         else
897             if (getaddrinfo (ctxt->hostname, NULL, &hints, &result) != 0) {
898                 __xmlIOErr(XML_FROM_FTP, 0, "getaddrinfo failed");
899                 return (-1);
900             }
901
902         for (tmp = result; tmp; tmp = tmp->ai_next)
903             if (tmp->ai_family == AF_INET || tmp->ai_family == AF_INET6)
904                 break;
905
906         if (!tmp) {
907             if (result)
908                 freeaddrinfo (result);
909             __xmlIOErr(XML_FROM_FTP, 0, "getaddrinfo failed");
910             return (-1);
911         }
912         if (tmp->ai_addrlen > sizeof(ctxt->ftpAddr)) {
913             if (result)
914                 freeaddrinfo (result);
915             __xmlIOErr(XML_FROM_FTP, 0, "gethostbyname address mismatch");
916             return (-1);
917         }
918         if (tmp->ai_family == AF_INET6) {
919             memcpy (&ctxt->ftpAddr, tmp->ai_addr, tmp->ai_addrlen);
920             ((struct sockaddr_in6 *) &ctxt->ftpAddr)->sin6_port = htons (port);
921             ctxt->controlFd = socket (AF_INET6, SOCK_STREAM, 0);
922         }
923         else {
924             memcpy (&ctxt->ftpAddr, tmp->ai_addr, tmp->ai_addrlen);
925             ((struct sockaddr_in *) &ctxt->ftpAddr)->sin_port = htons (port);
926             ctxt->controlFd = socket (AF_INET, SOCK_STREAM, 0);
927         }
928         addrlen = tmp->ai_addrlen;
929         freeaddrinfo (result);
930     }
931     else
932 #endif
933     {
934         if (proxy)
935             hp = gethostbyname (GETHOSTBYNAME_ARG_CAST proxy);
936         else
937             hp = gethostbyname (GETHOSTBYNAME_ARG_CAST ctxt->hostname);
938         if (hp == NULL) {
939             __xmlIOErr(XML_FROM_FTP, 0, "gethostbyname failed");
940             return (-1);
941         }
942         if ((unsigned int) hp->h_length >
943             sizeof(((struct sockaddr_in *)&ctxt->ftpAddr)->sin_addr)) {
944             __xmlIOErr(XML_FROM_FTP, 0, "gethostbyname address mismatch");
945             return (-1);
946         }
947
948         /*
949          * Prepare the socket
950          */
951         ((struct sockaddr_in *)&ctxt->ftpAddr)->sin_family = AF_INET;
952         memcpy (&((struct sockaddr_in *)&ctxt->ftpAddr)->sin_addr,
953                 hp->h_addr_list[0], hp->h_length);
954         ((struct sockaddr_in *)&ctxt->ftpAddr)->sin_port =
955              (unsigned short)htons ((unsigned short)port);
956         ctxt->controlFd = socket (AF_INET, SOCK_STREAM, 0);
957         addrlen = sizeof (struct sockaddr_in);
958     }
959
960     if (ctxt->controlFd == INVALID_SOCKET) {
961         __xmlIOErr(XML_FROM_FTP, 0, "socket failed");
962         return(-1);
963     }
964
965     /*
966      * Do the connect.
967      */
968     if (connect(ctxt->controlFd, (struct sockaddr *) &ctxt->ftpAddr,
969             addrlen) < 0) {
970         __xmlIOErr(XML_FROM_FTP, 0, "Failed to create a connection");
971         closesocket(ctxt->controlFd); ctxt->controlFd = INVALID_SOCKET;
972         ctxt->controlFd = INVALID_SOCKET;
973         return(-1);
974     }
975
976     /*
977      * Wait for the HELLO from the server.
978      */
979     res = xmlNanoFTPGetResponse(ctxt);
980     if (res != 2) {
981         closesocket(ctxt->controlFd); ctxt->controlFd = INVALID_SOCKET;
982         ctxt->controlFd = INVALID_SOCKET;
983         return(-1);
984     }
985
986     /*
987      * State diagram for the login operation on the FTP server
988      *
989      * Reference: RFC 959
990      *
991      *                       1
992      * +---+   USER    +---+------------->+---+
993      * | B |---------->| W | 2       ---->| E |
994      * +---+           +---+------  |  -->+---+
995      *                  | |       | | |
996      *                3 | | 4,5   | | |
997      *    --------------   -----  | | |
998      *   |                      | | | |
999      *   |                      | | | |
1000      *   |                 ---------  |
1001      *   |               1|     | |   |
1002      *   V                |     | |   |
1003      * +---+   PASS    +---+ 2  |  ------>+---+
1004      * |   |---------->| W |------------->| S |
1005      * +---+           +---+   ---------->+---+
1006      *                  | |   | |     |
1007      *                3 | |4,5| |     |
1008      *    --------------   --------   |
1009      *   |                    | |  |  |
1010      *   |                    | |  |  |
1011      *   |                 -----------
1012      *   |             1,3|   | |  |
1013      *   V                |  2| |  |
1014      * +---+   ACCT    +---+--  |   ----->+---+
1015      * |   |---------->| W | 4,5 -------->| F |
1016      * +---+           +---+------------->+---+
1017      *
1018      * Of course in case of using a proxy this get really nasty and is not
1019      * standardized at all :-(
1020      */
1021     if (proxy) {
1022         int len;
1023         char buf[400];
1024
1025         if (proxyUser != NULL) {
1026             /*
1027              * We need proxy auth
1028              */
1029             snprintf(buf, sizeof(buf), "USER %s\r\n", proxyUser);
1030             buf[sizeof(buf) - 1] = 0;
1031             len = strlen(buf);
1032 #ifdef DEBUG_FTP
1033             xmlGenericError(xmlGenericErrorContext, "%s", buf);
1034 #endif
1035             res = send(ctxt->controlFd, SEND_ARG2_CAST buf, len, 0);
1036             if (res < 0) {
1037                 __xmlIOErr(XML_FROM_FTP, 0, "send failed");
1038                 closesocket(ctxt->controlFd);
1039                 ctxt->controlFd = INVALID_SOCKET;
1040                 return(res);
1041             }
1042             res = xmlNanoFTPGetResponse(ctxt);
1043             switch (res) {
1044                 case 2:
1045                     if (proxyPasswd == NULL)
1046                         break;
1047                 case 3:
1048                     if (proxyPasswd != NULL)
1049                         snprintf(buf, sizeof(buf), "PASS %s\r\n", proxyPasswd);
1050                     else
1051                         snprintf(buf, sizeof(buf), "PASS anonymous@\r\n");
1052                     buf[sizeof(buf) - 1] = 0;
1053                     len = strlen(buf);
1054 #ifdef DEBUG_FTP
1055                     xmlGenericError(xmlGenericErrorContext, "%s", buf);
1056 #endif
1057                     res = send(ctxt->controlFd, SEND_ARG2_CAST buf, len, 0);
1058                     if (res < 0) {
1059                         __xmlIOErr(XML_FROM_FTP, 0, "send failed");
1060                         closesocket(ctxt->controlFd);
1061                         ctxt->controlFd = INVALID_SOCKET;
1062                         return(res);
1063                     }
1064                     res = xmlNanoFTPGetResponse(ctxt);
1065                     if (res > 3) {
1066                         closesocket(ctxt->controlFd);
1067                         ctxt->controlFd = INVALID_SOCKET;
1068                         return(-1);
1069                     }
1070                     break;
1071                 case 1:
1072                     break;
1073                 case 4:
1074                 case 5:
1075                 case -1:
1076                 default:
1077                     closesocket(ctxt->controlFd);
1078                     ctxt->controlFd = INVALID_SOCKET;
1079                     return(-1);
1080             }
1081         }
1082
1083         /*
1084          * We assume we don't need more authentication to the proxy
1085          * and that it succeeded :-\
1086          */
1087         switch (proxyType) {
1088             case 0:
1089                 /* we will try in sequence */
1090             case 1:
1091                 /* Using SITE command */
1092                 snprintf(buf, sizeof(buf), "SITE %s\r\n", ctxt->hostname);
1093                 buf[sizeof(buf) - 1] = 0;
1094                 len = strlen(buf);
1095 #ifdef DEBUG_FTP
1096                 xmlGenericError(xmlGenericErrorContext, "%s", buf);
1097 #endif
1098                 res = send(ctxt->controlFd, SEND_ARG2_CAST buf, len, 0);
1099                 if (res < 0) {
1100                     __xmlIOErr(XML_FROM_FTP, 0, "send failed");
1101                     closesocket(ctxt->controlFd); ctxt->controlFd = INVALID_SOCKET;
1102                     ctxt->controlFd = INVALID_SOCKET;
1103                     return(res);
1104                 }
1105                 res = xmlNanoFTPGetResponse(ctxt);
1106                 if (res == 2) {
1107                     /* we assume it worked :-\ 1 is error for SITE command */
1108                     proxyType = 1;
1109                     break;
1110                 }
1111                 if (proxyType == 1) {
1112                     closesocket(ctxt->controlFd); ctxt->controlFd = INVALID_SOCKET;
1113                     ctxt->controlFd = INVALID_SOCKET;
1114                     return(-1);
1115                 }
1116             case 2:
1117                 /* USER user@host command */
1118                 if (ctxt->user == NULL)
1119                     snprintf(buf, sizeof(buf), "USER anonymous@%s\r\n",
1120                                    ctxt->hostname);
1121                 else
1122                     snprintf(buf, sizeof(buf), "USER %s@%s\r\n",
1123                                    ctxt->user, ctxt->hostname);
1124                 buf[sizeof(buf) - 1] = 0;
1125                 len = strlen(buf);
1126 #ifdef DEBUG_FTP
1127                 xmlGenericError(xmlGenericErrorContext, "%s", buf);
1128 #endif
1129                 res = send(ctxt->controlFd, SEND_ARG2_CAST buf, len, 0);
1130                 if (res < 0) {
1131                     __xmlIOErr(XML_FROM_FTP, 0, "send failed");
1132                     closesocket(ctxt->controlFd); ctxt->controlFd = INVALID_SOCKET;
1133                     ctxt->controlFd = INVALID_SOCKET;
1134                     return(res);
1135                 }
1136                 res = xmlNanoFTPGetResponse(ctxt);
1137                 if ((res == 1) || (res == 2)) {
1138                     /* we assume it worked :-\ */
1139                     proxyType = 2;
1140                     return(0);
1141                 }
1142                 if (ctxt->passwd == NULL)
1143                     snprintf(buf, sizeof(buf), "PASS anonymous@\r\n");
1144                 else
1145                     snprintf(buf, sizeof(buf), "PASS %s\r\n", ctxt->passwd);
1146                 buf[sizeof(buf) - 1] = 0;
1147                 len = strlen(buf);
1148 #ifdef DEBUG_FTP
1149                 xmlGenericError(xmlGenericErrorContext, "%s", buf);
1150 #endif
1151                 res = send(ctxt->controlFd, SEND_ARG2_CAST buf, len, 0);
1152                 if (res < 0) {
1153                     __xmlIOErr(XML_FROM_FTP, 0, "send failed");
1154                     closesocket(ctxt->controlFd); ctxt->controlFd = INVALID_SOCKET;
1155                     ctxt->controlFd = INVALID_SOCKET;
1156                     return(res);
1157                 }
1158                 res = xmlNanoFTPGetResponse(ctxt);
1159                 if ((res == 1) || (res == 2)) {
1160                     /* we assume it worked :-\ */
1161                     proxyType = 2;
1162                     return(0);
1163                 }
1164                 if (proxyType == 2) {
1165                     closesocket(ctxt->controlFd); ctxt->controlFd = INVALID_SOCKET;
1166                     ctxt->controlFd = INVALID_SOCKET;
1167                     return(-1);
1168                 }
1169             case 3:
1170                 /*
1171                  * If you need support for other Proxy authentication scheme
1172                  * send the code or at least the sequence in use.
1173                  */
1174             default:
1175                 closesocket(ctxt->controlFd); ctxt->controlFd = INVALID_SOCKET;
1176                 ctxt->controlFd = INVALID_SOCKET;
1177                 return(-1);
1178         }
1179     }
1180     /*
1181      * Non-proxy handling.
1182      */
1183     res = xmlNanoFTPSendUser(ctxt);
1184     if (res < 0) {
1185         closesocket(ctxt->controlFd); ctxt->controlFd = INVALID_SOCKET;
1186         ctxt->controlFd = INVALID_SOCKET;
1187         return(-1);
1188     }
1189     res = xmlNanoFTPGetResponse(ctxt);
1190     switch (res) {
1191         case 2:
1192             return(0);
1193         case 3:
1194             break;
1195         case 1:
1196         case 4:
1197         case 5:
1198         case -1:
1199         default:
1200             closesocket(ctxt->controlFd); ctxt->controlFd = INVALID_SOCKET;
1201             ctxt->controlFd = INVALID_SOCKET;
1202             return(-1);
1203     }
1204     res = xmlNanoFTPSendPasswd(ctxt);
1205     if (res < 0) {
1206         closesocket(ctxt->controlFd); ctxt->controlFd = INVALID_SOCKET;
1207         ctxt->controlFd = INVALID_SOCKET;
1208         return(-1);
1209     }
1210     res = xmlNanoFTPGetResponse(ctxt);
1211     switch (res) {
1212         case 2:
1213             break;
1214         case 3:
1215             __xmlIOErr(XML_FROM_FTP, XML_FTP_ACCNT,
1216                        "FTP server asking for ACCNT on anonymous\n");
1217         case 1:
1218         case 4:
1219         case 5:
1220         case -1:
1221         default:
1222             closesocket(ctxt->controlFd); ctxt->controlFd = INVALID_SOCKET;
1223             ctxt->controlFd = INVALID_SOCKET;
1224             return(-1);
1225     }
1226
1227     return(0);
1228 }
1229
1230 /**
1231  * xmlNanoFTPConnectTo:
1232  * @server:  an FTP server name
1233  * @port:  the port (use 21 if 0)
1234  *
1235  * Tries to open a control connection to the given server/port
1236  *
1237  * Returns an fTP context or NULL if it failed
1238  */
1239
1240 void*
1241 xmlNanoFTPConnectTo(const char *server, int port) {
1242     xmlNanoFTPCtxtPtr ctxt;
1243     int res;
1244
1245     xmlNanoFTPInit();
1246     if (server == NULL)
1247         return(NULL);
1248     if (port <= 0)
1249         return(NULL);
1250     ctxt = (xmlNanoFTPCtxtPtr) xmlNanoFTPNewCtxt(NULL);
1251     if (ctxt == NULL)
1252         return(NULL);
1253     ctxt->hostname = xmlMemStrdup(server);
1254     if (ctxt->hostname == NULL) {
1255         xmlNanoFTPFreeCtxt(ctxt);
1256         return(NULL);
1257     }
1258     if (port != 0)
1259         ctxt->port = port;
1260     res = xmlNanoFTPConnect(ctxt);
1261     if (res < 0) {
1262         xmlNanoFTPFreeCtxt(ctxt);
1263         return(NULL);
1264     }
1265     return(ctxt);
1266 }
1267
1268 /**
1269  * xmlNanoFTPCwd:
1270  * @ctx:  an FTP context
1271  * @directory:  a directory on the server
1272  *
1273  * Tries to change the remote directory
1274  *
1275  * Returns -1 incase of error, 1 if CWD worked, 0 if it failed
1276  */
1277
1278 int
1279 xmlNanoFTPCwd(void *ctx, const char *directory) {
1280     xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
1281     char buf[400];
1282     int len;
1283     int res;
1284
1285     if ((ctxt == NULL) || (ctxt->controlFd == INVALID_SOCKET)) return(-1);
1286     if (directory == NULL) return 0;
1287
1288     /*
1289      * Expected response code for CWD:
1290      *
1291      * CWD
1292      *     250
1293      *     500, 501, 502, 421, 530, 550
1294      */
1295     snprintf(buf, sizeof(buf), "CWD %s\r\n", directory);
1296     buf[sizeof(buf) - 1] = 0;
1297     len = strlen(buf);
1298 #ifdef DEBUG_FTP
1299     xmlGenericError(xmlGenericErrorContext, "%s", buf);
1300 #endif
1301     res = send(ctxt->controlFd, SEND_ARG2_CAST buf, len, 0);
1302     if (res < 0) {
1303         __xmlIOErr(XML_FROM_FTP, 0, "send failed");
1304         return(res);
1305     }
1306     res = xmlNanoFTPGetResponse(ctxt);
1307     if (res == 4) {
1308         return(-1);
1309     }
1310     if (res == 2) return(1);
1311     if (res == 5) {
1312         return(0);
1313     }
1314     return(0);
1315 }
1316
1317 /**
1318  * xmlNanoFTPDele:
1319  * @ctx:  an FTP context
1320  * @file:  a file or directory on the server
1321  *
1322  * Tries to delete an item (file or directory) from server
1323  *
1324  * Returns -1 incase of error, 1 if DELE worked, 0 if it failed
1325  */
1326
1327 int
1328 xmlNanoFTPDele(void *ctx, const char *file) {
1329     xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
1330     char buf[400];
1331     int len;
1332     int res;
1333
1334     if ((ctxt == NULL) || (ctxt->controlFd == INVALID_SOCKET) ||
1335         (file == NULL)) return(-1);
1336
1337     /*
1338      * Expected response code for DELE:
1339      *
1340      * DELE
1341      *       250
1342      *       450, 550
1343      *       500, 501, 502, 421, 530
1344      */
1345
1346     snprintf(buf, sizeof(buf), "DELE %s\r\n", file);
1347     buf[sizeof(buf) - 1] = 0;
1348     len = strlen(buf);
1349 #ifdef DEBUG_FTP
1350     xmlGenericError(xmlGenericErrorContext, "%s", buf);
1351 #endif
1352     res = send(ctxt->controlFd, SEND_ARG2_CAST buf, len, 0);
1353     if (res < 0) {
1354         __xmlIOErr(XML_FROM_FTP, 0, "send failed");
1355         return(res);
1356     }
1357     res = xmlNanoFTPGetResponse(ctxt);
1358     if (res == 4) {
1359         return(-1);
1360     }
1361     if (res == 2) return(1);
1362     if (res == 5) {
1363         return(0);
1364     }
1365     return(0);
1366 }
1367 /**
1368  * xmlNanoFTPGetConnection:
1369  * @ctx:  an FTP context
1370  *
1371  * Try to open a data connection to the server. Currently only
1372  * passive mode is supported.
1373  *
1374  * Returns -1 incase of error, 0 otherwise
1375  */
1376
1377 SOCKET
1378 xmlNanoFTPGetConnection(void *ctx) {
1379     xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
1380     char buf[200], *cur;
1381     int len, i;
1382     int res;
1383     unsigned char ad[6], *adp, *portp;
1384     unsigned int temp[6];
1385 #ifdef SUPPORT_IP6
1386     struct sockaddr_storage dataAddr;
1387 #else
1388     struct sockaddr_in dataAddr;
1389 #endif
1390     XML_SOCKLEN_T dataAddrLen;
1391
1392     if (ctxt == NULL) return INVALID_SOCKET;
1393
1394     memset (&dataAddr, 0, sizeof(dataAddr));
1395 #ifdef SUPPORT_IP6
1396     if ((ctxt->ftpAddr).ss_family == AF_INET6) {
1397         ctxt->dataFd = socket (AF_INET6, SOCK_STREAM, IPPROTO_TCP);
1398         ((struct sockaddr_in6 *)&dataAddr)->sin6_family = AF_INET6;
1399         dataAddrLen = sizeof(struct sockaddr_in6);
1400     } else
1401 #endif
1402     {
1403         ctxt->dataFd = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP);
1404         ((struct sockaddr_in *)&dataAddr)->sin_family = AF_INET;
1405         dataAddrLen = sizeof (struct sockaddr_in);
1406     }
1407
1408     if (ctxt->dataFd == INVALID_SOCKET) {
1409         __xmlIOErr(XML_FROM_FTP, 0, "socket failed");
1410         return INVALID_SOCKET;
1411     }
1412
1413     if (ctxt->passive) {
1414 #ifdef SUPPORT_IP6
1415         if ((ctxt->ftpAddr).ss_family == AF_INET6)
1416             snprintf (buf, sizeof(buf), "EPSV\r\n");
1417         else
1418 #endif
1419             snprintf (buf, sizeof(buf), "PASV\r\n");
1420         len = strlen (buf);
1421 #ifdef DEBUG_FTP
1422         xmlGenericError(xmlGenericErrorContext, "%s", buf);
1423 #endif
1424         res = send(ctxt->controlFd, SEND_ARG2_CAST buf, len, 0);
1425         if (res < 0) {
1426             __xmlIOErr(XML_FROM_FTP, 0, "send failed");
1427             closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1428             return INVALID_SOCKET;
1429         }
1430         res = xmlNanoFTPReadResponse(ctx);
1431         if (res != 2) {
1432             if (res == 5) {
1433                 closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1434                 return INVALID_SOCKET;
1435             } else {
1436                 /*
1437                  * retry with an active connection
1438                  */
1439                 closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1440                 ctxt->passive = 0;
1441             }
1442         }
1443         cur = &ctxt->controlBuf[ctxt->controlBufAnswer];
1444         while (((*cur < '0') || (*cur > '9')) && *cur != '\0') cur++;
1445 #ifdef SUPPORT_IP6
1446         if ((ctxt->ftpAddr).ss_family == AF_INET6) {
1447             if (sscanf (cur, "%u", &temp[0]) != 1) {
1448                 __xmlIOErr(XML_FROM_FTP, XML_FTP_EPSV_ANSWER,
1449                         "Invalid answer to EPSV\n");
1450                 if (ctxt->dataFd != INVALID_SOCKET) {
1451                     closesocket (ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1452                 }
1453                 return INVALID_SOCKET;
1454             }
1455             memcpy (&((struct sockaddr_in6 *)&dataAddr)->sin6_addr, &((struct sockaddr_in6 *)&ctxt->ftpAddr)->sin6_addr, sizeof(struct in6_addr));
1456             ((struct sockaddr_in6 *)&dataAddr)->sin6_port = htons (temp[0]);
1457         }
1458         else
1459 #endif
1460         {
1461             if (sscanf (cur, "%u,%u,%u,%u,%u,%u", &temp[0], &temp[1], &temp[2],
1462                 &temp[3], &temp[4], &temp[5]) != 6) {
1463                 __xmlIOErr(XML_FROM_FTP, XML_FTP_PASV_ANSWER,
1464                         "Invalid answer to PASV\n");
1465                 if (ctxt->dataFd != INVALID_SOCKET) {
1466                     closesocket (ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1467                 }
1468                 return INVALID_SOCKET;
1469             }
1470             for (i=0; i<6; i++) ad[i] = (unsigned char) (temp[i] & 0xff);
1471             memcpy (&((struct sockaddr_in *)&dataAddr)->sin_addr, &ad[0], 4);
1472             memcpy (&((struct sockaddr_in *)&dataAddr)->sin_port, &ad[4], 2);
1473         }
1474
1475         if (connect(ctxt->dataFd, (struct sockaddr *) &dataAddr, dataAddrLen) < 0) {
1476             __xmlIOErr(XML_FROM_FTP, 0, "Failed to create a data connection");
1477             closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1478             return INVALID_SOCKET;
1479         }
1480     } else {
1481         getsockname(ctxt->dataFd, (struct sockaddr *) &dataAddr, &dataAddrLen);
1482 #ifdef SUPPORT_IP6
1483         if ((ctxt->ftpAddr).ss_family == AF_INET6)
1484             ((struct sockaddr_in6 *)&dataAddr)->sin6_port = 0;
1485         else
1486 #endif
1487             ((struct sockaddr_in *)&dataAddr)->sin_port = 0;
1488
1489         if (bind(ctxt->dataFd, (struct sockaddr *) &dataAddr, dataAddrLen) < 0) {
1490             __xmlIOErr(XML_FROM_FTP, 0, "bind failed");
1491             closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1492             return INVALID_SOCKET;
1493         }
1494         getsockname(ctxt->dataFd, (struct sockaddr *) &dataAddr, &dataAddrLen);
1495
1496         if (listen(ctxt->dataFd, 1) < 0) {
1497             __xmlIOErr(XML_FROM_FTP, 0, "listen failed");
1498             closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1499             return INVALID_SOCKET;
1500         }
1501 #ifdef SUPPORT_IP6
1502         if ((ctxt->ftpAddr).ss_family == AF_INET6) {
1503             char buf6[INET6_ADDRSTRLEN];
1504             inet_ntop (AF_INET6, &((struct sockaddr_in6 *)&dataAddr)->sin6_addr,
1505                     buf6, INET6_ADDRSTRLEN);
1506             adp = (unsigned char *) buf6;
1507             portp = (unsigned char *) &((struct sockaddr_in6 *)&dataAddr)->sin6_port;
1508             snprintf (buf, sizeof(buf), "EPRT |2|%s|%s|\r\n", adp, portp);
1509         } else
1510 #endif
1511         {
1512             adp = (unsigned char *) &((struct sockaddr_in *)&dataAddr)->sin_addr;
1513             portp = (unsigned char *) &((struct sockaddr_in *)&dataAddr)->sin_port;
1514             snprintf (buf, sizeof(buf), "PORT %d,%d,%d,%d,%d,%d\r\n",
1515             adp[0] & 0xff, adp[1] & 0xff, adp[2] & 0xff, adp[3] & 0xff,
1516             portp[0] & 0xff, portp[1] & 0xff);
1517         }
1518
1519         buf[sizeof(buf) - 1] = 0;
1520         len = strlen(buf);
1521 #ifdef DEBUG_FTP
1522         xmlGenericError(xmlGenericErrorContext, "%s", buf);
1523 #endif
1524
1525         res = send(ctxt->controlFd, SEND_ARG2_CAST buf, len, 0);
1526         if (res < 0) {
1527             __xmlIOErr(XML_FROM_FTP, 0, "send failed");
1528             closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1529             return INVALID_SOCKET;
1530         }
1531         res = xmlNanoFTPGetResponse(ctxt);
1532         if (res != 2) {
1533             closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1534             return INVALID_SOCKET;
1535         }
1536     }
1537     return(ctxt->dataFd);
1538
1539 }
1540
1541 /**
1542  * xmlNanoFTPCloseConnection:
1543  * @ctx:  an FTP context
1544  *
1545  * Close the data connection from the server
1546  *
1547  * Returns -1 incase of error, 0 otherwise
1548  */
1549
1550 int
1551 xmlNanoFTPCloseConnection(void *ctx) {
1552     xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
1553     int res;
1554     fd_set rfd, efd;
1555     struct timeval tv;
1556
1557     if ((ctxt == NULL) || (ctxt->controlFd == INVALID_SOCKET)) return(-1);
1558
1559     closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1560     tv.tv_sec = 15;
1561     tv.tv_usec = 0;
1562     FD_ZERO(&rfd);
1563     FD_SET(ctxt->controlFd, &rfd);
1564     FD_ZERO(&efd);
1565     FD_SET(ctxt->controlFd, &efd);
1566     res = select(ctxt->controlFd + 1, &rfd, NULL, &efd, &tv);
1567     if (res < 0) {
1568 #ifdef DEBUG_FTP
1569         perror("select");
1570 #endif
1571         closesocket(ctxt->controlFd); ctxt->controlFd = INVALID_SOCKET;
1572         return(-1);
1573     }
1574     if (res == 0) {
1575 #ifdef DEBUG_FTP
1576         xmlGenericError(xmlGenericErrorContext,
1577                 "xmlNanoFTPCloseConnection: timeout\n");
1578 #endif
1579         closesocket(ctxt->controlFd); ctxt->controlFd = INVALID_SOCKET;
1580     } else {
1581         res = xmlNanoFTPGetResponse(ctxt);
1582         if (res != 2) {
1583             closesocket(ctxt->controlFd); ctxt->controlFd = INVALID_SOCKET;
1584             return(-1);
1585         }
1586     }
1587     return(0);
1588 }
1589
1590 /**
1591  * xmlNanoFTPParseList:
1592  * @list:  some data listing received from the server
1593  * @callback:  the user callback
1594  * @userData:  the user callback data
1595  *
1596  * Parse at most one entry from the listing.
1597  *
1598  * Returns -1 incase of error, the length of data parsed otherwise
1599  */
1600
1601 static int
1602 xmlNanoFTPParseList(const char *list, ftpListCallback callback, void *userData) {
1603     const char *cur = list;
1604     char filename[151];
1605     char attrib[11];
1606     char owner[11];
1607     char group[11];
1608     char month[4];
1609     int year = 0;
1610     int minute = 0;
1611     int hour = 0;
1612     int day = 0;
1613     unsigned long size = 0;
1614     int links = 0;
1615     int i;
1616
1617     if (!strncmp(cur, "total", 5)) {
1618         cur += 5;
1619         while (*cur == ' ') cur++;
1620         while ((*cur >= '0') && (*cur <= '9'))
1621             links = (links * 10) + (*cur++ - '0');
1622         while ((*cur == ' ') || (*cur == '\n')  || (*cur == '\r'))
1623             cur++;
1624         return(cur - list);
1625     } else if (*list == '+') {
1626         return(0);
1627     } else {
1628         while ((*cur == ' ') || (*cur == '\n')  || (*cur == '\r'))
1629             cur++;
1630         if (*cur == 0) return(0);
1631         i = 0;
1632         while (*cur != ' ') {
1633             if (i < 10)
1634                 attrib[i++] = *cur;
1635             cur++;
1636             if (*cur == 0) return(0);
1637         }
1638         attrib[10] = 0;
1639         while (*cur == ' ') cur++;
1640         if (*cur == 0) return(0);
1641         while ((*cur >= '0') && (*cur <= '9'))
1642             links = (links * 10) + (*cur++ - '0');
1643         while (*cur == ' ') cur++;
1644         if (*cur == 0) return(0);
1645         i = 0;
1646         while (*cur != ' ') {
1647             if (i < 10)
1648                 owner[i++] = *cur;
1649             cur++;
1650             if (*cur == 0) return(0);
1651         }
1652         owner[i] = 0;
1653         while (*cur == ' ') cur++;
1654         if (*cur == 0) return(0);
1655         i = 0;
1656         while (*cur != ' ') {
1657             if (i < 10)
1658                 group[i++] = *cur;
1659             cur++;
1660             if (*cur == 0) return(0);
1661         }
1662         group[i] = 0;
1663         while (*cur == ' ') cur++;
1664         if (*cur == 0) return(0);
1665         while ((*cur >= '0') && (*cur <= '9'))
1666             size = (size * 10) + (*cur++ - '0');
1667         while (*cur == ' ') cur++;
1668         if (*cur == 0) return(0);
1669         i = 0;
1670         while (*cur != ' ') {
1671             if (i < 3)
1672                 month[i++] = *cur;
1673             cur++;
1674             if (*cur == 0) return(0);
1675         }
1676         month[i] = 0;
1677         while (*cur == ' ') cur++;
1678         if (*cur == 0) return(0);
1679         while ((*cur >= '0') && (*cur <= '9'))
1680             day = (day * 10) + (*cur++ - '0');
1681         while (*cur == ' ') cur++;
1682         if (*cur == 0) return(0);
1683         if ((cur[1] == 0) || (cur[2] == 0)) return(0);
1684         if ((cur[1] == ':') || (cur[2] == ':')) {
1685             while ((*cur >= '0') && (*cur <= '9'))
1686                 hour = (hour * 10) + (*cur++ - '0');
1687             if (*cur == ':') cur++;
1688             while ((*cur >= '0') && (*cur <= '9'))
1689                 minute = (minute * 10) + (*cur++ - '0');
1690         } else {
1691             while ((*cur >= '0') && (*cur <= '9'))
1692                 year = (year * 10) + (*cur++ - '0');
1693         }
1694         while (*cur == ' ') cur++;
1695         if (*cur == 0) return(0);
1696         i = 0;
1697         while ((*cur != '\n')  && (*cur != '\r')) {
1698             if (i < 150)
1699                 filename[i++] = *cur;
1700             cur++;
1701             if (*cur == 0) return(0);
1702         }
1703         filename[i] = 0;
1704         if ((*cur != '\n') && (*cur != '\r'))
1705             return(0);
1706         while ((*cur == '\n')  || (*cur == '\r'))
1707             cur++;
1708     }
1709     if (callback != NULL) {
1710         callback(userData, filename, attrib, owner, group, size, links,
1711                  year, month, day, hour, minute);
1712     }
1713     return(cur - list);
1714 }
1715
1716 /**
1717  * xmlNanoFTPList:
1718  * @ctx:  an FTP context
1719  * @callback:  the user callback
1720  * @userData:  the user callback data
1721  * @filename:  optional files to list
1722  *
1723  * Do a listing on the server. All files info are passed back
1724  * in the callbacks.
1725  *
1726  * Returns -1 incase of error, 0 otherwise
1727  */
1728
1729 int
1730 xmlNanoFTPList(void *ctx, ftpListCallback callback, void *userData,
1731                const char *filename) {
1732     xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
1733     char buf[4096 + 1];
1734     int len, res;
1735     int indx = 0, base;
1736     fd_set rfd, efd;
1737     struct timeval tv;
1738
1739     if (ctxt == NULL) return (-1);
1740     if (filename == NULL) {
1741         if (xmlNanoFTPCwd(ctxt, ctxt->path) < 1)
1742             return(-1);
1743         ctxt->dataFd = xmlNanoFTPGetConnection(ctxt);
1744         if (ctxt->dataFd == INVALID_SOCKET)
1745             return(-1);
1746         snprintf(buf, sizeof(buf), "LIST -L\r\n");
1747     } else {
1748         if (filename[0] != '/') {
1749             if (xmlNanoFTPCwd(ctxt, ctxt->path) < 1)
1750                 return(-1);
1751         }
1752         ctxt->dataFd = xmlNanoFTPGetConnection(ctxt);
1753         if (ctxt->dataFd == INVALID_SOCKET)
1754             return(-1);
1755         snprintf(buf, sizeof(buf), "LIST -L %s\r\n", filename);
1756     }
1757     buf[sizeof(buf) - 1] = 0;
1758     len = strlen(buf);
1759 #ifdef DEBUG_FTP
1760     xmlGenericError(xmlGenericErrorContext, "%s", buf);
1761 #endif
1762     res = send(ctxt->controlFd, SEND_ARG2_CAST buf, len, 0);
1763     if (res < 0) {
1764         __xmlIOErr(XML_FROM_FTP, 0, "send failed");
1765         closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1766         return(res);
1767     }
1768     res = xmlNanoFTPReadResponse(ctxt);
1769     if (res != 1) {
1770         closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1771         return(-res);
1772     }
1773
1774     do {
1775         tv.tv_sec = 1;
1776         tv.tv_usec = 0;
1777         FD_ZERO(&rfd);
1778         FD_SET(ctxt->dataFd, &rfd);
1779         FD_ZERO(&efd);
1780         FD_SET(ctxt->dataFd, &efd);
1781         res = select(ctxt->dataFd + 1, &rfd, NULL, &efd, &tv);
1782         if (res < 0) {
1783 #ifdef DEBUG_FTP
1784             perror("select");
1785 #endif
1786             closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1787             return(-1);
1788         }
1789         if (res == 0) {
1790             res = xmlNanoFTPCheckResponse(ctxt);
1791             if (res < 0) {
1792                 closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1793                 ctxt->dataFd = INVALID_SOCKET;
1794                 return(-1);
1795             }
1796             if (res == 2) {
1797                 closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1798                 return(0);
1799             }
1800
1801             continue;
1802         }
1803
1804         if ((len = recv(ctxt->dataFd, &buf[indx], sizeof(buf) - (indx + 1), 0)) < 0) {
1805             __xmlIOErr(XML_FROM_FTP, 0, "recv");
1806             closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1807             ctxt->dataFd = INVALID_SOCKET;
1808             return(-1);
1809         }
1810 #ifdef DEBUG_FTP
1811         write(1, &buf[indx], len);
1812 #endif
1813         indx += len;
1814         buf[indx] = 0;
1815         base = 0;
1816         do {
1817             res = xmlNanoFTPParseList(&buf[base], callback, userData);
1818             base += res;
1819         } while (res > 0);
1820
1821         memmove(&buf[0], &buf[base], indx - base);
1822         indx -= base;
1823     } while (len != 0);
1824     xmlNanoFTPCloseConnection(ctxt);
1825     return(0);
1826 }
1827
1828 /**
1829  * xmlNanoFTPGetSocket:
1830  * @ctx:  an FTP context
1831  * @filename:  the file to retrieve (or NULL if path is in context).
1832  *
1833  * Initiate fetch of the given file from the server.
1834  *
1835  * Returns the socket for the data connection, or <0 in case of error
1836  */
1837
1838
1839 SOCKET
1840 xmlNanoFTPGetSocket(void *ctx, const char *filename) {
1841     xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
1842     char buf[300];
1843     int res, len;
1844     if (ctx == NULL)
1845         return INVALID_SOCKET;
1846     if ((filename == NULL) && (ctxt->path == NULL))
1847         return INVALID_SOCKET;
1848     ctxt->dataFd = xmlNanoFTPGetConnection(ctxt);
1849     if (ctxt->dataFd == INVALID_SOCKET)
1850         return INVALID_SOCKET;
1851
1852     snprintf(buf, sizeof(buf), "TYPE I\r\n");
1853     len = strlen(buf);
1854 #ifdef DEBUG_FTP
1855     xmlGenericError(xmlGenericErrorContext, "%s", buf);
1856 #endif
1857     res = send(ctxt->controlFd, SEND_ARG2_CAST buf, len, 0);
1858     if (res < 0) {
1859         __xmlIOErr(XML_FROM_FTP, 0, "send failed");
1860         closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1861         return INVALID_SOCKET;
1862     }
1863     res = xmlNanoFTPReadResponse(ctxt);
1864     if (res != 2) {
1865         closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1866         return INVALID_SOCKET;
1867     }
1868     if (filename == NULL)
1869         snprintf(buf, sizeof(buf), "RETR %s\r\n", ctxt->path);
1870     else
1871         snprintf(buf, sizeof(buf), "RETR %s\r\n", filename);
1872     buf[sizeof(buf) - 1] = 0;
1873     len = strlen(buf);
1874 #ifdef DEBUG_FTP
1875     xmlGenericError(xmlGenericErrorContext, "%s", buf);
1876 #endif
1877     res = send(ctxt->controlFd, SEND_ARG2_CAST buf, len, 0);
1878     if (res < 0) {
1879         __xmlIOErr(XML_FROM_FTP, 0, "send failed");
1880         closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1881         return INVALID_SOCKET;
1882     }
1883     res = xmlNanoFTPReadResponse(ctxt);
1884     if (res != 1) {
1885         closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1886         return INVALID_SOCKET;
1887     }
1888     return(ctxt->dataFd);
1889 }
1890
1891 /**
1892  * xmlNanoFTPGet:
1893  * @ctx:  an FTP context
1894  * @callback:  the user callback
1895  * @userData:  the user callback data
1896  * @filename:  the file to retrieve
1897  *
1898  * Fetch the given file from the server. All data are passed back
1899  * in the callbacks. The last callback has a size of 0 block.
1900  *
1901  * Returns -1 incase of error, 0 otherwise
1902  */
1903
1904 int
1905 xmlNanoFTPGet(void *ctx, ftpDataCallback callback, void *userData,
1906               const char *filename) {
1907     xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
1908     char buf[4096];
1909     int len = 0, res;
1910     fd_set rfd;
1911     struct timeval tv;
1912
1913     if (ctxt == NULL) return(-1);
1914     if ((filename == NULL) && (ctxt->path == NULL))
1915         return(-1);
1916     if (callback == NULL)
1917         return(-1);
1918     if (xmlNanoFTPGetSocket(ctxt, filename) == INVALID_SOCKET)
1919         return(-1);
1920
1921     do {
1922         tv.tv_sec = 1;
1923         tv.tv_usec = 0;
1924         FD_ZERO(&rfd);
1925         FD_SET(ctxt->dataFd, &rfd);
1926         res = select(ctxt->dataFd + 1, &rfd, NULL, NULL, &tv);
1927         if (res < 0) {
1928 #ifdef DEBUG_FTP
1929             perror("select");
1930 #endif
1931             closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1932             return(-1);
1933         }
1934         if (res == 0) {
1935             res = xmlNanoFTPCheckResponse(ctxt);
1936             if (res < 0) {
1937                 closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1938                 ctxt->dataFd = INVALID_SOCKET;
1939                 return(-1);
1940             }
1941             if (res == 2) {
1942                 closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1943                 return(0);
1944             }
1945
1946             continue;
1947         }
1948         if ((len = recv(ctxt->dataFd, buf, sizeof(buf), 0)) < 0) {
1949             __xmlIOErr(XML_FROM_FTP, 0, "recv failed");
1950             callback(userData, buf, len);
1951             closesocket(ctxt->dataFd); ctxt->dataFd = INVALID_SOCKET;
1952             return(-1);
1953         }
1954         callback(userData, buf, len);
1955     } while (len != 0);
1956
1957     return(xmlNanoFTPCloseConnection(ctxt));
1958 }
1959
1960 /**
1961  * xmlNanoFTPRead:
1962  * @ctx:  the FTP context
1963  * @dest:  a buffer
1964  * @len:  the buffer length
1965  *
1966  * This function tries to read @len bytes from the existing FTP connection
1967  * and saves them in @dest. This is a blocking call.
1968  *
1969  * Returns the number of byte read. 0 is an indication of an end of connection.
1970  *         -1 indicates a parameter error.
1971  */
1972 int
1973 xmlNanoFTPRead(void *ctx, void *dest, int len) {
1974     xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
1975
1976     if (ctx == NULL) return(-1);
1977     if (ctxt->dataFd == INVALID_SOCKET) return(0);
1978     if (dest == NULL) return(-1);
1979     if (len <= 0) return(0);
1980
1981     len = recv(ctxt->dataFd, dest, len, 0);
1982     if (len <= 0) {
1983         if (len < 0)
1984             __xmlIOErr(XML_FROM_FTP, 0, "recv failed");
1985         xmlNanoFTPCloseConnection(ctxt);
1986     }
1987 #ifdef DEBUG_FTP
1988     xmlGenericError(xmlGenericErrorContext, "Recvd %d bytes\n", len);
1989 #endif
1990     return(len);
1991 }
1992
1993 /**
1994  * xmlNanoFTPOpen:
1995  * @URL: the URL to the resource
1996  *
1997  * Start to fetch the given ftp:// resource
1998  *
1999  * Returns an FTP context, or NULL
2000  */
2001
2002 void*
2003 xmlNanoFTPOpen(const char *URL) {
2004     xmlNanoFTPCtxtPtr ctxt;
2005     SOCKET sock;
2006
2007     xmlNanoFTPInit();
2008     if (URL == NULL) return(NULL);
2009     if (strncmp("ftp://", URL, 6)) return(NULL);
2010
2011     ctxt = (xmlNanoFTPCtxtPtr) xmlNanoFTPNewCtxt(URL);
2012     if (ctxt == NULL) return(NULL);
2013     if (xmlNanoFTPConnect(ctxt) < 0) {
2014         xmlNanoFTPFreeCtxt(ctxt);
2015         return(NULL);
2016     }
2017     sock = xmlNanoFTPGetSocket(ctxt, ctxt->path);
2018     if (sock == INVALID_SOCKET) {
2019         xmlNanoFTPFreeCtxt(ctxt);
2020         return(NULL);
2021     }
2022     return(ctxt);
2023 }
2024
2025 /**
2026  * xmlNanoFTPClose:
2027  * @ctx: an FTP context
2028  *
2029  * Close the connection and both control and transport
2030  *
2031  * Returns -1 incase of error, 0 otherwise
2032  */
2033
2034 int
2035 xmlNanoFTPClose(void *ctx) {
2036     xmlNanoFTPCtxtPtr ctxt = (xmlNanoFTPCtxtPtr) ctx;
2037
2038     if (ctxt == NULL)
2039         return(-1);
2040
2041     if (ctxt->dataFd != INVALID_SOCKET) {
2042         closesocket(ctxt->dataFd);
2043         ctxt->dataFd = INVALID_SOCKET;
2044     }
2045     if (ctxt->controlFd != INVALID_SOCKET) {
2046         xmlNanoFTPQuit(ctxt);
2047         closesocket(ctxt->controlFd);
2048         ctxt->controlFd = INVALID_SOCKET;
2049     }
2050     xmlNanoFTPFreeCtxt(ctxt);
2051     return(0);
2052 }
2053
2054 #ifdef STANDALONE
2055 /************************************************************************
2056  *                                                                      *
2057  *                      Basic test in Standalone mode                   *
2058  *                                                                      *
2059  ************************************************************************/
2060 static
2061 void ftpList(void *userData, const char *filename, const char* attrib,
2062              const char *owner, const char *group, unsigned long size, int links,
2063              int year, const char *month, int day, int hour, int minute) {
2064     xmlGenericError(xmlGenericErrorContext,
2065             "%s %s %s %ld %s\n", attrib, owner, group, size, filename);
2066 }
2067 static
2068 void ftpData(void *userData, const char *data, int len) {
2069     if (userData == NULL) return;
2070     if (len <= 0) {
2071         fclose((FILE*)userData);
2072         return;
2073     }
2074     fwrite(data, len, 1, (FILE*)userData);
2075 }
2076
2077 int main(int argc, char **argv) {
2078     void *ctxt;
2079     FILE *output;
2080     char *tstfile = NULL;
2081
2082     xmlNanoFTPInit();
2083     if (argc > 1) {
2084         ctxt = xmlNanoFTPNewCtxt(argv[1]);
2085         if (xmlNanoFTPConnect(ctxt) < 0) {
2086             xmlGenericError(xmlGenericErrorContext,
2087                     "Couldn't connect to %s\n", argv[1]);
2088             exit(1);
2089         }
2090         if (argc > 2)
2091             tstfile = argv[2];
2092     } else
2093         ctxt = xmlNanoFTPConnectTo("localhost", 0);
2094     if (ctxt == NULL) {
2095         xmlGenericError(xmlGenericErrorContext,
2096                 "Couldn't connect to localhost\n");
2097         exit(1);
2098     }
2099     xmlNanoFTPList(ctxt, ftpList, NULL, tstfile);
2100     output = fopen("/tmp/tstdata", "w");
2101     if (output != NULL) {
2102         if (xmlNanoFTPGet(ctxt, ftpData, (void *) output, tstfile) < 0)
2103             xmlGenericError(xmlGenericErrorContext,
2104                     "Failed to get file\n");
2105
2106     }
2107     xmlNanoFTPClose(ctxt);
2108     xmlMemoryDump();
2109     exit(0);
2110 }
2111 #endif /* STANDALONE */
2112 #else /* !LIBXML_FTP_ENABLED */
2113 #ifdef STANDALONE
2114 #include <stdio.h>
2115 int main(int argc, char **argv) {
2116     xmlGenericError(xmlGenericErrorContext,
2117             "%s : FTP support not compiled in\n", argv[0]);
2118     return(0);
2119 }
2120 #endif /* STANDALONE */
2121 #endif /* LIBXML_FTP_ENABLED */
2122 #define bottom_nanoftp
2123 #include "elfgcchack.h"