]> git.sesse.net Git - vlc/blob - modules/access/ftp.c
vpx: fix leak
[vlc] / modules / access / ftp.c
1 /*****************************************************************************
2  * ftp.c: FTP input module
3  *****************************************************************************
4  * Copyright (C) 2001-2006 VLC authors and VideoLAN
5  * Copyright © 2006 Rémi Denis-Courmont
6  * $Id$
7  *
8  * Authors: Laurent Aimar <fenrir@via.ecp.fr> - original code
9  *          Rémi Denis-Courmont <rem # videolan.org> - EPSV support
10  *
11  * This program is free software; you can redistribute it and/or modify it
12  * under the terms of the GNU Lesser General Public License as published by
13  * the Free Software Foundation; either version 2.1 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19  * GNU Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public License
22  * along with this program; if not, write to the Free Software Foundation,
23  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24  *****************************************************************************/
25
26 /*****************************************************************************
27  * Preamble
28  *****************************************************************************/
29 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
35
36 #include <assert.h>
37
38 #include <vlc_access.h>
39 #include <vlc_dialog.h>
40
41 #include <vlc_network.h>
42 #include <vlc_url.h>
43 #include <vlc_tls.h>
44 #include <vlc_sout.h>
45 #include <vlc_charset.h>
46
47 #ifndef IPPORT_FTP
48 # define IPPORT_FTP 21u
49 #endif
50
51 #ifndef IPPORT_FTPS
52 # define IPPORT_FTPS 990u
53 #endif
54
55 /*****************************************************************************
56  * Module descriptor
57  *****************************************************************************/
58 static int   InOpen ( vlc_object_t * );
59 static void  InClose( vlc_object_t * );
60 #ifdef ENABLE_SOUT
61 static int  OutOpen ( vlc_object_t * );
62 static void OutClose( vlc_object_t * );
63 #endif
64
65 #define USER_TEXT N_("Username")
66 #define USER_LONGTEXT N_("Username that will be used for the connection, " \
67         "if no username is set in the URL.")
68 #define PASS_TEXT N_("Password")
69 #define PASS_LONGTEXT N_("Password that will be used for the connection, " \
70         "if no username or password are set in URL.")
71 #define ACCOUNT_TEXT N_("FTP account")
72 #define ACCOUNT_LONGTEXT N_("Account that will be " \
73     "used for the connection.")
74
75 vlc_module_begin ()
76     set_shortname( "FTP" )
77     set_description( N_("FTP input") )
78     set_capability( "access", 0 )
79     set_category( CAT_INPUT )
80     set_subcategory( SUBCAT_INPUT_ACCESS )
81     add_string( "ftp-user", "anonymous", USER_TEXT, USER_LONGTEXT,
82                 false )
83     add_string( "ftp-pwd", "anonymous@example.com", PASS_TEXT,
84                 PASS_LONGTEXT, false )
85     add_string( "ftp-account", "anonymous", ACCOUNT_TEXT,
86                 ACCOUNT_LONGTEXT, false )
87     add_shortcut( "ftp", "ftps", "ftpes" )
88     set_callbacks( InOpen, InClose )
89
90 #ifdef ENABLE_SOUT
91     add_submodule ()
92         set_shortname( "FTP" )
93         set_description( N_("FTP upload output") )
94         set_capability( "sout access", 0 )
95         set_category( CAT_SOUT )
96         set_subcategory( SUBCAT_SOUT_ACO )
97         add_shortcut( "ftp", "ftps", "ftpes" )
98         set_callbacks( OutOpen, OutClose )
99 #endif
100 vlc_module_end ()
101
102 /*****************************************************************************
103  * Local prototypes
104  *****************************************************************************/
105 static ssize_t Read( access_t *, uint8_t *, size_t );
106 static int Seek( access_t *, uint64_t );
107 static int Control( access_t *, int, va_list );
108 #ifdef ENABLE_SOUT
109 static int OutSeek( sout_access_out_t *, off_t );
110 static ssize_t Write( sout_access_out_t *, block_t * );
111 #endif
112
113 static void FeaturesCheck( void *, const char * );
114
115 typedef struct ftp_features_t
116 {
117     bool b_unicode;
118     bool b_authtls;
119 } ftp_features_t;
120
121 enum tls_mode_e
122 {
123     NONE = 0,
124     IMPLICIT,/* ftps */
125     EXPLICIT /* ftpes */
126 };
127
128 struct access_sys_t
129 {
130     vlc_url_t  url;
131
132     ftp_features_t   features;
133     vlc_tls_creds_t *p_creds;
134     enum tls_mode_e  tlsmode;
135     struct
136     {
137         vlc_tls_t   *p_tls;
138         v_socket_t  *p_vs;
139         int          fd;
140     } cmd, data;
141
142     char       sz_epsv_ip[NI_MAXNUMERICHOST];
143     bool       out;
144     bool       directory;
145     uint64_t   size;
146 };
147 #define GET_OUT_SYS( p_this ) \
148     ((access_sys_t *)(((sout_access_out_t *)(p_this))->p_sys))
149
150 static int ftp_SendCommand( vlc_object_t *obj, access_sys_t *sys,
151                             const char *fmt, ... )
152 {
153     size_t fmtlen = strlen( fmt );
154     char fmtbuf[fmtlen + 3];
155
156     memcpy( fmtbuf, fmt, fmtlen );
157     memcpy( fmtbuf + fmtlen, "\r\n", 3 );
158
159     va_list args;
160     char *cmd;
161     int val;
162
163     va_start( args, fmt );
164     val = vasprintf( &cmd, fmtbuf, args );
165     va_end( args );
166     if( unlikely(val == -1) )
167         return -1;
168
169     msg_Dbg( obj, "sending request: \"%.*s\" (%d bytes)", val - 2, cmd, val );
170     if( net_Write( obj, sys->cmd.fd, sys->cmd.p_vs, cmd, val ) != val )
171     {
172         msg_Err( obj, "request failure" );
173         val = -1;
174     }
175     else
176         val = 0;
177     free( cmd );
178     return val;
179 }
180
181 /* TODO support this s**t :
182  RFC 959 allows the client to send certain TELNET strings at any moment,
183  even in the middle of a request:
184
185  * \377\377.
186  * \377\376x where x is one byte.
187  * \377\375x where x is one byte. The server is obliged to send \377\374x
188  *                                immediately after reading x.
189  * \377\374x where x is one byte.
190  * \377\373x where x is one byte. The server is obliged to send \377\376x
191  *                                immediately after reading x.
192  * \377x for any other byte x.
193
194  These strings are not part of the requests, except in the case \377\377,
195  where the request contains one \377. */
196 static int ftp_RecvAnswer( vlc_object_t *obj, access_sys_t *sys,
197                            int *restrict codep, char **restrict strp,
198                            void (*cb)(void *, const char *), void *opaque )
199 {
200     if( codep != NULL )
201         *codep = 500;
202     if( strp != NULL )
203         *strp = NULL;
204
205     char *resp = net_Gets( obj, sys->cmd.fd, sys->cmd.p_vs );
206     if( resp == NULL )
207     {
208         msg_Err( obj, "response failure" );
209         goto error;
210     }
211
212     char *end;
213     unsigned code = strtoul( resp, &end, 10 );
214     if( (end - resp) != 3 || (*end != '-' && *end != ' ') )
215     {
216         msg_Err( obj, "malformatted response" );
217         goto error;
218     }
219     msg_Dbg( obj, "received response: \"%s\"", resp );
220
221     if( *end == '-' ) /* Multi-line response */
222     {
223         bool done;
224
225         *end = ' ';
226         do
227         {
228             char *line = net_Gets( obj, sys->cmd.fd, sys->cmd.p_vs );
229             if( line == NULL )
230             {
231                 msg_Err( obj, "response failure" );
232                 goto error;
233             }
234
235             done = !strncmp( resp, line, 4 );
236             if( !done )
237                 cb( opaque, line );
238             free( line );
239         }
240         while( !done );
241     }
242
243     if( codep != NULL )
244         *codep = code;
245     if( strp != NULL )
246         *strp = resp;
247     else
248         free( resp );
249     return code / 100;
250 error:
251     free( resp );
252     return -1;
253 }
254
255 static void DummyLine( void *data, const char *str )
256 {
257     (void) data; (void) str;
258 }
259
260 static int ftp_RecvCommand( vlc_object_t *obj, access_sys_t *sys,
261                             int *restrict codep, char **restrict strp )
262 {
263     return ftp_RecvAnswer( obj, sys, codep, strp, DummyLine, NULL );
264 }
265
266 static int ftp_StartStream( vlc_object_t *, access_sys_t *, uint64_t );
267 static int ftp_StopStream ( vlc_object_t *, access_sys_t * );
268
269 static void readTLSMode( access_sys_t *p_sys, const char * psz_access )
270 {
271     if ( !strncmp( psz_access, "ftps", 4 ) )
272         p_sys->tlsmode = IMPLICIT;
273     else
274     if ( !strncmp( psz_access, "ftpes", 5 ) )
275         p_sys->tlsmode = EXPLICIT;
276     else
277         p_sys->tlsmode = NONE;
278 }
279
280 static int createCmdTLS( vlc_object_t *p_access, access_sys_t *p_sys, int fd,
281                          const char *psz_session_name )
282 {
283     p_sys->p_creds = vlc_tls_ClientCreate( p_access );
284     if( p_sys->p_creds == NULL ) return -1;
285
286     /* TLS/SSL handshake */
287     p_sys->cmd.p_tls = vlc_tls_ClientSessionCreate( p_sys->p_creds, fd,
288                                                     p_sys->url.psz_host,
289                                                     psz_session_name,
290                                                     NULL, NULL );
291     if( p_sys->cmd.p_tls == NULL )
292     {
293         msg_Err( p_access, "cannot establish FTP/TLS session on command channel" );
294         return -1;
295     }
296     p_sys->cmd.p_vs = &p_sys->cmd.p_tls->sock;
297
298     return 0;
299 }
300
301 static void clearCmdTLS( access_sys_t *p_sys )
302 {
303     if ( p_sys->cmd.p_tls ) vlc_tls_SessionDelete( p_sys->cmd.p_tls );
304     if ( p_sys->p_creds ) vlc_tls_Delete( p_sys->p_creds );
305     p_sys->cmd.p_tls = NULL;
306     p_sys->cmd.p_vs = NULL;
307     p_sys->p_creds = NULL;
308 }
309
310 static int Login( vlc_object_t *p_access, access_sys_t *p_sys )
311 {
312     int i_answer;
313
314     /* *** Open a TCP connection with server *** */
315     int fd = p_sys->cmd.fd = net_ConnectTCP( p_access, p_sys->url.psz_host,
316                                              p_sys->url.i_port );
317     if( fd == -1 )
318     {
319         msg_Err( p_access, "connection failed" );
320         dialog_Fatal( p_access, _("Network interaction failed"), "%s",
321                         _("VLC could not connect with the given server.") );
322         return -1;
323     }
324
325     if ( p_sys->tlsmode == IMPLICIT ) /* FTPS Mode */
326     {
327         if ( createCmdTLS( p_access, p_sys, fd, "ftps") < 0 )
328             goto error;
329     }
330
331     while( ftp_RecvCommand( p_access, p_sys, &i_answer, NULL ) == 1 );
332
333     if( i_answer / 100 != 2 )
334     {
335         msg_Err( p_access, "connection rejected" );
336         dialog_Fatal( p_access, _("Network interaction failed"), "%s",
337                         _("VLC's connection to the given server was rejected.") );
338         return -1;
339     }
340
341     msg_Dbg( p_access, "connection accepted (%d)", i_answer );
342
343     /* Features check first */
344     if( ftp_SendCommand( p_access, p_sys, "FEAT" ) < 0
345      || ftp_RecvAnswer( p_access, p_sys, NULL, NULL,
346                         FeaturesCheck, &p_sys->features ) < 0 )
347     {
348          msg_Err( p_access, "cannot get server features" );
349          return -1;
350     }
351
352     /* Create TLS Session */
353     if( p_sys->tlsmode == EXPLICIT )
354     {
355         if ( ! p_sys->features.b_authtls )
356         {
357             msg_Err( p_access, "Server does not support TLS" );
358             return -1;
359         }
360
361         if( ftp_SendCommand( p_access, p_sys, "AUTH TLS" ) < 0
362          || ftp_RecvCommand( p_access, p_sys, &i_answer, NULL ) < 0
363          || i_answer != 234 )
364         {
365              msg_Err( p_access, "cannot switch to TLS: server replied with code %d",
366                       i_answer );
367              return -1;
368         }
369
370         if ( createCmdTLS( p_access, p_sys, fd, "ftpes") < 0 )
371         {
372             goto error;
373         }
374     }
375
376     if( p_sys->tlsmode != NONE )
377     {
378         if( ftp_SendCommand( p_access, p_sys, "PBSZ 0" ) < 0 ||
379             ftp_RecvCommand( p_access, p_sys, &i_answer, NULL ) < 0 ||
380             i_answer != 200 )
381         {
382             msg_Err( p_access, "Can't truncate Protection buffer size for TLS" );
383             goto error;
384         }
385
386         if( ftp_SendCommand( p_access, p_sys, "PROT P" ) < 0 ||
387             ftp_RecvCommand( p_access, p_sys, &i_answer, NULL ) < 0 ||
388             i_answer != 200 )
389         {
390             msg_Err( p_access, "Can't set Data channel protection" );
391             goto error;
392         }
393     }
394
395     /* Send credentials over channel */
396     char *psz;
397
398     if( p_sys->url.psz_username && *p_sys->url.psz_username )
399         psz = strdup( p_sys->url.psz_username );
400     else
401         psz = var_InheritString( p_access, "ftp-user" );
402     if( !psz )
403         goto error;
404
405     if( ftp_SendCommand( p_access, p_sys, "USER %s", psz ) < 0 ||
406         ftp_RecvCommand( p_access, p_sys, &i_answer, NULL ) < 0 )
407     {
408         free( psz );
409         goto error;
410     }
411     free( psz );
412
413     switch( i_answer / 100 )
414     {
415         case 2:
416             /* X.509 auth successful after AUTH TLS / RFC 2228 sec. 4 */
417             if ( i_answer == 232 )
418                 msg_Dbg( p_access, "user accepted and authenticated" );
419             else
420                 msg_Dbg( p_access, "user accepted" );
421             break;
422         case 3:
423             msg_Dbg( p_access, "password needed" );
424             if( p_sys->url.psz_password && *p_sys->url.psz_password )
425                 psz = strdup( p_sys->url.psz_password );
426             else
427                 psz = var_InheritString( p_access, "ftp-pwd" );
428             if( !psz )
429                 goto error;
430
431             if( ftp_SendCommand( p_access, p_sys, "PASS %s", psz ) < 0 ||
432                 ftp_RecvCommand( p_access, p_sys, &i_answer, NULL ) < 0 )
433             {
434                 free( psz );
435                 goto error;
436             }
437             free( psz );
438
439             switch( i_answer / 100 )
440             {
441                 case 2:
442                     msg_Dbg( p_access, "password accepted" );
443                     break;
444                 case 3:
445                     msg_Dbg( p_access, "account needed" );
446                     psz = var_InheritString( p_access, "ftp-account" );
447                     if( ftp_SendCommand( p_access, p_sys, "ACCT %s",
448                                          psz ) < 0 ||
449                         ftp_RecvCommand( p_access, p_sys, &i_answer, NULL ) < 0 )
450                     {
451                         free( psz );
452                         goto error;
453                     }
454                     free( psz );
455
456                     if( i_answer / 100 != 2 )
457                     {
458                         msg_Err( p_access, "account rejected" );
459                         dialog_Fatal( p_access,
460                                       _("Network interaction failed"),
461                                       "%s", _("Your account was rejected.") );
462                         goto error;
463                     }
464                     msg_Dbg( p_access, "account accepted" );
465                     break;
466
467                 default:
468                     msg_Err( p_access, "password rejected" );
469                     dialog_Fatal( p_access, _("Network interaction failed"),
470                                   "%s",  _("Your password was rejected.") );
471                     goto error;
472             }
473             break;
474         default:
475             msg_Err( p_access, "user rejected" );
476             dialog_Fatal( p_access, _("Network interaction failed"), "%s",
477                         _("Your connection attempt to the server was rejected.") );
478             goto error;
479     }
480
481     return 0;
482
483 error:
484     clearCmdTLS( p_sys );
485     return -1;
486 }
487
488 static void FeaturesCheck( void *opaque, const char *feature )
489 {
490     ftp_features_t *features = opaque;
491
492     if( strcasestr( feature, "UTF8" ) != NULL )
493         features->b_unicode = true;
494     else
495     if( strcasestr( feature, "AUTH TLS" ) != NULL )
496         features->b_authtls = true;
497 }
498
499 static const char *IsASCII( const char *str )
500 {
501     int8_t c;
502     for( const char *p = str; (c = *p) != '\0'; p++ )
503         if( c < 0 )
504             return NULL;
505     return str;
506 }
507
508 static int Connect( vlc_object_t *p_access, access_sys_t *p_sys )
509 {
510     if( Login( p_access, p_sys ) < 0 )
511         return -1;
512
513     /* Extended passive mode */
514     if( ftp_SendCommand( p_access, p_sys, "EPSV ALL" ) < 0 )
515     {
516         msg_Err( p_access, "cannot request extended passive mode" );
517         goto error;
518     }
519
520     if( ftp_RecvCommand( p_access, p_sys, NULL, NULL ) == 2 )
521     {
522         if( net_GetPeerAddress( p_sys->cmd.fd, p_sys->sz_epsv_ip, NULL ) )
523             goto error;
524     }
525     else
526     {
527         /* If ESPV ALL fails, we fallback to PASV.
528          * We have to restart the connection in case there is a NAT that
529          * understands EPSV ALL in the way, and hence won't allow PASV on
530          * the initial connection.
531          */
532         msg_Info( p_access, "FTP Extended passive mode disabled" );
533         clearCmdTLS( p_sys );
534         net_Close( p_sys->cmd.fd );
535
536         if( Login( p_access, p_sys ) )
537             goto error;
538     }
539
540     if( (p_sys->features.b_unicode ? IsUTF8 : IsASCII)(p_sys->url.psz_path) == NULL )
541     {
542         msg_Err( p_access, "unsupported path: \"%s\"", p_sys->url.psz_path );
543         goto error;
544     }
545
546     /* check binary mode support */
547     if( ftp_SendCommand( p_access, p_sys, "TYPE I" ) < 0 ||
548         ftp_RecvCommand( p_access, p_sys, NULL, NULL ) != 2 )
549     {
550         msg_Err( p_access, "cannot set binary transfer mode" );
551         goto error;
552     }
553
554     return 0;
555
556 error:
557     clearCmdTLS( p_sys );
558     net_Close( p_sys->cmd.fd );
559     return -1;
560 }
561
562
563 static int parseURL( vlc_url_t *url, const char *path, enum tls_mode_e mode )
564 {
565     if( path == NULL )
566         return VLC_EGENERIC;
567
568     /* *** Parse URL and get server addr/port and path *** */
569     while( *path == '/' )
570         path++;
571
572     vlc_UrlParse( url, path, 0 );
573
574     if( url->psz_host == NULL || *url->psz_host == '\0' )
575         return VLC_EGENERIC;
576
577     if( url->i_port <= 0 )
578     {
579         if( mode == IMPLICIT )
580             url->i_port = IPPORT_FTPS;
581         else
582             url->i_port = IPPORT_FTP; /* default port */
583     }
584
585     if( url->psz_path == NULL )
586         return VLC_SUCCESS;
587     /* FTP URLs are relative to user's default directory (RFC1738 §3.2)
588     For absolute path use ftp://foo.bar//usr/local/etc/filename */
589     /* FIXME: we should issue a series of CWD, one per slash */
590     if( url->psz_path )
591     {
592         assert( url->psz_path[0] == '/' );
593         url->psz_path++;
594     }
595
596     char *type = strstr( url->psz_path, ";type=" );
597     if( type )
598     {
599         *type = '\0';
600         if( strchr( "iI", type[6] ) == NULL )
601             return VLC_EGENERIC; /* ASCII and directory not supported */
602     }
603     decode_URI( url->psz_path );
604     return VLC_SUCCESS;
605 }
606
607
608 /****************************************************************************
609  * Open: connect to ftp server and ask for file
610  ****************************************************************************/
611 static int InOpen( vlc_object_t *p_this )
612 {
613     access_t     *p_access = (access_t*)p_this;
614     access_sys_t *p_sys;
615     char         *psz_arg;
616
617     /* Init p_access */
618     STANDARD_READ_ACCESS_INIT
619     p_sys->data.fd = -1;
620     p_sys->out = false;
621     p_sys->directory = false;
622     p_sys->size = 0;
623     readTLSMode( p_sys, p_access->psz_access );
624
625     if( parseURL( &p_sys->url, p_access->psz_location, p_sys->tlsmode ) )
626         goto exit_error;
627
628     if( Connect( p_this, p_sys ) )
629         goto exit_error;
630
631     /* get size */
632     if( p_sys->url.psz_path == NULL )
633         p_sys->directory = true;
634     else
635     if( ftp_SendCommand( p_this, p_sys, "SIZE %s", p_sys->url.psz_path ) < 0 )
636         goto error;
637     else
638     if ( ftp_RecvCommand( p_this, p_sys, NULL, &psz_arg ) == 2 )
639     {
640         p_sys->size = atoll( &psz_arg[4] );
641         free( psz_arg );
642         msg_Dbg( p_access, "file size: %"PRIu64, p_sys->size );
643     }
644     else
645     if( ftp_SendCommand( p_this, p_sys, "CWD %s", p_sys->url.psz_path ) < 0 )
646         goto error;
647     else
648     if( ftp_RecvCommand( p_this, p_sys, NULL, NULL ) != 2 )
649     {
650         msg_Err( p_this, "file or directory does not exist" );
651         goto error;
652     }
653     else
654         p_sys->directory = true;
655
656     /* Start the 'stream' */
657     if( ftp_StartStream( p_this, p_sys, 0 ) < 0 )
658     {
659         msg_Err( p_this, "cannot retrieve file" );
660         clearCmdTLS( p_sys );
661         net_Close( p_sys->cmd.fd );
662         goto exit_error;
663     }
664
665     return VLC_SUCCESS;
666
667 error:
668     clearCmdTLS( p_sys );
669     net_Close( p_sys->cmd.fd );
670
671 exit_error:
672     vlc_UrlClean( &p_sys->url );
673     free( p_sys );
674     return VLC_EGENERIC;
675 }
676
677 #ifdef ENABLE_SOUT
678 static int OutOpen( vlc_object_t *p_this )
679 {
680     sout_access_out_t *p_access = (sout_access_out_t *)p_this;
681     access_sys_t      *p_sys;
682
683     p_sys = calloc( 1, sizeof( *p_sys ) );
684     if( !p_sys )
685         return VLC_ENOMEM;
686
687     /* Init p_access */
688     p_sys->data.fd = -1;
689     p_sys->out = true;
690     readTLSMode( p_sys, p_access->psz_access );
691
692     if( parseURL( &p_sys->url, p_access->psz_path, p_sys->tlsmode ) )
693         goto exit_error;
694     if( p_sys->url.psz_path == NULL )
695     {
696         msg_Err( p_this, "no filename specified" );
697         goto exit_error;
698     }
699
700     if( Connect( p_this, p_sys ) )
701         goto exit_error;
702
703     /* Start the 'stream' */
704     if( ftp_StartStream( p_this, p_sys, 0 ) < 0 )
705     {
706         msg_Err( p_access, "cannot store file" );
707         clearCmdTLS( p_sys );
708         net_Close( p_sys->cmd.fd );
709         goto exit_error;
710     }
711
712     p_access->pf_seek = OutSeek;
713     p_access->pf_write = Write;
714     p_access->p_sys = (void *)p_sys;
715
716     return VLC_SUCCESS;
717
718 exit_error:
719     vlc_UrlClean( &p_sys->url );
720     free( p_sys );
721     return VLC_EGENERIC;
722 }
723 #endif
724
725 /*****************************************************************************
726  * Close: free unused data structures
727  *****************************************************************************/
728 static void Close( vlc_object_t *p_access, access_sys_t *p_sys )
729 {
730     msg_Dbg( p_access, "stopping stream" );
731     ftp_StopStream( p_access, p_sys );
732
733     if( ftp_SendCommand( p_access, p_sys, "QUIT" ) < 0 )
734     {
735         msg_Warn( p_access, "cannot quit" );
736     }
737     else
738     {
739         ftp_RecvCommand( p_access, p_sys, NULL, NULL );
740     }
741
742     clearCmdTLS( p_sys );
743     net_Close( p_sys->cmd.fd );
744
745     /* free memory */
746     vlc_UrlClean( &p_sys->url );
747     free( p_sys );
748 }
749
750 static void InClose( vlc_object_t *p_this )
751 {
752     Close( p_this, ((access_t *)p_this)->p_sys);
753 }
754
755 #ifdef ENABLE_SOUT
756 static void OutClose( vlc_object_t *p_this )
757 {
758     Close( p_this, GET_OUT_SYS(p_this));
759 }
760 #endif
761
762
763 /*****************************************************************************
764  * Seek: try to go at the right place
765  *****************************************************************************/
766 static int _Seek( vlc_object_t *p_access, access_sys_t *p_sys, uint64_t i_pos )
767 {
768     msg_Dbg( p_access, "seeking to %"PRIu64, i_pos );
769
770     ftp_StopStream( (vlc_object_t *)p_access, p_sys );
771     if( ftp_StartStream( (vlc_object_t *)p_access, p_sys, i_pos ) < 0 )
772         return VLC_EGENERIC;
773
774     return VLC_SUCCESS;
775 }
776
777 static int Seek( access_t *p_access, uint64_t i_pos )
778 {
779     int val = _Seek( (vlc_object_t *)p_access, p_access->p_sys, i_pos );
780     if( val )
781         return val;
782
783     p_access->info.b_eof = false;
784     p_access->info.i_pos = i_pos;
785
786     return VLC_SUCCESS;
787 }
788
789 #ifdef ENABLE_SOUT
790 static int OutSeek( sout_access_out_t *p_access, off_t i_pos )
791 {
792     return _Seek( (vlc_object_t *)p_access, GET_OUT_SYS( p_access ), i_pos);
793 }
794 #endif
795
796 /*****************************************************************************
797  * Read:
798  *****************************************************************************/
799 static ssize_t Read( access_t *p_access, uint8_t *p_buffer, size_t i_len )
800 {
801     access_sys_t *p_sys = p_access->p_sys;
802
803     assert( p_sys->data.fd != -1 );
804     assert( !p_sys->out );
805
806     if( p_access->info.b_eof )
807         return 0;
808
809     if( p_sys->directory )
810     {
811         char *psz_line = net_Gets( p_access, p_sys->data.fd, p_sys->data.p_vs );
812         if( !psz_line )
813         {
814             p_access->info.b_eof = true;
815             return 0;
816         }
817         else
818         {
819             snprintf( (char*)p_buffer, i_len, "%s://%s:%d/%s/%s\n",
820                       ( p_sys->tlsmode == NONE ) ? "ftp" :
821                       ( ( p_sys->tlsmode == IMPLICIT ) ? "ftps" : "ftpes" ),
822                       p_sys->url.psz_host, p_sys->url.i_port,
823                       p_sys->url.psz_path, psz_line );
824             free( psz_line );
825             return strlen( (const char *)p_buffer );
826         }
827     }
828     else
829     {
830         int i_read = net_Read( p_access, p_sys->data.fd, p_sys->data.p_vs,
831                                p_buffer, i_len, false );
832         if( i_read == 0 )
833             p_access->info.b_eof = true;
834         else if( i_read > 0 )
835             p_access->info.i_pos += i_read;
836
837         return i_read;
838     }
839 }
840
841 /*****************************************************************************
842  * Write:
843  *****************************************************************************/
844 #ifdef ENABLE_SOUT
845 static ssize_t Write( sout_access_out_t *p_access, block_t *p_buffer )
846 {
847     access_sys_t *p_sys = GET_OUT_SYS(p_access);
848     size_t i_write = 0;
849
850     assert( p_sys->data.fd != -1 );
851
852     while( p_buffer != NULL )
853     {
854         block_t *p_next = p_buffer->p_next;;
855
856         i_write += net_Write( p_access, p_sys->data.fd, p_sys->data.p_vs,
857                               p_buffer->p_buffer, p_buffer->i_buffer );
858         block_Release( p_buffer );
859
860         p_buffer = p_next;
861     }
862
863     return i_write;
864 }
865 #endif
866
867 /*****************************************************************************
868  * Control:
869  *****************************************************************************/
870 static int Control( access_t *p_access, int i_query, va_list args )
871 {
872     bool    *pb_bool;
873     int64_t *pi_64;
874
875     switch( i_query )
876     {
877         case ACCESS_CAN_SEEK:
878             pb_bool = (bool*)va_arg( args, bool* );
879             *pb_bool = !p_access->p_sys->directory;
880             break;
881         case ACCESS_CAN_FASTSEEK:
882             pb_bool = (bool*)va_arg( args, bool* );
883             *pb_bool = false;
884             break;
885         case ACCESS_CAN_PAUSE:
886             pb_bool = (bool*)va_arg( args, bool* );
887             *pb_bool = true;    /* FIXME */
888             break;
889         case ACCESS_CAN_CONTROL_PACE:
890             pb_bool = (bool*)va_arg( args, bool* );
891             *pb_bool = true;    /* FIXME */
892             break;
893         case ACCESS_GET_SIZE:
894             *va_arg( args, uint64_t * ) = p_access->p_sys->size;
895             break;
896
897         case ACCESS_GET_PTS_DELAY:
898             pi_64 = (int64_t*)va_arg( args, int64_t * );
899             *pi_64 = INT64_C(1000)
900                    * var_InheritInteger( p_access, "network-caching" );
901             break;
902
903         case ACCESS_SET_PAUSE_STATE:
904             pb_bool = (bool*)va_arg( args, bool* );
905             if ( !pb_bool )
906               return Seek( p_access, p_access->info.i_pos );
907             break;
908
909         default:
910             return VLC_EGENERIC;
911
912     }
913     return VLC_SUCCESS;
914 }
915
916 static int ftp_StartStream( vlc_object_t *p_access, access_sys_t *p_sys,
917                             uint64_t i_start )
918 {
919     char psz_ipv4[16], *psz_ip = p_sys->sz_epsv_ip;
920     int  i_answer;
921     char *psz_arg, *psz_parser;
922     int  i_port;
923
924     assert( p_sys->data.fd == -1 );
925
926     if( ( ftp_SendCommand( p_access, p_sys, *psz_ip ? "EPSV" : "PASV" ) < 0 )
927      || ( ftp_RecvCommand( p_access, p_sys, &i_answer, &psz_arg ) != 2 ) )
928     {
929         msg_Err( p_access, "cannot set passive mode" );
930         return VLC_EGENERIC;
931     }
932
933     psz_parser = strchr( psz_arg, '(' );
934     if( psz_parser == NULL )
935     {
936         free( psz_arg );
937         msg_Err( p_access, "cannot parse passive mode response" );
938         return VLC_EGENERIC;
939     }
940
941     if( *psz_ip )
942     {
943         char psz_fmt[7] = "(|||%u";
944         psz_fmt[1] = psz_fmt[2] = psz_fmt[3] = psz_parser[1];
945
946         if( sscanf( psz_parser, psz_fmt, &i_port ) < 1 )
947         {
948             free( psz_arg );
949             msg_Err( p_access, "cannot parse passive mode response" );
950             return VLC_EGENERIC;
951         }
952     }
953     else
954     {
955         unsigned a1, a2, a3, a4, p1, p2;
956
957         if( ( sscanf( psz_parser, "(%u,%u,%u,%u,%u,%u", &a1, &a2, &a3, &a4,
958                       &p1, &p2 ) < 6 ) || ( a1 > 255 ) || ( a2 > 255 )
959          || ( a3 > 255 ) || ( a4 > 255 ) || ( p1 > 255 ) || ( p2 > 255 ) )
960         {
961             free( psz_arg );
962             msg_Err( p_access, "cannot parse passive mode response" );
963             return VLC_EGENERIC;
964         }
965
966         sprintf( psz_ipv4, "%u.%u.%u.%u", a1, a2, a3, a4 );
967         psz_ip = psz_ipv4;
968         i_port = (p1 << 8) | p2;
969     }
970     free( psz_arg );
971
972     msg_Dbg( p_access, "ip:%s port:%d", psz_ip, i_port );
973
974     if( ftp_SendCommand( p_access, p_sys, "TYPE I" ) < 0 ||
975         ftp_RecvCommand( p_access, p_sys, &i_answer, NULL ) != 2 )
976     {
977         msg_Err( p_access, "cannot set binary transfer mode" );
978         return VLC_EGENERIC;
979     }
980
981     if( i_start > 0 )
982     {
983         if( ftp_SendCommand( p_access, p_sys, "REST %"PRIu64, i_start ) < 0 ||
984             ftp_RecvCommand( p_access, p_sys, &i_answer, NULL ) > 3 )
985         {
986             msg_Err( p_access, "cannot set restart offset" );
987             return VLC_EGENERIC;
988         }
989     }
990
991     msg_Dbg( p_access, "waiting for data connection..." );
992     p_sys->data.fd = net_ConnectTCP( p_access, psz_ip, i_port );
993     if( p_sys->data.fd < 0 )
994     {
995         msg_Err( p_access, "failed to connect with server" );
996         return VLC_EGENERIC;
997     }
998     msg_Dbg( p_access, "connection with \"%s:%d\" successful",
999              psz_ip, i_port );
1000
1001     if( p_sys->directory )
1002     {
1003         if( ftp_SendCommand( p_access, p_sys, "NLST" ) < 0 ||
1004             ftp_RecvCommand( p_access, p_sys, NULL, &psz_arg ) > 2 )
1005         {
1006             msg_Err( p_access, "cannot list directory contents" );
1007         return VLC_EGENERIC;
1008         }
1009     }
1010     else
1011     {
1012         /* "1xx" message */
1013         assert( p_sys->url.psz_path );
1014         if( ftp_SendCommand( p_access, p_sys, "%s %s",
1015                              p_sys->out ? "STOR" : "RETR",
1016                              p_sys->url.psz_path ) < 0
1017          || ftp_RecvCommand( p_access, p_sys, &i_answer, NULL ) > 2 )
1018         {
1019             msg_Err( p_access, "cannot retrieve file" );
1020             return VLC_EGENERIC;
1021         }
1022     }
1023
1024     if( p_sys->tlsmode != NONE )
1025     {
1026         /* FIXME: Do Reuse TLS Session */
1027         /* TLS/SSL handshake */
1028         p_sys->data.p_tls = vlc_tls_ClientSessionCreate( p_sys->p_creds,
1029                             p_sys->data.fd, p_sys->url.psz_host,
1030                             ( p_sys->tlsmode == EXPLICIT ) ? "ftpes-data"
1031                                                            : "ftps-data",
1032                                                          NULL, NULL );
1033         if( p_sys->data.p_tls == NULL )
1034         {
1035             msg_Err( p_access, "cannot establish FTP/TLS session for data" \
1036                              ": server not allowing new session ?" );
1037             return VLC_EGENERIC;
1038         }
1039         p_sys->data.p_vs = &p_sys->data.p_tls->sock;
1040     }
1041     else
1042         shutdown( p_sys->data.fd, p_sys->out ? SHUT_RD : SHUT_WR );
1043
1044     return VLC_SUCCESS;
1045 }
1046
1047 static int ftp_StopStream ( vlc_object_t *p_access, access_sys_t *p_sys )
1048 {
1049     if( ftp_SendCommand( p_access, p_sys, "ABOR" ) < 0 )
1050     {
1051         msg_Warn( p_access, "cannot abort file" );
1052         if( p_sys->data.fd > 0 )
1053         {
1054             if ( p_sys->data.p_tls ) vlc_tls_SessionDelete( p_sys->data.p_tls );
1055             net_Close( p_sys->data.fd );
1056         }
1057         p_sys->data.fd = -1;
1058         p_sys->data.p_tls = NULL;
1059         p_sys->data.p_vs = NULL;
1060         return VLC_EGENERIC;
1061     }
1062
1063     if( p_sys->data.fd != -1 )
1064     {
1065         if ( p_sys->data.p_tls ) vlc_tls_SessionDelete( p_sys->data.p_tls );
1066         net_Close( p_sys->data.fd );
1067         p_sys->data.fd = -1;
1068         p_sys->data.p_tls = NULL;
1069         p_sys->data.p_vs = NULL;
1070         /* Read the final response from RETR/STOR, i.e. 426 or 226 */
1071         ftp_RecvCommand( p_access, p_sys, NULL, NULL );
1072     }
1073     /* Read the response from ABOR, i.e. 226 or 225 */
1074     ftp_RecvCommand( p_access, p_sys, NULL, NULL );
1075
1076     return VLC_SUCCESS;
1077 }