Moved the NI_WITHSCOPEID magic #ifdef to the top of the file and made sure
[platform/upstream/curl.git] / lib / ftp.c
1 /***************************************************************************
2  *                                  _   _ ____  _     
3  *  Project                     ___| | | |  _ \| |    
4  *                             / __| | | | |_) | |    
5  *                            | (__| |_| |  _ <| |___ 
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2004, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
10  * This software is licensed as described in the file COPYING, which
11  * you should have received as part of this distribution. The terms
12  * are also available at http://curl.haxx.se/docs/copyright.html.
13  * 
14  * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15  * copies of the Software, and permit persons to whom the Software is
16  * furnished to do so, under the terms of the COPYING file.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  * $Id$
22  ***************************************************************************/
23
24 #include "setup.h"
25
26 #ifndef CURL_DISABLE_FTP
27 #include <stdio.h>
28 #include <string.h>
29 #include <stdlib.h>
30 #include <stdarg.h>
31 #include <ctype.h>
32 #include <errno.h>
33
34 #ifdef HAVE_UNISTD_H
35 #include <unistd.h>
36 #endif
37 #ifdef HAVE_SYS_SELECT_H
38 #include <sys/select.h>
39 #endif
40
41 #if defined(WIN32) && !defined(__GNUC__) || defined(__MINGW32__)
42
43 #else /* some kind of unix */
44 #ifdef HAVE_SYS_SOCKET_H
45 #include <sys/socket.h>
46 #endif
47 #include <sys/types.h>
48 #ifdef HAVE_NETINET_IN_H
49 #include <netinet/in.h>
50 #endif
51 #ifdef HAVE_ARPA_INET_H
52 #include <arpa/inet.h>
53 #endif
54 #include <sys/utsname.h>
55 #ifdef HAVE_NETDB_H
56 #include <netdb.h>
57 #endif
58 #ifdef  VMS
59 #include <in.h>
60 #include <inet.h>
61 #endif
62 #endif
63
64 #if defined(WIN32) && defined(__GNUC__) || defined(__MINGW32__)
65 #include <errno.h>
66 #endif
67
68 #if (defined(NETWARE) && defined(__NOVELL_LIBC__))
69 #undef in_addr_t
70 #define in_addr_t unsigned long
71 #endif
72
73 #include <curl/curl.h>
74 #include "urldata.h"
75 #include "sendf.h"
76
77 #include "if2ip.h"
78 #include "hostip.h"
79 #include "progress.h"
80 #include "transfer.h"
81 #include "escape.h"
82 #include "http.h" /* for HTTP proxy tunnel stuff */
83 #include "ftp.h"
84
85 #ifdef HAVE_KRB4
86 #include "security.h"
87 #include "krb4.h"
88 #endif
89
90 #include "strtoofft.h"
91 #include "strequal.h"
92 #include "ssluse.h"
93 #include "connect.h"
94 #include "strerror.h"
95
96 #if defined(HAVE_INET_NTOA_R) && !defined(HAVE_INET_NTOA_R_DECL)
97 #include "inet_ntoa_r.h"
98 #endif
99
100 #define _MPRINTF_REPLACE /* use our functions only */
101 #include <curl/mprintf.h>
102
103 /* The last #include file should be: */
104 #ifdef CURLDEBUG
105 #include "memdebug.h"
106 #endif
107
108 #ifdef NI_WITHSCOPEID
109 #define NIFLAGS NI_NUMERICHOST | NI_NUMERICSERV | NI_WITHSCOPEID
110 #else
111 #define NIFLAGS NI_NUMERICHOST | NI_NUMERICSERV
112 #endif
113
114 /* Local API functions */
115 static CURLcode ftp_sendquote(struct connectdata *conn,
116                               struct curl_slist *quote);
117 static CURLcode ftp_cwd(struct connectdata *conn, char *path);
118 static CURLcode ftp_mkd(struct connectdata *conn, char *path);
119 static CURLcode ftp_cwd_and_mkd(struct connectdata *conn, char *path);
120
121 /* easy-to-use macro: */
122 #define FTPSENDF(x,y,z) if((result = Curl_ftpsendf(x,y,z))) return result
123
124 static void freedirs(struct FTP *ftp)
125 {
126   int i;
127   for (i=0; ftp->dirs[i]; i++){
128     free(ftp->dirs[i]);
129     ftp->dirs[i]=NULL;
130   }
131 }
132
133 /***********************************************************************
134  *
135  * AllowServerConnect()
136  *
137  * When we've issue the PORT command, we have told the server to connect
138  * to us. This function will sit and wait here until the server has
139  * connected.
140  *
141  */
142 static CURLcode AllowServerConnect(struct connectdata *conn)
143 {
144   fd_set rdset;
145   struct timeval dt;
146   struct SessionHandle *data = conn->data;
147   curl_socket_t sock = conn->sock[SECONDARYSOCKET];
148   struct timeval now = Curl_tvnow();
149   long timespent = Curl_tvdiff(Curl_tvnow(), now)/1000;
150   long timeout = data->set.connecttimeout?data->set.connecttimeout:
151     (data->set.timeout?data->set.timeout: 0);
152   
153   FD_ZERO(&rdset);
154
155   FD_SET(sock, &rdset);
156   
157   if(timeout) {
158     timeout -= timespent;
159     if(timeout<=0) {
160       failf(data, "Timed out before server could connect to us");
161       return CURLE_OPERATION_TIMEDOUT;
162     }
163   }
164
165   /* we give the server 60 seconds to connect to us, or a custom timeout */
166   dt.tv_sec = (int)(timeout?timeout:60);
167   dt.tv_usec = 0;
168
169   switch (select(sock+1, &rdset, NULL, NULL, &dt)) {
170   case -1: /* error */
171     /* let's die here */
172     failf(data, "Error while waiting for server connect");
173     return CURLE_FTP_PORT_FAILED;
174   case 0:  /* timeout */
175     /* let's die here */
176     failf(data, "Timeout while waiting for server connect");
177     return CURLE_FTP_PORT_FAILED;
178   default:
179     /* we have received data here */
180     {
181       curl_socket_t s;
182       size_t size = sizeof(struct sockaddr_in);
183       struct sockaddr_in add;
184
185       getsockname(sock, (struct sockaddr *) &add, (socklen_t *)&size);
186       s=accept(sock, (struct sockaddr *) &add, (socklen_t *)&size);
187
188       sclose(sock); /* close the first socket */
189
190       if (CURL_SOCKET_BAD == s) {
191         /* DIE! */
192         failf(data, "Error accept()ing server connect");
193         return CURLE_FTP_PORT_FAILED;
194       }
195       infof(data, "Connection accepted from server\n");
196
197       conn->sock[SECONDARYSOCKET] = s;
198       Curl_nonblock(s, TRUE); /* enable non-blocking */
199     }
200     break;
201   }
202
203   return CURLE_OK;
204 }
205
206
207 /* --- parse FTP server responses --- */
208
209 /*
210  * Curl_GetFTPResponse() is supposed to be invoked after each command sent to
211  * a remote FTP server. This function will wait and read all lines of the
212  * response and extract the relevant return code for the invoking function.
213  */
214
215 CURLcode Curl_GetFTPResponse(ssize_t *nreadp, /* return number of bytes read */
216                              struct connectdata *conn,
217                              int *ftpcode) /* return the ftp-code */
218 {
219   /* Brand new implementation.
220    * We cannot read just one byte per read() and then go back to select()
221    * as it seems that the OpenSSL read() stuff doesn't grok that properly.
222    *
223    * Alas, read as much as possible, split up into lines, use the ending
224    * line in a response or continue reading.  */
225
226   curl_socket_t sockfd = conn->sock[FIRSTSOCKET];
227   int perline; /* count bytes per line */
228   bool keepon=TRUE;
229   ssize_t gotbytes;
230   char *ptr;
231   long timeout;              /* timeout in seconds */
232   struct timeval interval;
233   fd_set rkeepfd;
234   fd_set readfd;
235   struct SessionHandle *data = conn->data;
236   char *line_start;
237   int code=0; /* default ftp "error code" to return */
238   char *buf = data->state.buffer;
239   CURLcode result = CURLE_OK;
240   struct FTP *ftp = conn->proto.ftp;
241   struct timeval now = Curl_tvnow();
242
243   if (ftpcode)
244     *ftpcode = 0; /* 0 for errors */
245
246   FD_ZERO (&readfd);            /* clear it */
247   FD_SET (sockfd, &readfd);     /* read socket */
248
249   /* get this in a backup variable to be able to restore it on each lap in the
250      select() loop */
251   rkeepfd = readfd;
252
253   ptr=buf;
254   line_start = buf;
255
256   *nreadp=0;
257   perline=0;
258   keepon=TRUE;
259
260   while((*nreadp<BUFSIZE) && (keepon && !result)) {
261     /* check and reset timeout value every lap */
262     if(data->set.ftp_response_timeout )
263       /* if CURLOPT_FTP_RESPONSE_TIMEOUT is set, use that to determine
264          remaining time.  Also, use "now" as opposed to "conn->now"
265          because ftp_response_timeout is only supposed to govern
266          the response for any given ftp response, not for the time
267          from connect to the given ftp response. */
268       timeout = data->set.ftp_response_timeout - /* timeout time */
269         Curl_tvdiff(Curl_tvnow(), now)/1000; /* spent time */
270     else if(data->set.timeout)
271       /* if timeout is requested, find out how much remaining time we have */
272       timeout = data->set.timeout - /* timeout time */
273         Curl_tvdiff(Curl_tvnow(), conn->now)/1000; /* spent time */
274     else
275       /* Even without a requested timeout, we only wait response_time
276          seconds for the full response to arrive before we bail out */
277       timeout = ftp->response_time -
278         Curl_tvdiff(Curl_tvnow(), now)/1000; /* spent time */
279
280     if(timeout <=0 ) {
281       failf(data, "FTP response timeout");
282       return CURLE_OPERATION_TIMEDOUT; /* already too little time */
283     }
284
285     if(!ftp->cache) {
286       readfd = rkeepfd;            /* set every lap */
287       interval.tv_sec = 1; /* use 1 second timeout intervals */
288       interval.tv_usec = 0;
289
290       switch (select (sockfd+1, &readfd, NULL, NULL, &interval)) {
291       case -1: /* select() error, stop reading */
292         result = CURLE_RECV_ERROR;
293         failf(data, "FTP response aborted due to select() error: %d", errno);
294         break;
295       case 0: /* timeout */
296         if(Curl_pgrsUpdate(conn))
297           return CURLE_ABORTED_BY_CALLBACK;
298         continue; /* just continue in our loop for the timeout duration */
299
300       default:
301         break;
302       }
303     }
304     if(CURLE_OK == result) {
305       /*
306        * This code previously didn't use the kerberos sec_read() code
307        * to read, but when we use Curl_read() it may do so. Do confirm
308        * that this is still ok and then remove this comment!
309        */
310       if(ftp->cache) {
311         /* we had data in the "cache", copy that instead of doing an actual
312          * read
313          *
314          * Dave Meyer, December 2003:
315          * ftp->cache_size is cast to int here.  This should be safe,
316          * because it would have been populated with something of size
317          * int to begin with, even though its datatype may be larger
318          * than an int.
319          */
320         memcpy(ptr, ftp->cache, (int)ftp->cache_size);
321         gotbytes = (int)ftp->cache_size;
322         free(ftp->cache);    /* free the cache */
323         ftp->cache = NULL;   /* clear the pointer */
324         ftp->cache_size = 0; /* zero the size just in case */
325       }
326       else {
327         int res = Curl_read(conn, sockfd, ptr, BUFSIZE-*nreadp, &gotbytes);
328         if(res < 0)
329           /* EWOULDBLOCK */
330           continue; /* go looping again */
331
332         if(CURLE_OK != res)
333           keepon = FALSE;
334       }
335
336       if(!keepon)
337         ;
338       else if(gotbytes <= 0) {
339         keepon = FALSE;
340         result = CURLE_RECV_ERROR;
341         failf(data, "FTP response reading failed");
342       }
343       else {
344         /* we got a whole chunk of data, which can be anything from one
345          * byte to a set of lines and possible just a piece of the last
346          * line */
347         int i;
348
349         *nreadp += gotbytes;
350         for(i = 0; i < gotbytes; ptr++, i++) {
351           perline++;
352           if(*ptr=='\n') {
353             /* a newline is CRLF in ftp-talk, so the CR is ignored as
354                the line isn't really terminated until the LF comes */
355
356             /* output debug output if that is requested */
357             if(data->set.verbose)
358               Curl_debug(data, CURLINFO_HEADER_IN, line_start, perline);
359
360             /*
361              * We pass all response-lines to the callback function registered
362              * for "headers". The response lines can be seen as a kind of
363              * headers.
364              */
365             result = Curl_client_write(data, CLIENTWRITE_HEADER,
366                                        line_start, perline);
367             if(result)
368               return result;
369                                        
370 #define lastline(line) (isdigit((int)line[0]) && isdigit((int)line[1]) && \
371                         isdigit((int)line[2]) && (' ' == line[3]))
372
373             if(perline>3 && lastline(line_start)) {
374               /* This is the end of the last line, copy the last
375                * line to the start of the buffer and zero terminate,
376                * for old times sake (and krb4)! */
377               char *meow;
378               int n;
379               for(meow=line_start, n=0; meow<ptr; meow++, n++)
380                 buf[n] = *meow;
381               *meow=0; /* zero terminate */
382               keepon=FALSE;
383               line_start = ptr+1; /* advance pointer */
384               i++; /* skip this before getting out */
385               break;
386             }
387             perline=0; /* line starts over here */
388             line_start = ptr+1;
389           }
390         }
391         if(!keepon && (i != gotbytes)) {
392           /* We found the end of the response lines, but we didn't parse the
393              full chunk of data we have read from the server. We therefore
394              need to store the rest of the data to be checked on the next
395              invoke as it may actually contain another end of response
396              already!  Cleverly figured out by Eric Lavigne in December
397              2001. */
398           ftp->cache_size = gotbytes - i;
399           ftp->cache = (char *)malloc((int)ftp->cache_size);
400           if(ftp->cache)
401             memcpy(ftp->cache, line_start, (int)ftp->cache_size);
402           else
403             return CURLE_OUT_OF_MEMORY; /**BANG**/
404         }
405       } /* there was data */
406     } /* if(no error) */
407   } /* while there's buffer left and loop is requested */
408
409   if(!result)
410     code = atoi(buf);
411
412 #ifdef HAVE_KRB4
413   /* handle the security-oriented responses 6xx ***/
414   /* FIXME: some errorchecking perhaps... ***/
415   switch(code) {
416   case 631:
417     Curl_sec_read_msg(conn, buf, prot_safe);
418     break;
419   case 632:
420     Curl_sec_read_msg(conn, buf, prot_private);
421     break;
422   case 633:
423     Curl_sec_read_msg(conn, buf, prot_confidential);
424     break;
425   default:
426     /* normal ftp stuff we pass through! */
427     break;
428   }
429 #endif
430
431   if(ftpcode)
432     *ftpcode=code; /* return the initial number like this */
433
434   /* store the latest code for later retrieval */
435   conn->data->info.httpcode=code;
436
437   return result;
438 }
439
440 static const char *ftpauth[]= {
441   "SSL", "TLS", NULL
442 };
443
444 /*
445  * Curl_ftp_connect() should do everything that is to be considered a part of
446  * the connection phase.
447  */
448 CURLcode Curl_ftp_connect(struct connectdata *conn)
449 {
450   /* this is FTP and no proxy */
451   ssize_t nread;
452   struct SessionHandle *data=conn->data;
453   char *buf = data->state.buffer; /* this is our buffer */
454   struct FTP *ftp;
455   CURLcode result;
456   int ftpcode, try;
457
458   ftp = (struct FTP *)malloc(sizeof(struct FTP));
459   if(!ftp)
460     return CURLE_OUT_OF_MEMORY;
461
462   memset(ftp, 0, sizeof(struct FTP));
463   conn->proto.ftp = ftp;
464
465   /* We always support persistant connections on ftp */
466   conn->bits.close = FALSE;
467
468   /* get some initial data into the ftp struct */
469   ftp->bytecountp = &conn->bytecount;
470
471   /* no need to duplicate them, this connectdata struct won't change */
472   ftp->user = conn->user;
473   ftp->passwd = conn->passwd;
474   ftp->response_time = 3600; /* set default response time-out */
475
476   if (data->set.tunnel_thru_httpproxy) {
477     /* We want "seamless" FTP operations through HTTP proxy tunnel */
478     result = Curl_ConnectHTTPProxyTunnel(conn, FIRSTSOCKET,
479                                          conn->hostname, conn->remote_port);
480     if(CURLE_OK != result)
481       return result;
482   }
483
484   if(conn->protocol & PROT_FTPS) {
485     /* FTPS is simply ftp with SSL for the control channel */
486     /* now, perform the SSL initialization for this socket */
487     result = Curl_SSLConnect(conn, FIRSTSOCKET);
488     if(result)
489       return result;
490   }
491
492   /* The first thing we do is wait for the "220*" line: */
493   result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
494   if(result)
495     return result;
496
497   if(ftpcode != 220) {
498     failf(data, "This doesn't seem like a nice ftp-server response");
499     return CURLE_FTP_WEIRD_SERVER_REPLY;
500   }
501
502 #ifdef HAVE_KRB4
503   /* if not anonymous login, try a secure login */
504   if(data->set.krb4) {
505
506     /* request data protection level (default is 'clear') */
507     Curl_sec_request_prot(conn, "private");
508
509     /* We set private first as default, in case the line below fails to
510        set a valid level */
511     Curl_sec_request_prot(conn, data->set.krb4_level);
512
513     if(Curl_sec_login(conn) != 0)
514       infof(data, "Logging in with password in cleartext!\n");
515     else
516       infof(data, "Authentication successful\n");
517   }
518 #endif
519
520   if(data->set.ftp_ssl && !conn->ssl[FIRSTSOCKET].use) {
521     /* we don't have a SSL/TLS connection, try a FTPS connection now */
522
523     for (try = 0; ftpauth[try]; try++) {
524
525       FTPSENDF(conn, "AUTH %s", ftpauth[try]);
526
527       result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
528
529       if(result)
530         return result;
531
532       /* RFC2228 (page 5) says:
533        *
534        * If the server is willing to accept the named security mechanism, and
535        * does not require any security data, it must respond with reply code
536        * 234/334.
537        */
538
539       if((ftpcode == 234) || (ftpcode == 334)) {
540         result = Curl_SSLConnect(conn, FIRSTSOCKET);
541         if(result)
542           return result;
543         conn->protocol |= PROT_FTPS;
544         conn->ssl[SECONDARYSOCKET].use = FALSE; /* clear-text data */
545         break;
546       }
547     }
548   }
549   
550   /* send USER */
551   FTPSENDF(conn, "USER %s", ftp->user?ftp->user:"");
552
553   /* wait for feedback */
554   result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
555   if(result)
556     return result;
557
558   if(ftpcode == 530) {
559     /* 530 User ... access denied
560        (the server denies to log the specified user) */
561     failf(data, "Access denied: %s", &buf[4]);
562     return CURLE_FTP_ACCESS_DENIED;
563   }
564   else if(ftpcode == 331) {
565     /* 331 Password required for ...
566        (the server requires to send the user's password too) */
567     FTPSENDF(conn, "PASS %s", ftp->passwd?ftp->passwd:"");
568     result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
569     if(result)
570       return result;
571
572     if(ftpcode == 530) {
573       /* 530 Login incorrect.
574          (the username and/or the password are incorrect) */
575       failf(data, "the username and/or the password are incorrect");
576       return CURLE_FTP_USER_PASSWORD_INCORRECT;
577     }
578     else if(ftpcode == 230) {
579       /* 230 User ... logged in.
580          (user successfully logged in) */
581         
582       infof(data, "We have successfully logged in\n");
583     }
584     else {
585       failf(data, "Odd return code after PASS");
586       return CURLE_FTP_WEIRD_PASS_REPLY;
587     }
588   }
589   else if(buf[0] == '2') {
590     /* 230 User ... logged in.
591        (the user logged in without password) */
592     infof(data, "We have successfully logged in\n");
593     if (conn->ssl[FIRSTSOCKET].use) {
594 #ifdef HAVE_KRB4
595         /* we are logged in (with Kerberos)
596          * now set the requested protection level
597          */
598     if(conn->sec_complete)
599       Curl_sec_set_protection_level(conn);
600
601     /* we may need to issue a KAUTH here to have access to the files
602      * do it if user supplied a password
603      */
604     if(conn->passwd && *conn->passwd) {
605       result = Curl_krb_kauth(conn);
606       if(result)
607         return result;
608     }
609 #endif
610   }
611   }
612   else {
613     failf(data, "Odd return code after USER");
614     return CURLE_FTP_WEIRD_USER_REPLY;
615   }
616
617   if(conn->ssl[FIRSTSOCKET].use) {
618     /* PBSZ = PROTECTION BUFFER SIZE.
619
620        The 'draft-murray-auth-ftp-ssl' (draft 12, page 7) says:
621
622        Specifically, the PROT command MUST be preceded by a PBSZ command
623        and a PBSZ command MUST be preceded by a successful security data
624        exchange (the TLS negotiation in this case)
625
626        ... (and on page 8):
627          
628        Thus the PBSZ command must still be issued, but must have a parameter
629        of '0' to indicate that no buffering is taking place and the data
630        connection should not be encapsulated.
631     */
632     FTPSENDF(conn, "PBSZ %d", 0);
633     result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
634     if(result)
635       return result;
636
637     /* For TLS, the data connection can have one of two security levels.
638
639        1)Clear (requested by 'PROT C')
640
641        2)Private (requested by 'PROT P')
642     */
643     if(!conn->ssl[SECONDARYSOCKET].use) {
644       FTPSENDF(conn, "PROT %c", 'P');
645       result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
646       if(result)
647         return result;
648     
649       if(ftpcode == 200)
650         /* We have enabled SSL for the data connection! */
651         conn->ssl[SECONDARYSOCKET].use = TRUE;
652
653       /* FTP servers typically responds with 500 if they decide to reject
654          our 'P' request */
655     }
656   }
657
658   /* send PWD to discover our entry point */
659   FTPSENDF(conn, "PWD", NULL);
660
661   /* wait for feedback */
662   result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
663   if(result)
664     return result;
665
666   if(ftpcode == 257) {
667     char *dir = (char *)malloc(nread+1);
668     char *store=dir;
669     char *ptr=&buf[4]; /* start on the first letter */
670
671     if(!dir)
672       return CURLE_OUT_OF_MEMORY;
673     
674     /* Reply format is like
675        257<space>"<directory-name>"<space><commentary> and the RFC959 says
676
677        The directory name can contain any character; embedded double-quotes
678        should be escaped by double-quotes (the "quote-doubling" convention).
679     */
680     if('\"' == *ptr) {
681       /* it started good */
682       ptr++;
683       while(ptr && *ptr) {
684         if('\"' == *ptr) {
685           if('\"' == ptr[1]) {
686             /* "quote-doubling" */
687             *store = ptr[1];
688             ptr++;
689           }
690           else {
691             /* end of path */
692             *store = '\0'; /* zero terminate */
693             break; /* get out of this loop */
694           }
695         }
696         else
697           *store = *ptr;
698         store++;
699         ptr++;
700       }
701       ftp->entrypath =dir; /* remember this */
702       infof(data, "Entry path is '%s'\n", ftp->entrypath);
703     }
704     else {
705       /* couldn't get the path */
706       free(dir);
707       infof(data, "Failed to figure out path\n");
708     }
709
710   }
711   else {
712     /* We couldn't read the PWD response! */
713   }
714
715   return CURLE_OK;
716 }
717
718 /***********************************************************************
719  *
720  * Curl_ftp_done()
721  *
722  * The DONE function. This does what needs to be done after a single DO has
723  * performed.
724  *
725  * Input argument is already checked for validity.
726  */
727 CURLcode Curl_ftp_done(struct connectdata *conn)
728 {
729   struct SessionHandle *data = conn->data;
730   struct FTP *ftp = conn->proto.ftp;
731   ssize_t nread;
732   int ftpcode;
733   CURLcode result=CURLE_OK;
734
735   /* free the dir tree parts */
736   freedirs(ftp);
737
738   if(ftp->file) {
739     free(ftp->file);
740     ftp->file = NULL;
741   }
742
743   if(data->set.upload) {
744     if((-1 != data->set.infilesize) &&
745        (data->set.infilesize != *ftp->bytecountp) &&
746        !data->set.crlf) {
747       failf(data, "Uploaded unaligned file size (%" FORMAT_OFF_T
748             " out of %" FORMAT_OFF_T " bytes)",
749             *ftp->bytecountp, data->set.infilesize);
750       conn->bits.close = TRUE; /* close this connection since we don't
751                                   know what state this error leaves us in */
752       return CURLE_PARTIAL_FILE;
753     }
754   }
755   else {
756     if((-1 != conn->size) && (conn->size != *ftp->bytecountp) &&
757        (conn->maxdownload != *ftp->bytecountp)) {
758       failf(data, "Received only partial file: %" FORMAT_OFF_T " bytes",
759             *ftp->bytecountp);
760       conn->bits.close = TRUE; /* close this connection since we don't
761                                   know what state this error leaves us in */
762       return CURLE_PARTIAL_FILE;
763     }
764     else if(!ftp->dont_check &&
765             !*ftp->bytecountp &&
766             (conn->size>0)) {
767       /* We consider this an error, but there's no true FTP error received
768          why we need to continue to "read out" the server response too.
769          We don't want to leave a "waiting" server reply if we'll get told
770          to make a second request on this same connection! */
771       failf(data, "No data was received!");
772       result = CURLE_FTP_COULDNT_RETR_FILE;
773     }
774   }
775
776 #ifdef HAVE_KRB4
777   Curl_sec_fflush_fd(conn, conn->sock[SECONDARYSOCKET]);
778 #endif
779   /* shut down the socket to inform the server we're done */
780   sclose(conn->sock[SECONDARYSOCKET]);
781   conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD;
782
783   if(!ftp->no_transfer) {
784     /* Let's see what the server says about the transfer we just performed,
785        but lower the timeout as sometimes this connection has died while 
786        the data has been transfered. This happens when doing through NATs
787        etc that abandon old silent connections.
788     */
789     ftp->response_time = 60; /* give it only a minute for now */
790
791     result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
792
793     ftp->response_time = 3600; /* set this back to one hour waits */
794   
795     if(!nread && (CURLE_OPERATION_TIMEDOUT == result)) {
796       failf(data, "control connection looks dead");
797       return result;
798     }
799
800     if(result)
801       return result;
802
803     if(!ftp->dont_check) {
804       /* 226 Transfer complete, 250 Requested file action okay, completed. */
805       if((ftpcode != 226) && (ftpcode != 250)) {
806         failf(data, "server did not report OK, got %d", ftpcode);
807         return CURLE_FTP_WRITE_ERROR;
808       }
809     }
810   }
811
812   /* clear these for next connection */
813   ftp->no_transfer = FALSE;
814   ftp->dont_check = FALSE; 
815
816   /* Send any post-transfer QUOTE strings? */
817   if(!result && data->set.postquote)
818     result = ftp_sendquote(conn, data->set.postquote);
819
820   return result;
821 }
822
823 /***********************************************************************
824  *
825  * ftp_sendquote()
826  *
827  * Where a 'quote' means a list of custom commands to send to the server.
828  * The quote list is passed as an argument.
829  */
830
831 static 
832 CURLcode ftp_sendquote(struct connectdata *conn, struct curl_slist *quote)
833 {
834   struct curl_slist *item;
835   ssize_t nread;
836   int ftpcode;
837   CURLcode result;
838
839   item = quote;
840   while (item) {
841     if (item->data) {
842       FTPSENDF(conn, "%s", item->data);
843
844       result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
845       if (result)
846         return result;
847
848       if (ftpcode >= 400) {
849         failf(conn->data, "QUOT string not accepted: %s", item->data);
850         return CURLE_FTP_QUOTE_ERROR;
851       }
852     }
853
854     item = item->next;
855   }
856
857   return CURLE_OK;
858 }
859
860 /***********************************************************************
861  *
862  * ftp_getfiletime()
863  *
864  * Get the timestamp of the given file.
865  */
866 static
867 CURLcode ftp_getfiletime(struct connectdata *conn, char *file)
868 {
869   CURLcode result=CURLE_OK;
870   int ftpcode; /* for ftp status */
871   ssize_t nread;
872   char *buf = conn->data->state.buffer;
873
874   /* we have requested to get the modified-time of the file, this is yet
875      again a grey area as the MDTM is not kosher RFC959 */
876   FTPSENDF(conn, "MDTM %s", file);
877
878   result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
879   if(result)
880     return result;
881
882   switch(ftpcode) {
883   case 213:
884     {
885       /* we got a time. Format should be: "YYYYMMDDHHMMSS[.sss]" where the
886          last .sss part is optional and means fractions of a second */
887       int year, month, day, hour, minute, second;
888       if(6 == sscanf(buf+4, "%04d%02d%02d%02d%02d%02d",
889                      &year, &month, &day, &hour, &minute, &second)) {
890         /* we have a time, reformat it */
891         time_t secs=time(NULL);
892         sprintf(buf, "%04d%02d%02d %02d:%02d:%02d GMT",
893                 year, month, day, hour, minute, second);
894         /* now, convert this into a time() value: */
895         conn->data->info.filetime = curl_getdate(buf, &secs);
896       }
897     }
898     break;
899   default:
900     infof(conn->data, "unsupported MDTM reply format\n");
901     break;
902   case 550: /* "No such file or directory" */
903     failf(conn->data, "Given file does not exist");
904     result = CURLE_FTP_COULDNT_RETR_FILE;
905     break;
906   }
907   return  result;
908 }
909
910 /***********************************************************************
911  *
912  * ftp_transfertype()
913  *
914  * Set transfer type. We only deal with ASCII or BINARY so this function
915  * sets one of them.
916  */
917 static CURLcode ftp_transfertype(struct connectdata *conn,
918                                   bool ascii)
919 {
920   struct SessionHandle *data = conn->data;
921   int ftpcode;
922   ssize_t nread;
923   CURLcode result;
924
925   FTPSENDF(conn, "TYPE %s", ascii?"A":"I");
926
927   result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
928   if(result)
929     return result;
930   
931   if(ftpcode != 200) {
932     failf(data, "Couldn't set %s mode",
933           ascii?"ASCII":"binary");
934     return ascii? CURLE_FTP_COULDNT_SET_ASCII:CURLE_FTP_COULDNT_SET_BINARY;
935   }
936
937   return CURLE_OK;
938 }
939
940 /***********************************************************************
941  *
942  * ftp_getsize()
943  *
944  * Returns the file size (in bytes) of the given remote file.
945  */
946
947 static
948 CURLcode ftp_getsize(struct connectdata *conn, char *file,
949                      curl_off_t *size)
950 {
951   struct SessionHandle *data = conn->data;
952   int ftpcode;
953   ssize_t nread;
954   char *buf=data->state.buffer;
955   CURLcode result;
956
957   FTPSENDF(conn, "SIZE %s", file);
958   result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
959   if(result)
960     return result;
961
962   if(ftpcode == 213) {
963     /* get the size from the ascii string: */
964     *size = strtoofft(buf+4, NULL, 0);
965   }
966   else
967     return CURLE_FTP_COULDNT_GET_SIZE;
968
969   return CURLE_OK;
970 }
971
972 /***************************************************************************
973  *
974  * ftp_pasv_verbose()
975  *
976  * This function only outputs some informationals about this second connection
977  * when we've issued a PASV command before and thus we have connected to a
978  * possibly new IP address.
979  *
980  */
981 static void
982 ftp_pasv_verbose(struct connectdata *conn,
983                  Curl_ipconnect *addr,
984                  char *newhost, /* ascii version */
985                  int port)
986 {
987 #ifndef ENABLE_IPV6
988   /*****************************************************************
989    *
990    * IPv4-only code section
991    */
992
993   struct in_addr in;
994   struct hostent * answer;
995
996 #ifdef HAVE_INET_NTOA_R
997   char ntoa_buf[64];
998 #endif
999   /* The array size trick below is to make this a large chunk of memory
1000      suitably 8-byte aligned on 64-bit platforms. This was thoughtfully
1001      suggested by Philip Gladstone. */
1002   long bigbuf[9000 / sizeof(long)];
1003
1004 #if defined(HAVE_INET_ADDR)
1005   in_addr_t address;
1006 # if defined(HAVE_GETHOSTBYADDR_R)
1007   int h_errnop;
1008 # endif
1009   char *hostent_buf = (char *)bigbuf; /* get a char * to the buffer */
1010
1011   address = inet_addr(newhost);
1012 # ifdef HAVE_GETHOSTBYADDR_R
1013
1014 #  ifdef HAVE_GETHOSTBYADDR_R_5
1015   /* AIX, Digital Unix (OSF1, Tru64) style:
1016      extern int gethostbyaddr_r(char *addr, size_t len, int type,
1017      struct hostent *htent, struct hostent_data *ht_data); */
1018
1019   /* Fred Noz helped me try this out, now it at least compiles! */
1020
1021   /* Bjorn Reese (November 28 2001):
1022      The Tru64 man page on gethostbyaddr_r() says that
1023      the hostent struct must be filled with zeroes before the call to
1024      gethostbyaddr_r(). 
1025
1026      ... as must be struct hostent_data Craig Markwardt 19 Sep 2002. */
1027
1028   memset(hostent_buf, 0, sizeof(struct hostent)+sizeof(struct hostent_data));
1029
1030   if(gethostbyaddr_r((char *) &address,
1031                      sizeof(address), AF_INET,
1032                      (struct hostent *)hostent_buf,
1033                      (struct hostent_data *)(hostent_buf + sizeof(*answer))))
1034     answer=NULL;
1035   else
1036     answer=(struct hostent *)hostent_buf;
1037                            
1038 #  endif
1039 #  ifdef HAVE_GETHOSTBYADDR_R_7
1040   /* Solaris and IRIX */
1041   answer = gethostbyaddr_r((char *) &address, sizeof(address), AF_INET,
1042                            (struct hostent *)bigbuf,
1043                            hostent_buf + sizeof(*answer),
1044                            sizeof(bigbuf) - sizeof(*answer),
1045                            &h_errnop);
1046 #  endif
1047 #  ifdef HAVE_GETHOSTBYADDR_R_8
1048   /* Linux style */
1049   if(gethostbyaddr_r((char *) &address, sizeof(address), AF_INET,
1050                      (struct hostent *)hostent_buf,
1051                      hostent_buf + sizeof(*answer),
1052                      sizeof(bigbuf) - sizeof(*answer),
1053                      &answer,
1054                      &h_errnop))
1055     answer=NULL; /* error */
1056 #  endif
1057         
1058 # else
1059   (void)hostent_buf; /* avoid compiler warning */
1060   answer = gethostbyaddr((char *) &address, sizeof(address), AF_INET);
1061 # endif
1062 #else
1063   answer = NULL;
1064 #endif
1065   (void) memcpy(&in.s_addr, addr, sizeof (Curl_ipconnect));
1066   infof(conn->data, "Connecting to %s (%s) port %u\n",
1067         answer?answer->h_name:newhost,
1068 #if defined(HAVE_INET_NTOA_R)
1069         inet_ntoa_r(in, ntoa_buf, sizeof(ntoa_buf)),
1070 #else
1071         inet_ntoa(in),
1072 #endif
1073         port);
1074
1075 #else
1076   /*****************************************************************
1077    *
1078    * IPv6-only code section
1079    */
1080   char hbuf[NI_MAXHOST]; /* ~1KB */
1081   char nbuf[NI_MAXHOST]; /* ~1KB */
1082   char sbuf[NI_MAXSERV]; /* around 32 */
1083   (void)port; /* prevent compiler warning */
1084   if (getnameinfo(addr->ai_addr, addr->ai_addrlen,
1085                   nbuf, sizeof(nbuf), sbuf, sizeof(sbuf), NIFLAGS)) {
1086     snprintf(nbuf, sizeof(nbuf), "?");
1087     snprintf(sbuf, sizeof(sbuf), "?");
1088   }
1089         
1090   if (getnameinfo(addr->ai_addr, addr->ai_addrlen,
1091                   hbuf, sizeof(hbuf), NULL, 0, 0)) {
1092     infof(conn->data, "Connecting to %s (%s) port %s\n", nbuf, newhost, sbuf);
1093   }
1094   else {
1095     infof(conn->data, "Connecting to %s (%s) port %s\n", hbuf, nbuf, sbuf);
1096   }
1097 #endif
1098 }
1099
1100 /***********************************************************************
1101  *
1102  * ftp_use_port()
1103  *
1104  * Send the proper PORT command. PORT is the ftp client's way of telling the
1105  * server that *WE* open a port that we listen on an awaits the server to
1106  * connect to. This is the opposite of PASV.
1107  */
1108
1109 static
1110 CURLcode ftp_use_port(struct connectdata *conn)
1111 {
1112   struct SessionHandle *data=conn->data;
1113   curl_socket_t portsock= CURL_SOCKET_BAD;
1114   ssize_t nread;
1115   int ftpcode; /* receive FTP response codes in this */
1116   CURLcode result;
1117
1118 #ifdef ENABLE_IPV6
1119   /******************************************************************
1120    *
1121    * Here's a piece of IPv6-specific code coming up
1122    *
1123    */
1124
1125   struct addrinfo hints, *res, *ai;
1126   struct sockaddr_storage ss;
1127   socklen_t sslen;
1128   char hbuf[NI_MAXHOST];
1129
1130   struct sockaddr *sa=(struct sockaddr *)&ss;
1131   unsigned char *ap;
1132   unsigned char *pp;
1133   char portmsgbuf[4096], tmp[4096];
1134
1135   const char *mode[] = { "EPRT", "LPRT", "PORT", NULL };
1136   char **modep;
1137   int rc;
1138   int error;
1139
1140   /*
1141    * we should use Curl_if2ip?  given pickiness of recent ftpd,
1142    * I believe we should use the same address as the control connection.
1143    */
1144   sslen = sizeof(ss);
1145   rc = getsockname(conn->sock[FIRSTSOCKET], (struct sockaddr *)&ss, &sslen);
1146   if(rc < 0) {
1147     failf(data, "getsockname() returned %d\n", rc);
1148     return CURLE_FTP_PORT_FAILED;
1149   }
1150   
1151   rc = getnameinfo((struct sockaddr *)&ss, sslen, hbuf, sizeof(hbuf), NULL, 0,
1152                    NIFLAGS);
1153   if(rc) {
1154     failf(data, "getnameinfo() returned %d\n", rc);
1155     return CURLE_FTP_PORT_FAILED;
1156   }
1157
1158   memset(&hints, 0, sizeof(hints));
1159   hints.ai_family = sa->sa_family;
1160   /*hints.ai_family = ss.ss_family;
1161     this way can be used if sockaddr_storage is properly defined, as glibc 
1162     2.1.X doesn't do*/
1163   hints.ai_socktype = SOCK_STREAM;
1164   hints.ai_flags = AI_PASSIVE;
1165
1166   rc = getaddrinfo(hbuf, NULL, &hints, &res);
1167   if(rc) {
1168     failf(data, "getaddrinfo() returned %d\n", rc);
1169     return CURLE_FTP_PORT_FAILED;
1170   }
1171   
1172   portsock = CURL_SOCKET_BAD;
1173   error = 0;
1174   for (ai = res; ai; ai = ai->ai_next) {
1175     /*
1176      * Workaround for AIX5 getaddrinfo() problem (it doesn't set ai_socktype):
1177      */
1178     if (ai->ai_socktype == 0)
1179       ai->ai_socktype = hints.ai_socktype;
1180
1181     portsock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
1182     if (portsock == CURL_SOCKET_BAD) {
1183       error = Curl_ourerrno();
1184       continue;
1185     }
1186
1187     if (bind(portsock, ai->ai_addr, ai->ai_addrlen) < 0) {
1188       error = Curl_ourerrno();
1189       sclose(portsock);
1190       portsock = CURL_SOCKET_BAD;
1191       continue;
1192     }
1193       
1194     if (listen(portsock, 1) < 0) {
1195       error = Curl_ourerrno();
1196       sclose(portsock);
1197       portsock = CURL_SOCKET_BAD;
1198       continue;
1199     }
1200     
1201     break;
1202   }
1203   freeaddrinfo(res);
1204   if (portsock == CURL_SOCKET_BAD) {
1205     failf(data, "%s", Curl_strerror(conn,error));
1206     return CURLE_FTP_PORT_FAILED;
1207   }
1208
1209   sslen = sizeof(ss);
1210   if (getsockname(portsock, sa, &sslen) < 0) {
1211     failf(data, "%s", Curl_strerror(conn,Curl_ourerrno()));
1212     return CURLE_FTP_PORT_FAILED;
1213   }
1214
1215   for (modep = (char **)(data->set.ftp_use_eprt?&mode[0]:&mode[2]);
1216        modep && *modep; modep++) {
1217     int lprtaf, eprtaf;
1218     int alen=0, plen=0;
1219     
1220     switch (sa->sa_family) {
1221     case AF_INET:
1222       ap = (unsigned char *)&((struct sockaddr_in *)&ss)->sin_addr;
1223       alen = sizeof(((struct sockaddr_in *)&ss)->sin_addr);
1224       pp = (unsigned char *)&((struct sockaddr_in *)&ss)->sin_port;
1225       plen = sizeof(((struct sockaddr_in *)&ss)->sin_port);
1226       lprtaf = 4;
1227       eprtaf = 1;
1228       break;
1229     case AF_INET6:
1230       ap = (unsigned char *)&((struct sockaddr_in6 *)&ss)->sin6_addr;
1231       alen = sizeof(((struct sockaddr_in6 *)&ss)->sin6_addr);
1232       pp = (unsigned char *)&((struct sockaddr_in6 *)&ss)->sin6_port;
1233       plen = sizeof(((struct sockaddr_in6 *)&ss)->sin6_port);
1234       lprtaf = 6;
1235       eprtaf = 2;
1236       break;
1237     default:
1238       ap = pp = NULL;
1239       lprtaf = eprtaf = -1;
1240       break;
1241     }
1242
1243     if (strcmp(*modep, "EPRT") == 0) {
1244       if (eprtaf < 0)
1245         continue;
1246       if (getnameinfo((struct sockaddr *)&ss, sslen,
1247                       portmsgbuf, sizeof(portmsgbuf), tmp, sizeof(tmp),
1248                       NIFLAGS))
1249         continue;
1250
1251       /* do not transmit IPv6 scope identifier to the wire */
1252       if (sa->sa_family == AF_INET6) {
1253         char *q = strchr(portmsgbuf, '%');
1254         if (q)
1255           *q = '\0';
1256       }
1257
1258       result = Curl_ftpsendf(conn, "%s |%d|%s|%s|", *modep, eprtaf,
1259                              portmsgbuf, tmp);
1260       if(result)
1261         return result;
1262     }
1263     else if (strcmp(*modep, "LPRT") == 0 ||
1264              strcmp(*modep, "PORT") == 0) {
1265       int i;
1266
1267       if (strcmp(*modep, "LPRT") == 0 && lprtaf < 0)
1268         continue;
1269       if (strcmp(*modep, "PORT") == 0 && sa->sa_family != AF_INET)
1270         continue;
1271
1272       portmsgbuf[0] = '\0';
1273       if (strcmp(*modep, "LPRT") == 0) {
1274         snprintf(tmp, sizeof(tmp), "%d,%d", lprtaf, alen);
1275         if (strlcat(portmsgbuf, tmp, sizeof(portmsgbuf)) >=
1276             sizeof(portmsgbuf)) {
1277           continue;
1278         }
1279       }
1280
1281       for (i = 0; i < alen; i++) {
1282         if (portmsgbuf[0])
1283           snprintf(tmp, sizeof(tmp), ",%u", ap[i]);
1284         else
1285           snprintf(tmp, sizeof(tmp), "%u", ap[i]);
1286         
1287         if (strlcat(portmsgbuf, tmp, sizeof(portmsgbuf)) >=
1288             sizeof(portmsgbuf)) {
1289           continue;
1290         }
1291       }
1292       
1293       if (strcmp(*modep, "LPRT") == 0) {
1294         snprintf(tmp, sizeof(tmp), ",%d", plen);
1295         
1296         if (strlcat(portmsgbuf, tmp, sizeof(portmsgbuf)) >= sizeof(portmsgbuf))
1297           continue;
1298       }
1299
1300       for (i = 0; i < plen; i++) {
1301         snprintf(tmp, sizeof(tmp), ",%u", pp[i]);
1302         
1303         if (strlcat(portmsgbuf, tmp, sizeof(portmsgbuf)) >=
1304             sizeof(portmsgbuf)) {
1305           continue;
1306         }
1307       }
1308       
1309       result = Curl_ftpsendf(conn, "%s %s", *modep, portmsgbuf);
1310       if(result)
1311         return result;
1312     }
1313     
1314     result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
1315     if(result)
1316       return result;
1317     
1318     if (ftpcode != 200) {
1319       continue;
1320     }
1321     else
1322       break;
1323   }
1324   
1325   if (!*modep) {
1326     sclose(portsock);
1327     failf(data, "PORT command attempts failed");
1328     return CURLE_FTP_PORT_FAILED;
1329   }
1330   /* we set the secondary socket variable to this for now, it
1331      is only so that the cleanup function will close it in case
1332      we fail before the true secondary stuff is made */
1333   conn->sock[SECONDARYSOCKET] = portsock;
1334   
1335 #else
1336   /******************************************************************
1337    *
1338    * Here's a piece of IPv4-specific code coming up
1339    *
1340    */
1341   struct sockaddr_in sa;
1342   struct Curl_dns_entry *h=NULL;
1343   unsigned short porttouse;
1344   char myhost[256] = "";
1345   bool sa_filled_in = FALSE;
1346
1347   if(data->set.ftpport) {
1348     in_addr_t in;
1349     int rc;
1350
1351     /* First check if the given name is an IP address */
1352     in=inet_addr(data->set.ftpport);
1353
1354     if((in == CURL_INADDR_NONE) &&
1355        Curl_if2ip(data->set.ftpport, myhost, sizeof(myhost))) {
1356       rc = Curl_resolv(conn, myhost, 0, &h);
1357       if(rc == 1)
1358         rc = Curl_wait_for_resolv(conn, &h);
1359     }
1360     else {
1361       size_t len = strlen(data->set.ftpport);
1362       if(len>1) {
1363         rc = Curl_resolv(conn, data->set.ftpport, 0, &h);
1364         if(rc == 1)
1365           rc = Curl_wait_for_resolv(conn, &h);
1366       }
1367       if(h)
1368         strcpy(myhost, data->set.ftpport); /* buffer overflow risk */
1369     }
1370   }
1371   if(! *myhost) {
1372     /* pick a suitable default here */
1373
1374     socklen_t sslen;
1375     
1376     sslen = sizeof(sa);
1377     if (getsockname(conn->sock[FIRSTSOCKET],
1378                     (struct sockaddr *)&sa, &sslen) < 0) {
1379       failf(data, "getsockname() failed");
1380       return CURLE_FTP_PORT_FAILED;
1381     }
1382
1383     sa_filled_in = TRUE; /* the sa struct is filled in */
1384   }
1385
1386   if(h)
1387     /* when we return from here, we can forget about this */
1388     Curl_resolv_unlock(data, h);
1389
1390   if ( h || sa_filled_in) {
1391     if( (portsock = socket(AF_INET, SOCK_STREAM, 0)) != CURL_SOCKET_BAD ) {
1392       int size;
1393       
1394       /* we set the secondary socket variable to this for now, it
1395          is only so that the cleanup function will close it in case
1396          we fail before the true secondary stuff is made */
1397       conn->sock[SECONDARYSOCKET] = portsock;
1398
1399       if(!sa_filled_in) {
1400         memset((char *)&sa, 0, sizeof(sa));
1401         memcpy((char *)&sa.sin_addr,
1402                h->addr->h_addr,
1403                h->addr->h_length);
1404         sa.sin_family = AF_INET;
1405         sa.sin_addr.s_addr = INADDR_ANY;
1406       }
1407
1408       sa.sin_port = 0;
1409       size = sizeof(sa);
1410       
1411       if(bind(portsock, (struct sockaddr *)&sa, size) >= 0) {
1412         /* we succeeded to bind */
1413         struct sockaddr_in add;
1414         socklen_t socksize = sizeof(add);
1415
1416         if(getsockname(portsock, (struct sockaddr *) &add,
1417                        &socksize)<0) {
1418           failf(data, "getsockname() failed");
1419           return CURLE_FTP_PORT_FAILED;
1420         }
1421         porttouse = ntohs(add.sin_port);
1422         
1423         if ( listen(portsock, 1) < 0 ) {
1424           failf(data, "listen(2) failed on socket");
1425           return CURLE_FTP_PORT_FAILED;
1426         }
1427       }
1428       else {
1429         failf(data, "bind(2) failed on socket");
1430         return CURLE_FTP_PORT_FAILED;
1431       }
1432     }
1433     else {
1434       failf(data, "socket(2) failed (%s)");
1435       return CURLE_FTP_PORT_FAILED;
1436     }
1437   }
1438   else {
1439     failf(data, "could't find my own IP address (%s)", myhost);
1440     return CURLE_FTP_PORT_FAILED;
1441   }
1442   {
1443 #ifdef HAVE_INET_NTOA_R
1444     char ntoa_buf[64];
1445 #endif
1446     struct in_addr in;
1447     unsigned short ip[5];
1448     (void) memcpy(&in.s_addr,
1449                   h?*h->addr->h_addr_list:(char *)&sa.sin_addr.s_addr,
1450                   sizeof (in.s_addr));
1451
1452 #ifdef HAVE_INET_NTOA_R
1453     /* ignore the return code from inet_ntoa_r() as it is int or
1454        char * depending on system */
1455     inet_ntoa_r(in, ntoa_buf, sizeof(ntoa_buf));
1456     sscanf( ntoa_buf, "%hu.%hu.%hu.%hu",
1457             &ip[0], &ip[1], &ip[2], &ip[3]);
1458 #else
1459     sscanf( inet_ntoa(in), "%hu.%hu.%hu.%hu",
1460             &ip[0], &ip[1], &ip[2], &ip[3]);
1461 #endif
1462     infof(data, "Telling server to connect to %d.%d.%d.%d:%d\n",
1463           ip[0], ip[1], ip[2], ip[3], porttouse);
1464   
1465     result=Curl_ftpsendf(conn, "PORT %d,%d,%d,%d,%d,%d",
1466                          ip[0], ip[1], ip[2], ip[3],
1467                          porttouse >> 8,
1468                          porttouse & 255);
1469     if(result)
1470       return result;
1471   }
1472
1473   result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
1474   if(result)
1475     return result;
1476
1477   if(ftpcode != 200) {
1478     failf(data, "Server does not grok PORT, try without it!");
1479     return CURLE_FTP_PORT_FAILED;
1480   }
1481 #endif /* end of ipv4-specific code */
1482
1483   return CURLE_OK;
1484 }
1485
1486 /***********************************************************************
1487  *
1488  * ftp_use_pasv()
1489  *
1490  * Send the PASV command. PASV is the ftp client's way of asking the server to
1491  * open a second port that we can connect to (for the data transfer). This is
1492  * the opposite of PORT.
1493  */
1494
1495 static
1496 CURLcode ftp_use_pasv(struct connectdata *conn,
1497                       bool *connected)
1498 {
1499   struct SessionHandle *data = conn->data;
1500   ssize_t nread;
1501   char *buf = data->state.buffer; /* this is our buffer */
1502   int ftpcode; /* receive FTP response codes in this */
1503   CURLcode result;
1504   struct Curl_dns_entry *addr=NULL;
1505   Curl_ipconnect *conninfo;
1506   int rc;
1507
1508   /*
1509     Here's the excecutive summary on what to do:
1510
1511     PASV is RFC959, expect:
1512     227 Entering Passive Mode (a1,a2,a3,a4,p1,p2)
1513
1514     LPSV is RFC1639, expect:
1515     228 Entering Long Passive Mode (4,4,a1,a2,a3,a4,2,p1,p2)
1516
1517     EPSV is RFC2428, expect:
1518     229 Entering Extended Passive Mode (|||port|)
1519
1520   */
1521
1522   const char *mode[] = { "EPSV", "PASV", NULL };
1523   int results[] = { 229, 227, 0 };
1524   int modeoff;
1525   unsigned short connectport; /* the local port connect() should use! */
1526   unsigned short newport=0; /* remote port, not necessary the local one */
1527   
1528   /* newhost must be able to hold a full IP-style address in ASCII, which
1529      in the IPv6 case means 5*8-1 = 39 letters */
1530   char newhost[48];
1531   char *newhostp=NULL;
1532   
1533   for (modeoff = (data->set.ftp_use_epsv?0:1);
1534        mode[modeoff]; modeoff++) {
1535     result = Curl_ftpsendf(conn, "%s", mode[modeoff]);
1536     if(result)
1537       return result;
1538     result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
1539     if(result)
1540       return result;
1541     if (ftpcode == results[modeoff])
1542       break;
1543   }
1544
1545   if (!mode[modeoff]) {
1546     failf(data, "Odd return code after PASV");
1547     return CURLE_FTP_WEIRD_PASV_REPLY;
1548   }
1549   else if (227 == results[modeoff]) {
1550     int ip[4];
1551     int port[2];
1552     char *str=buf;
1553
1554     /*
1555      * New 227-parser June 3rd 1999.
1556      * It now scans for a sequence of six comma-separated numbers and
1557      * will take them as IP+port indicators.
1558      *
1559      * Found reply-strings include:
1560      * "227 Entering Passive Mode (127,0,0,1,4,51)"
1561      * "227 Data transfer will passively listen to 127,0,0,1,4,51"
1562      * "227 Entering passive mode. 127,0,0,1,4,51"
1563      */
1564       
1565     while(*str) {
1566       if (6 == sscanf(str, "%d,%d,%d,%d,%d,%d",
1567                       &ip[0], &ip[1], &ip[2], &ip[3],
1568                       &port[0], &port[1]))
1569         break;
1570       str++;
1571     }
1572
1573     if(!*str) {
1574       failf(data, "Couldn't interpret this 227-reply: %s", buf);
1575       return CURLE_FTP_WEIRD_227_FORMAT;
1576     }
1577
1578     sprintf(newhost, "%d.%d.%d.%d", ip[0], ip[1], ip[2], ip[3]);
1579     newhostp = newhost;
1580     newport = (port[0]<<8) + port[1];
1581   }
1582   else if (229 == results[modeoff]) {
1583     char *ptr = strchr(buf, '(');
1584     if(ptr) {
1585       unsigned int num;
1586       char separator[4];
1587       ptr++;
1588       if(5  == sscanf(ptr, "%c%c%c%u%c",
1589                       &separator[0],
1590                       &separator[1],
1591                       &separator[2],
1592                       &num,
1593                       &separator[3])) {
1594         char sep1 = separator[0];
1595         int i;
1596
1597         /* The four separators should be identical, or else this is an oddly
1598            formatted reply and we bail out immediately. */
1599         for(i=1; i<4; i++) {
1600           if(separator[i] != sep1) {
1601             ptr=NULL; /* set to NULL to signal error */
1602             break;
1603           }
1604         }
1605         if(ptr) {
1606           newport = num;
1607
1608           /* we should use the same host we already are connected to */
1609           newhostp = conn->name;
1610         }
1611       }                      
1612       else
1613         ptr=NULL;
1614     }
1615     if(!ptr) {
1616       failf(data, "Weirdly formatted EPSV reply");
1617       return CURLE_FTP_WEIRD_PASV_REPLY;
1618     }
1619   }
1620   else
1621     return CURLE_FTP_CANT_RECONNECT;
1622
1623   if(data->change.proxy && *data->change.proxy) {
1624     /*
1625      * This is a tunnel through a http proxy and we need to connect to the
1626      * proxy again here.
1627      *
1628      * We don't want to rely on a former host lookup that might've expired
1629      * now, instead we remake the lookup here and now!
1630      */
1631     rc = Curl_resolv(conn, conn->proxyhost, conn->port, &addr);
1632     if(rc == 1)
1633       rc = Curl_wait_for_resolv(conn, &addr);
1634
1635     connectport =
1636       (unsigned short)conn->port; /* we connect to the proxy's port */    
1637
1638   }
1639   else {
1640     /* normal, direct, ftp connection */
1641     rc = Curl_resolv(conn, newhostp, newport, &addr);
1642     if(rc == 1)
1643       rc = Curl_wait_for_resolv(conn, &addr);
1644
1645     if(!addr) {
1646       failf(data, "Can't resolve new host %s:%d", newhostp, newport);
1647       return CURLE_FTP_CANT_GET_HOST;
1648     }
1649     connectport = newport; /* we connect to the remote port */
1650   }
1651     
1652   result = Curl_connecthost(conn,
1653                             addr,
1654                             connectport,
1655                             &conn->sock[SECONDARYSOCKET],
1656                             &conninfo,
1657                             connected);
1658
1659   Curl_resolv_unlock(data, addr); /* we're done using this address */
1660
1661   if(result)
1662     return result;
1663
1664   /*
1665    * When this is used from the multi interface, this might've returned with
1666    * the 'connected' set to FALSE and thus we are now awaiting a non-blocking
1667    * connect to connect and we should not be "hanging" here waiting.
1668    */
1669   
1670   if(data->set.verbose)
1671     /* this just dumps information about this second connection */
1672     ftp_pasv_verbose(conn, conninfo, newhostp, connectport);
1673   
1674   if(data->set.tunnel_thru_httpproxy) {
1675     /* We want "seamless" FTP operations through HTTP proxy tunnel */
1676     result = Curl_ConnectHTTPProxyTunnel(conn, SECONDARYSOCKET,
1677                                          newhostp, newport);
1678     if(CURLE_OK != result)
1679       return result;
1680   }
1681
1682   return CURLE_OK;
1683 }
1684
1685 /*
1686  * Curl_ftp_nextconnect()
1687  *
1688  * This function shall be called when the second FTP connection has been
1689  * established and is confirmed connected.
1690  */
1691
1692 CURLcode Curl_ftp_nextconnect(struct connectdata *conn)
1693 {
1694   struct SessionHandle *data=conn->data;
1695   char *buf = data->state.buffer; /* this is our buffer */
1696   CURLcode result;
1697   ssize_t nread;
1698   int ftpcode; /* for ftp status */
1699
1700   /* the ftp struct is already inited in Curl_ftp_connect() */
1701   struct FTP *ftp = conn->proto.ftp;
1702   curl_off_t *bytecountp = ftp->bytecountp;
1703
1704   if(data->set.upload) {
1705
1706     /* Set type to binary (unless specified ASCII) */
1707     result = ftp_transfertype(conn, data->set.ftp_ascii);
1708     if(result)
1709       return result;
1710
1711     /* Send any PREQUOTE strings after transfer type is set? (Wesley Laxton)*/
1712     if(data->set.prequote) {
1713       if ((result = ftp_sendquote(conn, data->set.prequote)) != CURLE_OK)
1714         return result;
1715     }
1716
1717     if(conn->resume_from) {
1718       /* we're about to continue the uploading of a file */
1719       /* 1. get already existing file's size. We use the SIZE
1720          command for this which may not exist in the server!
1721          The SIZE command is not in RFC959. */
1722
1723       /* 2. This used to set REST. But since we can do append, we
1724          don't another ftp command. We just skip the source file
1725          offset and then we APPEND the rest on the file instead */
1726
1727       /* 3. pass file-size number of bytes in the source file */
1728       /* 4. lower the infilesize counter */
1729       /* => transfer as usual */
1730
1731       if(conn->resume_from < 0 ) {
1732         /* we could've got a specified offset from the command line,
1733            but now we know we didn't */
1734         curl_off_t gottensize;
1735
1736         if(CURLE_OK != ftp_getsize(conn, ftp->file, &gottensize)) {
1737           failf(data, "Couldn't get remote file size");
1738           return CURLE_FTP_COULDNT_GET_SIZE;
1739         }
1740         conn->resume_from = gottensize;
1741       }
1742
1743       if(conn->resume_from) {
1744         /* do we still game? */
1745         curl_off_t passed=0;
1746         /* enable append instead */
1747         data->set.ftp_append = 1;
1748
1749         /* Now, let's read off the proper amount of bytes from the
1750            input. If we knew it was a proper file we could've just
1751            fseek()ed but we only have a stream here */
1752         do {
1753           curl_off_t readthisamountnow = (conn->resume_from - passed);
1754           curl_off_t actuallyread;
1755
1756           if(readthisamountnow > BUFSIZE)
1757             readthisamountnow = BUFSIZE;
1758
1759           actuallyread =
1760             conn->fread(data->state.buffer, 1, (size_t)readthisamountnow,
1761                         conn->fread_in);
1762
1763           passed += actuallyread;
1764           if(actuallyread != readthisamountnow) {
1765             failf(data, "Could only read %" FORMAT_OFF_T
1766                   " bytes from the input", passed);
1767             return CURLE_FTP_COULDNT_USE_REST;
1768           }
1769         }
1770         while(passed != conn->resume_from);
1771
1772         /* now, decrease the size of the read */
1773         if(data->set.infilesize>0) {
1774           data->set.infilesize -= conn->resume_from;
1775
1776           if(data->set.infilesize <= 0) {
1777             infof(data, "File already completely uploaded\n");
1778
1779             /* no data to transfer */
1780             result=Curl_Transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1781             
1782             /* Set no_transfer so that we won't get any error in
1783              * Curl_ftp_done() because we didn't transfer anything! */
1784             ftp->no_transfer = TRUE; 
1785
1786             return CURLE_OK;
1787           }
1788         }
1789         /* we've passed, proceed as normal */
1790       }
1791     }
1792
1793     /* Send everything on data->state.in to the socket */
1794     if(data->set.ftp_append) {
1795       /* we append onto the file instead of rewriting it */
1796       FTPSENDF(conn, "APPE %s", ftp->file);
1797     }
1798     else {
1799       FTPSENDF(conn, "STOR %s", ftp->file);
1800     }
1801
1802     result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
1803     if(result)
1804       return result;
1805
1806     if(ftpcode>=400) {
1807       failf(data, "Failed FTP upload:%s", buf+3);
1808       /* oops, we never close the sockets! */
1809       return CURLE_FTP_COULDNT_STOR_FILE;
1810     }
1811
1812     if(data->set.ftp_use_port) {
1813       /* PORT means we are now awaiting the server to connect to us. */
1814       result = AllowServerConnect(conn);
1815       if( result )
1816         return result;
1817     }
1818
1819     if(conn->ssl[SECONDARYSOCKET].use) {
1820       /* since we only have a plaintext TCP connection here, we must now
1821          do the TLS stuff */
1822       infof(data, "Doing the SSL/TLS handshake on the data stream\n");
1823       result = Curl_SSLConnect(conn, SECONDARYSOCKET);
1824       if(result)
1825         return result;
1826     }
1827
1828     *bytecountp=0;
1829
1830     /* When we know we're uploading a specified file, we can get the file
1831        size prior to the actual upload. */
1832
1833     Curl_pgrsSetUploadSize(data, data->set.infilesize);
1834
1835     result = Curl_Transfer(conn, -1, -1, FALSE, NULL, /* no download */
1836                            SECONDARYSOCKET, bytecountp);
1837     if(result)
1838       return result;
1839       
1840   }
1841   else if(!data->set.no_body) {
1842     /* Retrieve file or directory */
1843     bool dirlist=FALSE;
1844     curl_off_t downloadsize=-1;
1845
1846     if(conn->bits.use_range && conn->range) {
1847       curl_off_t from, to;
1848       curl_off_t totalsize=-1;
1849       char *ptr;
1850       char *ptr2;
1851
1852       from=strtoofft(conn->range, &ptr, 0);
1853       while(ptr && *ptr && (isspace((int)*ptr) || (*ptr=='-')))
1854         ptr++;
1855       to=strtoofft(ptr, &ptr2, 0);
1856       if(ptr == ptr2) {
1857         /* we didn't get any digit */
1858         to=-1;
1859       }
1860       if((-1 == to) && (from>=0)) {
1861         /* X - */
1862         conn->resume_from = from;
1863         infof(data, "FTP RANGE %" FORMAT_OFF_T " to end of file\n", from);
1864       }
1865       else if(from < 0) {
1866         /* -Y */
1867         totalsize = -from;
1868         conn->maxdownload = -from;
1869         conn->resume_from = from;
1870         infof(data, "FTP RANGE the last %" FORMAT_OFF_T " bytes\n", totalsize);
1871       }
1872       else {
1873         /* X-Y */
1874         totalsize = to-from;
1875         conn->maxdownload = totalsize+1; /* include the last mentioned byte */
1876         conn->resume_from = from;
1877         infof(data, "FTP RANGE from %" FORMAT_OFF_T
1878               " getting %" FORMAT_OFF_T " bytes\n", from, conn->maxdownload);
1879       }
1880       infof(data, "range-download from %" FORMAT_OFF_T
1881             " to %" FORMAT_OFF_T ", totally %" FORMAT_OFF_T " bytes\n",
1882             from, to, conn->maxdownload);
1883       ftp->dont_check = TRUE; /* dont check for successful transfer */
1884     }
1885
1886     if((data->set.ftp_list_only) || !ftp->file) {
1887       /* The specified path ends with a slash, and therefore we think this
1888          is a directory that is requested, use LIST. But before that we
1889          need to set ASCII transfer mode. */
1890       dirlist = TRUE;
1891
1892       /* Set type to ASCII */
1893       result = ftp_transfertype(conn, TRUE /* ASCII enforced */);
1894       if(result)
1895         return result;
1896
1897       /* if this output is to be machine-parsed, the NLST command will be
1898          better used since the LIST command output is not specified or
1899          standard in any way */
1900
1901       FTPSENDF(conn, "%s",
1902             data->set.customrequest?data->set.customrequest:
1903             (data->set.ftp_list_only?"NLST":"LIST"));
1904     }
1905     else {
1906       curl_off_t foundsize;
1907
1908       /* Set type to binary (unless specified ASCII) */
1909       result = ftp_transfertype(conn, data->set.ftp_ascii);
1910       if(result)
1911         return result;
1912
1913       /* Send any PREQUOTE strings after transfer type is set? */
1914       if(data->set.prequote) {
1915         if ((result = ftp_sendquote(conn, data->set.prequote)) != CURLE_OK)
1916           return result;
1917       }
1918
1919       /* Attempt to get the size, it'll be useful in some cases: for resumed
1920          downloads and when talking to servers that don't give away the size
1921          in the RETR response line. */
1922       result = ftp_getsize(conn, ftp->file, &foundsize);
1923       if(CURLE_OK == result) {
1924         if (data->set.max_filesize && foundsize > data->set.max_filesize) {
1925           failf(data, "Maximum file size exceeded");
1926           return CURLE_FILESIZE_EXCEEDED;
1927         }
1928         downloadsize = foundsize;
1929       }
1930
1931       if(conn->resume_from) {
1932
1933         /* Daniel: (August 4, 1999)
1934          *
1935          * We start with trying to use the SIZE command to figure out the size
1936          * of the file we're gonna get. If we can get the size, this is by far
1937          * the best way to know if we're trying to resume beyond the EOF.
1938          *
1939          * Daniel, November 28, 2001. We *always* get the size on downloads
1940          * now, so it is done before this even when not doing resumes. I saved
1941          * the comment above for nostalgical reasons! ;-)
1942          */
1943         if(CURLE_OK != result) {
1944           infof(data, "ftp server doesn't support SIZE\n");
1945           /* We couldn't get the size and therefore we can't know if there
1946              really is a part of the file left to get, although the server
1947              will just close the connection when we start the connection so it
1948              won't cause us any harm, just not make us exit as nicely. */
1949         }
1950         else {
1951           /* We got a file size report, so we check that there actually is a
1952              part of the file left to get, or else we go home.  */
1953           if(conn->resume_from< 0) {
1954             /* We're supposed to download the last abs(from) bytes */
1955             if(foundsize < -conn->resume_from) {
1956               failf(data, "Offset (%" FORMAT_OFF_T
1957                     ") was beyond file size (%" FORMAT_OFF_T ")",
1958                     conn->resume_from, foundsize);
1959               return CURLE_FTP_BAD_DOWNLOAD_RESUME;
1960             }
1961             /* convert to size to download */
1962             downloadsize = -conn->resume_from;
1963             /* download from where? */
1964             conn->resume_from = foundsize - downloadsize;
1965           }
1966           else {
1967             if(foundsize < conn->resume_from) {
1968               failf(data, "Offset (%" FORMAT_OFF_T
1969                     ") was beyond file size (%" FORMAT_OFF_T ")",
1970                     conn->resume_from, foundsize);
1971               return CURLE_FTP_BAD_DOWNLOAD_RESUME;
1972             }
1973             /* Now store the number of bytes we are expected to download */
1974             downloadsize = foundsize-conn->resume_from;
1975           }
1976         }
1977
1978         if (downloadsize == 0) {
1979           /* no data to transfer */
1980           result=Curl_Transfer(conn, -1, -1, FALSE, NULL, -1, NULL);
1981           infof(data, "File already completely downloaded\n");
1982
1983           /* Set no_transfer so that we won't get any error in Curl_ftp_done()
1984            * because we didn't transfer the any file */
1985           ftp->no_transfer = TRUE;
1986           return CURLE_OK;
1987         }
1988         
1989         /* Set resume file transfer offset */
1990         infof(data, "Instructs server to resume from offset %" FORMAT_OFF_T
1991               "\n",
1992               conn->resume_from);
1993
1994         FTPSENDF(conn, "REST %" FORMAT_OFF_T, conn->resume_from);
1995
1996         result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
1997         if(result)
1998           return result;
1999
2000         if(ftpcode != 350) {
2001           failf(data, "Couldn't use REST: %s", buf+4);
2002           return CURLE_FTP_COULDNT_USE_REST;
2003         }
2004       }
2005
2006       FTPSENDF(conn, "RETR %s", ftp->file);
2007     }
2008
2009     result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
2010     if(result)
2011       return result;
2012
2013     if((ftpcode == 150) || (ftpcode == 125)) {
2014
2015       /*
2016         A;
2017         150 Opening BINARY mode data connection for /etc/passwd (2241
2018         bytes).  (ok, the file is being transfered)
2019         
2020         B:
2021         150 Opening ASCII mode data connection for /bin/ls 
2022
2023         C:
2024         150 ASCII data connection for /bin/ls (137.167.104.91,37445) (0 bytes).
2025
2026         D:
2027         150 Opening ASCII mode data connection for /linux/fisk/kpanelrc (0.0.0.0,0) (545 bytes).
2028           
2029         E:
2030         125 Data connection already open; Transfer starting. */
2031
2032       curl_off_t size=-1; /* default unknown size */
2033
2034
2035       /*
2036        * It appears that there are FTP-servers that return size 0 for files
2037        * when SIZE is used on the file while being in BINARY mode. To work
2038        * around that (stupid) behavior, we attempt to parse the RETR response
2039        * even if the SIZE returned size zero.
2040        *
2041        * Debugging help from Salvatore Sorrentino on February 26, 2003.
2042        */
2043
2044       if(!dirlist &&
2045          !data->set.ftp_ascii &&
2046          (downloadsize < 1)) {
2047         /*
2048          * It seems directory listings either don't show the size or very
2049          * often uses size 0 anyway. ASCII transfers may very well turn out
2050          * that the transfered amount of data is not the same as this line
2051          * tells, why using this number in those cases only confuses us.
2052          *
2053          * Example D above makes this parsing a little tricky */
2054         char *bytes;
2055         bytes=strstr(buf, " bytes");
2056         if(bytes--) {
2057           long in=bytes-buf;
2058           /* this is a hint there is size information in there! ;-) */
2059           while(--in) {
2060             /* scan for the parenthesis and break there */
2061             if('(' == *bytes)
2062               break;
2063             /* if only skip digits, or else we're in deep trouble */
2064             if(!isdigit((int)*bytes)) {
2065               bytes=NULL;
2066               break;
2067             }
2068             /* one more estep backwards */
2069             bytes--;
2070           }
2071           /* only if we have nothing but digits: */
2072           if(bytes++) {
2073             /* get the number! */
2074             size = strtoofft(bytes, NULL, 0);
2075           }
2076             
2077         }
2078       }
2079       else if(downloadsize > -1)
2080         size = downloadsize;
2081
2082       if(data->set.ftp_use_port) {
2083         result = AllowServerConnect(conn);
2084         if( result )
2085           return result;
2086       }
2087
2088       if(conn->ssl[SECONDARYSOCKET].use) {
2089         /* since we only have a plaintext TCP connection here, we must now
2090            do the TLS stuff */
2091         infof(data, "Doing the SSL/TLS handshake on the data stream\n");
2092         result = Curl_SSLConnect(conn, SECONDARYSOCKET);
2093         if(result)
2094           return result;
2095       }
2096
2097       if(size > conn->maxdownload && conn->maxdownload > 0)
2098         size = conn->size = conn->maxdownload;
2099
2100       infof(data, "Getting file with size: %" FORMAT_OFF_T "\n", size);
2101
2102       /* FTP download: */
2103       result=Curl_Transfer(conn, SECONDARYSOCKET, size, FALSE,
2104                            bytecountp,
2105                            -1, NULL); /* no upload here */
2106       if(result)
2107         return result;
2108     }
2109     else {
2110       if(dirlist && (ftpcode == 450)) {
2111         /* simply no matching files */
2112         ftp->no_transfer = TRUE; /* don't think we should download anything */
2113       }
2114       else {
2115         failf(data, "%s", buf+4);
2116         return CURLE_FTP_COULDNT_RETR_FILE;
2117       }
2118     }
2119         
2120   }
2121   /* end of transfer */
2122
2123   return CURLE_OK;
2124 }
2125
2126 /***********************************************************************
2127  *
2128  * ftp_perform()
2129  *
2130  * This is the actual DO function for FTP. Get a file/directory according to
2131  * the options previously setup.
2132  */
2133
2134 static
2135 CURLcode ftp_perform(struct connectdata *conn,
2136                      bool *connected)  /* for the TCP connect status after
2137                                           PASV / PORT */
2138 {
2139   /* this is FTP and no proxy */
2140   CURLcode result=CURLE_OK;
2141   struct SessionHandle *data=conn->data;
2142   char *buf = data->state.buffer; /* this is our buffer */
2143
2144   /* the ftp struct is already inited in Curl_ftp_connect() */
2145   struct FTP *ftp = conn->proto.ftp;
2146
2147   /* Send any QUOTE strings? */
2148   if(data->set.quote) {
2149     if ((result = ftp_sendquote(conn, data->set.quote)) != CURLE_OK)
2150       return result;
2151   }
2152
2153   /* This is a re-used connection. Since we change directory to where the
2154      transfer is taking place, we must now get back to the original dir
2155      where we ended up after login: */
2156   if (conn->bits.reuse && ftp->entrypath) {
2157     if ((result = ftp_cwd_and_mkd(conn, ftp->entrypath)) != CURLE_OK)
2158       return result;
2159   }
2160
2161   {
2162     int i; /* counter for loop */
2163     for (i=0; ftp->dirs[i]; i++) {
2164       /* RFC 1738 says empty components should be respected too, but
2165          that is plain stupid since CWD can't be used with an empty argument */
2166       if ((result = ftp_cwd_and_mkd(conn, ftp->dirs[i])) != CURLE_OK)
2167         return result;
2168     }
2169   }
2170
2171   /* Requested time of file or time-depended transfer? */
2172   if((data->set.get_filetime || data->set.timecondition) &&
2173      ftp->file) {
2174     result = ftp_getfiletime(conn, ftp->file);
2175     switch( result )
2176       {
2177       case CURLE_FTP_COULDNT_RETR_FILE:
2178       case CURLE_OK:
2179         if(data->set.timecondition) {
2180           if((data->info.filetime > 0) && (data->set.timevalue > 0)) {
2181             switch(data->set.timecondition) {
2182             case CURL_TIMECOND_IFMODSINCE:
2183             default:
2184               if(data->info.filetime < data->set.timevalue) {
2185                 infof(data, "The requested document is not new enough\n");
2186                 ftp->no_transfer = TRUE; /* mark this to not transfer data */
2187                 return CURLE_OK;
2188               }
2189               break;
2190             case CURL_TIMECOND_IFUNMODSINCE:
2191               if(data->info.filetime > data->set.timevalue) {
2192                 infof(data, "The requested document is not old enough\n");
2193                 ftp->no_transfer = TRUE; /* mark this to not transfer data */
2194                 return CURLE_OK;
2195               }
2196               break;
2197             } /* switch */
2198           }
2199           else {
2200             infof(data, "Skipping time comparison\n");
2201           }
2202         }
2203         break;
2204       default:
2205         return result;
2206       } /* switch */
2207   }
2208
2209   /* If we have selected NOBODY and HEADER, it means that we only want file
2210      information. Which in FTP can't be much more than the file size and
2211      date. */
2212   if(data->set.no_body && data->set.include_header && ftp->file) {
2213     /* The SIZE command is _not_ RFC 959 specified, and therefor many servers
2214        may not support it! It is however the only way we have to get a file's
2215        size! */
2216     curl_off_t filesize;
2217     ssize_t nread;
2218     int ftpcode;
2219
2220     ftp->no_transfer = TRUE; /* this means no actual transfer is made */
2221     
2222     /* Some servers return different sizes for different modes, and thus we
2223        must set the proper type before we check the size */
2224     result = ftp_transfertype(conn, data->set.ftp_ascii);
2225     if(result)
2226       return result;
2227
2228     /* failing to get size is not a serious error */
2229     result = ftp_getsize(conn, ftp->file, &filesize);
2230
2231     if(CURLE_OK == result) {
2232       sprintf(buf, "Content-Length: %" FORMAT_OFF_T "\r\n", filesize);
2233       result = Curl_client_write(data, CLIENTWRITE_BOTH, buf, 0);
2234       if(result)
2235         return result;
2236     }
2237
2238     /* Determine if server can respond to REST command and therefore
2239        whether it can do a range */
2240     FTPSENDF(conn, "REST 0", NULL);
2241     result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
2242
2243     if ((CURLE_OK == result) && (ftpcode == 350)) {
2244       result = Curl_client_write(data, CLIENTWRITE_BOTH,
2245                                  (char *)"Accept-ranges: bytes\r\n", 0);
2246       if(result)
2247         return result;
2248     }
2249
2250     /* If we asked for a time of the file and we actually got one as
2251        well, we "emulate" a HTTP-style header in our output. */
2252
2253 #ifdef HAVE_STRFTIME
2254     if(data->set.get_filetime && (data->info.filetime>=0) ) {
2255       struct tm *tm;
2256       time_t clock = (time_t)data->info.filetime;
2257 #ifdef HAVE_GMTIME_R
2258       struct tm buffer;
2259       tm = (struct tm *)gmtime_r(&clock, &buffer);
2260 #else
2261       tm = gmtime(&clock);
2262 #endif
2263       /* format: "Tue, 15 Nov 1994 12:45:26" */
2264       strftime(buf, BUFSIZE-1, "Last-Modified: %a, %d %b %Y %H:%M:%S GMT\r\n",
2265                tm);
2266       result = Curl_client_write(data, CLIENTWRITE_BOTH, buf, 0);
2267       if(result)
2268         return result;
2269     }
2270 #endif
2271
2272     return CURLE_OK;
2273   }
2274
2275   if(data->set.no_body)
2276     /* doesn't really transfer any data */
2277     ftp->no_transfer = TRUE;
2278   /* Get us a second connection up and connected */
2279   else if(data->set.ftp_use_port) {
2280     /* We have chosen to use the PORT command */
2281     result = ftp_use_port(conn);
2282     if(CURLE_OK == result) {
2283       /* we have the data connection ready */
2284       infof(data, "Ordered connect of the data stream with PORT!\n");
2285       *connected = TRUE; /* mark us "still connected" */
2286     }
2287   }
2288   else {
2289     /* We have chosen (this is default) to use the PASV command */
2290     result = ftp_use_pasv(conn, connected);
2291     if(CURLE_OK == result && *connected)
2292       infof(data, "Connected the data stream with PASV!\n");
2293   }
2294   
2295   return result;
2296 }
2297
2298 /***********************************************************************
2299  *
2300  * Curl_ftp()
2301  *
2302  * This function is registered as 'curl_do' function. It decodes the path
2303  * parts etc as a wrapper to the actual DO function (ftp_perform).
2304  *
2305  * The input argument is already checked for validity.
2306  *
2307  * ftp->ctl_valid starts out as FALSE, and gets set to TRUE if we reach the
2308  * end of the function.
2309  */
2310 CURLcode Curl_ftp(struct connectdata *conn)
2311 {
2312   CURLcode retcode=CURLE_OK;
2313   bool connected=0;
2314   struct SessionHandle *data = conn->data;
2315   struct FTP *ftp;
2316
2317   char *slash_pos;  /* position of the first '/' char in curpos */
2318   char *cur_pos=conn->ppath; /* current position in ppath. point at the begin
2319                                 of next path component */
2320   int path_part=0;/* current path component */
2321
2322   /* the ftp struct is already inited in ftp_connect() */
2323   ftp = conn->proto.ftp;
2324   ftp->ctl_valid = FALSE;
2325   conn->size = -1; /* make sure this is unknown at this point */
2326
2327   Curl_pgrsSetUploadCounter(data, 0);
2328   Curl_pgrsSetDownloadCounter(data, 0);
2329   Curl_pgrsSetUploadSize(data, 0);
2330   Curl_pgrsSetDownloadSize(data, 0);
2331
2332   /*  fixed : initialize ftp->dirs[xxx] to NULL !
2333       is done in Curl_ftp_connect() */
2334
2335   /* parse the URL path into separate path components */
2336   while((slash_pos=strchr(cur_pos, '/'))) {
2337     /* 1 or 0 to indicate absolute directory */
2338     bool absolute_dir = (cur_pos - conn->ppath > 0) && (path_part == 0);
2339
2340     /* seek out the next path component */
2341     if (slash_pos-cur_pos) {
2342       /* we skip empty path components, like "x//y" since the FTP command CWD
2343          requires a parameter and a non-existant parameter a) doesn't work on
2344          many servers and b) has no effect on the others. */
2345       ftp->dirs[path_part] = curl_unescape(cur_pos - absolute_dir,
2346                                            slash_pos - cur_pos + absolute_dir);
2347     
2348       if (!ftp->dirs[path_part]) { /* run out of memory ... */
2349         failf(data, "no memory");
2350         freedirs(ftp);
2351         return CURLE_OUT_OF_MEMORY;
2352       }
2353     }
2354     else {
2355       cur_pos = slash_pos + 1; /* jump to the rest of the string */
2356       continue;
2357     }
2358
2359     if(!retcode) {
2360       cur_pos = slash_pos + 1; /* jump to the rest of the string */
2361       if(++path_part >= (CURL_MAX_FTP_DIRDEPTH-1)) {
2362         /* too deep, we need the last entry to be kept NULL at all
2363            times to signal end of list */
2364         failf(data, "too deep dir hierarchy");
2365         freedirs(ftp);
2366         return CURLE_URL_MALFORMAT;
2367       }
2368     }
2369   }
2370
2371   ftp->file = cur_pos;  /* the rest is the file name */
2372
2373   if(*ftp->file) {
2374     ftp->file = curl_unescape(ftp->file, 0);
2375     if(NULL == ftp->file) {
2376       freedirs(ftp);
2377       failf(data, "no memory");
2378       return CURLE_OUT_OF_MEMORY;
2379     }
2380   }
2381   else
2382     ftp->file=NULL; /* instead of point to a zero byte, we make it a NULL
2383                        pointer */
2384   
2385   retcode = ftp_perform(conn, &connected);
2386
2387   if(CURLE_OK == retcode) {
2388     if(connected)
2389       retcode = Curl_ftp_nextconnect(conn);
2390
2391     if(retcode && (conn->sock[SECONDARYSOCKET] != CURL_SOCKET_BAD)) {
2392       /* Failure detected, close the second socket if it was created already */
2393       sclose(conn->sock[SECONDARYSOCKET]);
2394       conn->sock[SECONDARYSOCKET] = CURL_SOCKET_BAD;
2395     }
2396
2397     if(ftp->no_transfer)
2398       /* no data to transfer */
2399       retcode=Curl_Transfer(conn, -1, -1, FALSE, NULL, -1, NULL);        
2400     else if(!connected)
2401       /* since we didn't connect now, we want do_more to get called */
2402       conn->bits.do_more = TRUE;
2403   }
2404   else
2405     freedirs(ftp);
2406
2407   ftp->ctl_valid = TRUE;
2408   return retcode;
2409 }
2410
2411 /***********************************************************************
2412  *
2413  * Curl_ftpsendf()
2414  *
2415  * Sends the formated string as a ftp command to a ftp server
2416  *
2417  * NOTE: we build the command in a fixed-length buffer, which sets length
2418  * restrictions on the command!
2419  */
2420 CURLcode Curl_ftpsendf(struct connectdata *conn,
2421                        const char *fmt, ...)
2422 {
2423   ssize_t bytes_written;
2424   char s[256];
2425   size_t write_len;
2426   char *sptr=s;
2427   CURLcode res = CURLE_OK;
2428
2429   va_list ap;
2430   va_start(ap, fmt);
2431   vsnprintf(s, 250, fmt, ap);
2432   va_end(ap);
2433   
2434   strcat(s, "\r\n"); /* append a trailing CRLF */
2435
2436   bytes_written=0;
2437   write_len = strlen(s);
2438
2439   while(1) {
2440     res = Curl_write(conn, conn->sock[FIRSTSOCKET], sptr, write_len,
2441                      &bytes_written);
2442
2443     if(CURLE_OK != res)
2444       break;
2445
2446     if(conn->data->set.verbose)
2447       Curl_debug(conn->data, CURLINFO_HEADER_OUT, sptr, bytes_written);
2448
2449     if(bytes_written != (ssize_t)write_len) {
2450       write_len -= bytes_written;
2451       sptr += bytes_written;
2452     }
2453     else
2454       break;
2455   }
2456
2457   return res;
2458 }
2459
2460 /***********************************************************************
2461  *
2462  * Curl_ftp_quit()
2463  *
2464  * This should be called before calling sclose() on an ftp control connection
2465  * (not data connections). We should then wait for the response from the 
2466  * server before returning. The calling code should then try to close the
2467  * connection.
2468  *
2469  */
2470 CURLcode Curl_ftp_quit(struct connectdata *conn)
2471 {
2472   ssize_t nread;
2473   int ftpcode;
2474   CURLcode ret = CURLE_OK;
2475
2476   if(conn->proto.ftp->ctl_valid) {
2477     ret = Curl_ftpsendf(conn, "%s", "QUIT");
2478     if(CURLE_OK == ret)
2479       ret = Curl_GetFTPResponse(&nread, conn, &ftpcode);
2480   }
2481
2482   return ret;
2483 }
2484
2485 /***********************************************************************
2486  *
2487  * Curl_ftp_disconnect()
2488  *
2489  * Disconnect from an FTP server. Cleanup protocol-specific per-connection
2490  * resources
2491  */
2492 CURLcode Curl_ftp_disconnect(struct connectdata *conn)
2493 {
2494   struct FTP *ftp= conn->proto.ftp;
2495
2496   /* We cannot send quit unconditionally. If this connection is stale or
2497      bad in any way, sending quit and waiting around here will make the
2498      disconnect wait in vain and cause more problems than we need to.
2499
2500      Curl_ftp_quit() will check the state of ftp->ctl_valid. If it's ok it
2501      will try to send the QUIT command, otherwise it will just return.
2502   */
2503
2504   /* The FTP session may or may not have been allocated/setup at this point! */
2505   if(ftp) {
2506     (void)Curl_ftp_quit(conn); /* ignore errors on the QUIT */
2507
2508     if(ftp->entrypath)
2509       free(ftp->entrypath);
2510     if(ftp->cache) {
2511       free(ftp->cache);
2512       ftp->cache = NULL;
2513     }
2514     if(ftp->file) {
2515       free(ftp->file);
2516       ftp->file = NULL; /* zero */
2517     }
2518     freedirs(ftp);
2519   }
2520   return CURLE_OK;
2521 }
2522
2523 /***********************************************************************
2524  *
2525  * ftp_mkd()
2526  *
2527  * Makes a directory on the FTP server.
2528  *
2529  * Calls failf()
2530  */
2531 CURLcode ftp_mkd(struct connectdata *conn, char *path)
2532 {
2533   CURLcode result=CURLE_OK;
2534   int ftpcode; /* for ftp status */
2535   ssize_t nread;
2536
2537   /* Create a directory on the remote server */
2538   FTPSENDF(conn, "MKD %s", path);
2539
2540   result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
2541   if(result)
2542     return result;
2543   
2544   switch(ftpcode) {
2545   case 257:
2546     /* success! */
2547     infof( conn->data , "Created remote directory %s\n" , path );
2548     break;
2549   case 550:
2550     failf(conn->data, "Permission denied to make directory %s", path);
2551     result = CURLE_FTP_ACCESS_DENIED;
2552     break;
2553   default:
2554     failf(conn->data, "unrecognized MKD response: %d", ftpcode );
2555     result = CURLE_FTP_ACCESS_DENIED;
2556     break;
2557   }
2558   return  result;
2559 }
2560
2561 /***********************************************************************
2562  *
2563  * ftp_cwd()
2564  *
2565  * Send 'CWD' to the remote server to Change Working Directory.  It is the ftp
2566  * version of the unix 'cd' command. This function is only called from the
2567  * ftp_cwd_and_mkd() function these days.
2568  *
2569  * This function does NOT call failf().
2570  */
2571 static 
2572 CURLcode ftp_cwd(struct connectdata *conn, char *path)
2573 {
2574   ssize_t nread;
2575   int     ftpcode;
2576   CURLcode result;
2577   
2578   FTPSENDF(conn, "CWD %s", path);
2579   result = Curl_GetFTPResponse(&nread, conn, &ftpcode);
2580   if (!result) {
2581     /* According to RFC959, CWD is supposed to return 250 on success, but
2582        there seem to be non-compliant FTP servers out there that return 200,
2583        so we accept any '2xy' code here. */
2584     if (ftpcode/100 != 2)
2585       result = CURLE_FTP_ACCESS_DENIED;
2586   }
2587
2588   return result;
2589 }
2590
2591 /***********************************************************************
2592  *
2593  * ftp_cwd_and_mkd()
2594  *
2595  * Change to the given directory.  If the directory is not present, and we
2596  * have been told to allow it, then create the directory and cd to it.
2597  *
2598  */
2599 static CURLcode ftp_cwd_and_mkd(struct connectdata *conn, char *path)
2600 {
2601   CURLcode result;
2602   
2603   result = ftp_cwd(conn, path);
2604   if (result) {
2605     if(conn->data->set.ftp_create_missing_dirs) {
2606       result = ftp_mkd(conn, path);
2607       if (result)
2608         /* ftp_mkd() calls failf() itself */
2609         return result;
2610       result = ftp_cwd(conn, path);
2611     }
2612     if(result)
2613       failf(conn->data, "Couldn't cd to %s", path);
2614   }
2615   return result;
2616 }
2617
2618 #endif /* CURL_DISABLE_FTP */