]> git.sesse.net Git - vlc/blob - modules/access/ftp.c
- Fix (?) handling of EPSV non-compliant FTP servers
[vlc] / modules / access / ftp.c
1 /*****************************************************************************
2  * ftp.c: FTP input module
3  *****************************************************************************
4  * Copyright (C) 2001-2005 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr> - original code
8  *          RĂ©mi Denis-Courmont <rem # videolan.org> - EPSV support
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #include <stdlib.h>
29
30 #include <vlc/vlc.h>
31 #include <vlc/input.h>
32
33 #include "network.h"
34 #if defined( UNDER_CE )
35 #   include <winsock.h>
36 #elif defined( WIN32 )
37 #   include <winsock2.h>
38 #else
39 #   include <sys/socket.h>
40 #endif
41
42 /*****************************************************************************
43  * Module descriptor
44  *****************************************************************************/
45 static int     Open ( vlc_object_t * );
46 static void    Close( vlc_object_t * );
47
48 #define CACHING_TEXT N_("Caching value in ms")
49 #define CACHING_LONGTEXT N_( \
50     "Allows you to modify the default caching value for FTP streams. This " \
51     "value should be set in millisecond units." )
52 #define USER_TEXT N_("FTP user name")
53 #define USER_LONGTEXT N_("Allows you to modify the user name that will " \
54     "be used for the connection.")
55 #define PASS_TEXT N_("FTP password")
56 #define PASS_LONGTEXT N_("Allows you to modify the password that will be " \
57     "used for the connection.")
58 #define ACCOUNT_TEXT N_("FTP account")
59 #define ACCOUNT_LONGTEXT N_("Allows you to modify the account that will be " \
60     "used for the connection.")
61
62 vlc_module_begin();
63     set_shortname( "FTP" );
64     set_description( _("FTP input") );
65     set_capability( "access2", 0 );
66     set_category( CAT_INPUT );
67     set_subcategory( SUBCAT_INPUT_ACCESS );
68     add_integer( "ftp-caching", 2 * DEFAULT_PTS_DELAY / 1000, NULL,
69                  CACHING_TEXT, CACHING_LONGTEXT, VLC_TRUE );
70     add_string( "ftp-user", "anonymous", NULL, USER_TEXT, USER_LONGTEXT,
71                 VLC_FALSE );
72     add_string( "ftp-pwd", "anonymous@dummy.org", NULL, PASS_TEXT,
73                 PASS_LONGTEXT, VLC_FALSE );
74     add_string( "ftp-account", "anonymous", NULL, ACCOUNT_TEXT,
75                 ACCOUNT_LONGTEXT, VLC_FALSE );
76     add_shortcut( "ftp" );
77     set_callbacks( Open, Close );
78 vlc_module_end();
79
80 /*****************************************************************************
81  * Local prototypes
82  *****************************************************************************/
83 static int Read( access_t *, uint8_t *, int );
84 static int Seek( access_t *, int64_t );
85 static int Control( access_t *, int, va_list );
86
87 struct access_sys_t
88 {
89     vlc_url_t  url;
90
91     int        fd_cmd;
92     int        fd_data;
93     
94     char       *psz_epsv_ip;
95 };
96
97 static int  ftp_SendCommand( access_t *, char *, ... );
98 static int  ftp_ReadCommand( access_t *, int *, char ** );
99 static int  ftp_StartStream( access_t *, int64_t );
100 static int  ftp_StopStream ( access_t *);
101
102 static int Connect( access_t *p_access, access_sys_t *p_sys )
103 {
104     int fd, i_answer;
105     char *psz;
106
107     /* *** Open a TCP connection with server *** */
108     msg_Dbg( p_access, "waiting for connection..." );
109     p_sys->fd_cmd = fd = net_OpenTCP( p_access, p_sys->url.psz_host,
110                                       p_sys->url.i_port );
111     if( fd < 0 )
112     {
113         msg_Err( p_access, "failed to connect with server" );
114         return -1;
115     }
116
117     for( ;; )
118     {
119         if( ftp_ReadCommand( p_access, &i_answer, NULL ) != 1 )
120         {
121             break;
122         }
123     }
124     if( i_answer / 100 != 2 )
125     {
126         msg_Err( p_access, "connection rejected" );
127         return -1;
128     }
129
130     msg_Dbg( p_access, "connection accepted (%d)", i_answer );
131
132     psz = var_CreateGetString( p_access, "ftp-user" );
133     if( ftp_SendCommand( p_access, "USER %s", psz ) < 0 ||
134         ftp_ReadCommand( p_access, &i_answer, NULL ) < 0 )
135     {
136         free( psz );
137         return -1;
138     }
139     free( psz );
140
141     switch( i_answer / 100 )
142     {
143         case 2:
144             msg_Dbg( p_access, "user accepted" );
145             break;
146         case 3:
147             msg_Dbg( p_access, "password needed" );
148             psz = var_CreateGetString( p_access, "ftp-pwd" );
149             if( ftp_SendCommand( p_access, "PASS %s", psz ) < 0 ||
150                 ftp_ReadCommand( p_access, &i_answer, NULL ) < 0 )
151             {
152                 free( psz );
153                 return -1;
154             }
155             free( psz );
156
157             switch( i_answer / 100 )
158             {
159                 case 2:
160                     msg_Dbg( p_access, "password accepted" );
161                     break;
162                 case 3:
163                     msg_Dbg( p_access, "account needed" );
164                     psz = var_CreateGetString( p_access, "ftp-account" );
165                     if( ftp_SendCommand( p_access, "ACCT %s",
166                                          psz ) < 0 ||
167                         ftp_ReadCommand( p_access, &i_answer, NULL ) < 0 )
168                     {
169                         free( psz );
170                         return -1;
171                     }
172                     free( psz );
173
174                     if( i_answer / 100 != 2 )
175                     {
176                         msg_Err( p_access, "account rejected" );
177                         return -1;
178                     }
179                     msg_Dbg( p_access, "account accepted" );
180                     break;
181
182                 default:
183                     msg_Err( p_access, "password rejected" );
184                     return -1;
185             }
186             break;
187         default:
188             msg_Err( p_access, "user rejected" );
189             return -1;
190     }
191
192     /* Extended passive mode */
193     if( ftp_SendCommand( p_access, "EPSV ALL" ) < 0 )
194     {
195         msg_Err( p_access, "cannot request extended passive mode" );
196         return -1;
197     }
198
199     return 0;
200 }
201
202 /****************************************************************************
203  * Open: connect to ftp server and ask for file
204  ****************************************************************************/
205 static int Open( vlc_object_t *p_this )
206 {
207     access_t     *p_access = (access_t*)p_this;
208     access_sys_t *p_sys;
209     char         *psz;
210
211     int          i_answer;
212     char         *psz_arg;
213
214     /* Init p_access */
215     p_access->pf_read = Read;
216     p_access->pf_block = NULL;
217     p_access->pf_seek = Seek;
218     p_access->pf_control = Control;
219     p_access->info.i_update = 0;
220     p_access->info.i_size = 0;
221     p_access->info.i_pos = 0;
222     p_access->info.b_eof = VLC_FALSE;
223     p_access->info.i_title = 0;
224     p_access->info.i_seekpoint = 0;
225     p_access->p_sys = p_sys = malloc( sizeof( access_sys_t ) );
226     memset( p_sys, 0, sizeof( access_sys_t ) );
227     p_sys->fd_cmd = -1;
228     p_sys->fd_data = -1;
229     p_sys->psz_epsv_ip = NULL;
230
231     /* *** Parse URL and get server addr/port and path *** */
232     psz = p_access->psz_path;
233     while( *psz == '/' )
234     {
235         psz++;
236     }
237     vlc_UrlParse( &p_sys->url, psz, 0 );
238
239     if( p_sys->url.psz_host == NULL || *p_sys->url.psz_host == '\0' )
240     {
241         msg_Err( p_access, "invalid server name" );
242         goto exit_error;
243     }
244     if( p_sys->url.i_port <= 0 )
245     {
246         p_sys->url.i_port = 21; /* default port */
247     }
248
249     if( Connect( p_access, p_sys ) < 0 )
250         goto exit_error;
251
252     if( ftp_ReadCommand( p_access, &i_answer, NULL ) == 2 )
253     {
254         char hostaddr[NI_MAXNUMERICHOST];
255         struct sockaddr_storage addr;
256         socklen_t len = sizeof (addr);
257
258         if( getpeername( p_sys->fd_cmd, (struct sockaddr *)&addr, &len ) )
259         {
260             msg_Err( p_access, "getpeername failed" );
261             goto exit_error;
262         }
263
264         i_answer = vlc_getnameinfo( (struct sockaddr *)&addr, len, hostaddr,
265                                     sizeof( hostaddr ), NULL, NI_NUMERICHOST );
266         if( i_answer )
267         {
268             msg_Err( p_access, "getnameinfo failed: %s",
269                      vlc_gai_strerror( i_answer ) );
270             goto exit_error;
271         }
272         p_sys->psz_epsv_ip = strdup( hostaddr );
273         if( p_sys->psz_epsv_ip == NULL )
274             goto exit_error;
275     }
276     else
277     {
278         /* If ESPV ALL fails, we fallback to PASV.
279          * We have to restart the connection in case there is a NAT that
280          * understands EPSV ALL in the way, and hence won't allow PASV on
281          * the initial connection.
282          */
283         net_Close( p_sys->fd_cmd );
284         p_sys->fd_cmd = -1;
285
286         if( ( p_sys->fd_cmd = Connect( p_access, p_sys ) ) < 0 )
287            goto exit_error;
288
289         msg_Info( p_access, "FTP Extended passive mode disabled" );
290     }
291     
292     /* binary mode */
293     if( ftp_SendCommand( p_access, "TYPE I" ) < 0 ||
294         ftp_ReadCommand( p_access, &i_answer, NULL ) != 2 )
295     {
296         msg_Err( p_access, "cannot set binary transfer mode" );
297         goto exit_error;
298     }
299
300     /* get size */
301     if( ftp_SendCommand( p_access, "SIZE %s", p_sys->url.psz_path ) < 0 ||
302         ftp_ReadCommand( p_access, &i_answer, &psz_arg ) != 2 )
303     {
304         msg_Err( p_access, "cannot get file size" );
305         goto exit_error;
306     }
307     p_access->info.i_size = atoll( &psz_arg[4] );
308     free( psz_arg );
309     msg_Dbg( p_access, "file size: "I64Fd, p_access->info.i_size );
310
311     /* Start the 'stream' */
312     if( ftp_StartStream( p_access, 0 ) < 0 )
313     {
314         msg_Err( p_access, "cannot retrieve file" );
315         goto exit_error;
316     }
317
318     /* Update default_pts to a suitable value for ftp access */
319     var_Create( p_access, "ftp-caching", VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
320
321     return VLC_SUCCESS;
322
323 exit_error:
324     if( p_sys->fd_cmd >= 0 )
325         net_Close( p_sys->fd_cmd );
326     vlc_UrlClean( &p_sys->url );
327     free( p_sys );
328     return VLC_EGENERIC;
329 }
330
331 /*****************************************************************************
332  * Close: free unused data structures
333  *****************************************************************************/
334 static void Close( vlc_object_t *p_this )
335 {
336     access_t      *p_access = (access_t*)p_this;
337     access_sys_t  *p_sys = p_access->p_sys;
338
339     msg_Dbg( p_access, "stopping stream" );
340     ftp_StopStream( p_access );
341
342     if( ftp_SendCommand( p_access, "QUIT" ) < 0 )
343     {
344         msg_Warn( p_access, "cannot quit" );
345     }
346     else
347     {
348         ftp_ReadCommand( p_access, NULL, NULL );
349     }
350     net_Close( p_sys->fd_cmd );
351     if( p_sys->psz_epsv_ip != NULL )
352         free( p_sys->psz_epsv_ip );
353
354     /* free memory */
355     vlc_UrlClean( &p_sys->url );
356     free( p_sys );
357 }
358
359 /*****************************************************************************
360  * Seek: try to go at the right place
361  *****************************************************************************/
362 static int Seek( access_t *p_access, int64_t i_pos )
363 {
364     if( i_pos < 0 )
365     {
366         return VLC_EGENERIC;
367     }
368     msg_Dbg( p_access, "seeking to "I64Fd, i_pos );
369
370     ftp_StopStream( p_access );
371     if( ftp_StartStream( p_access, i_pos ) < 0 )
372     {
373         p_access->info.b_eof = VLC_TRUE;
374         return VLC_EGENERIC;
375     }
376
377     p_access->info.b_eof = VLC_FALSE;
378     p_access->info.i_pos = i_pos;
379
380     return VLC_SUCCESS;
381 }
382
383 /*****************************************************************************
384  * Read:
385  *****************************************************************************/
386 static int Read( access_t *p_access, uint8_t *p_buffer, int i_len )
387 {
388     access_sys_t *p_sys = p_access->p_sys;
389     int i_read;
390
391     if( p_access->info.b_eof )
392         return 0;
393
394     i_read = net_Read( p_access, p_sys->fd_data, NULL, p_buffer, i_len,
395                        VLC_FALSE );
396     if( i_read == 0 )
397         p_access->info.b_eof = VLC_TRUE;
398     else if( i_read > 0 )
399         p_access->info.i_pos += i_read;
400
401     return i_read;
402 }
403
404 /*****************************************************************************
405  * Control:
406  *****************************************************************************/
407 static int Control( access_t *p_access, int i_query, va_list args )
408 {
409     vlc_bool_t   *pb_bool;
410     int          *pi_int;
411     int64_t      *pi_64;
412     vlc_value_t  val;
413
414     switch( i_query )
415     {
416         /* */
417         case ACCESS_CAN_SEEK:
418             pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t* );
419             *pb_bool = VLC_TRUE;
420             break;
421         case ACCESS_CAN_FASTSEEK:
422             pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t* );
423             *pb_bool = VLC_FALSE;
424             break;
425         case ACCESS_CAN_PAUSE:
426             pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t* );
427             *pb_bool = VLC_TRUE;    /* FIXME */
428             break;
429         case ACCESS_CAN_CONTROL_PACE:
430             pb_bool = (vlc_bool_t*)va_arg( args, vlc_bool_t* );
431             *pb_bool = VLC_TRUE;    /* FIXME */
432             break;
433
434         /* */
435         case ACCESS_GET_MTU:
436             pi_int = (int*)va_arg( args, int * );
437             *pi_int = 0;
438             break;
439
440         case ACCESS_GET_PTS_DELAY:
441             pi_64 = (int64_t*)va_arg( args, int64_t * );
442             var_Get( p_access, "ftp-caching", &val );
443             *pi_64 = (int64_t)var_GetInteger( p_access, "ftp-caching" ) * I64C(1000);
444             break;
445
446         /* */
447         case ACCESS_SET_PAUSE_STATE:
448             /* Nothing to do */
449             break;
450
451         case ACCESS_GET_TITLE_INFO:
452         case ACCESS_SET_TITLE:
453         case ACCESS_SET_SEEKPOINT:
454         case ACCESS_SET_PRIVATE_ID_STATE:
455             return VLC_EGENERIC;
456
457         default:
458             msg_Warn( p_access, "unimplemented query in control" );
459             return VLC_EGENERIC;
460
461     }
462     return VLC_SUCCESS;
463 }
464
465 /*****************************************************************************
466  * ftp_*:
467  *****************************************************************************/
468 static int ftp_SendCommand( access_t *p_access, char *psz_fmt, ... )
469 {
470     access_sys_t *p_sys = p_access->p_sys;
471     va_list      args;
472     char         *psz_cmd;
473
474     va_start( args, psz_fmt );
475     vasprintf( &psz_cmd, psz_fmt, args );
476     va_end( args );
477
478     msg_Dbg( p_access, "ftp_SendCommand:\"%s\"", psz_cmd);
479     if( net_Printf( VLC_OBJECT(p_access), p_sys->fd_cmd, NULL, "%s\r\n",
480                     psz_cmd ) < 0 )
481     {
482         msg_Err( p_access, "failed to send command" );
483         return VLC_EGENERIC;
484     }
485     return VLC_SUCCESS;
486 }
487
488 /* TODO support this s**t :
489  RFC 959 allows the client to send certain TELNET strings at any moment,
490  even in the middle of a request:
491
492  * \377\377.
493  * \377\376x where x is one byte.
494  * \377\375x where x is one byte. The server is obliged to send \377\374x
495  *                                immediately after reading x.
496  * \377\374x where x is one byte.
497  * \377\373x where x is one byte. The server is obliged to send \377\376x
498  *                                immediately after reading x.
499  * \377x for any other byte x.
500
501  These strings are not part of the requests, except in the case \377\377,
502  where the request contains one \377. */
503 static int ftp_ReadCommand( access_t *p_access,
504                             int *pi_answer, char **ppsz_answer )
505 {
506     access_sys_t *p_sys = p_access->p_sys;
507     char         *psz_line;
508     int          i_answer;
509
510     psz_line = net_Gets( p_access, p_sys->fd_cmd, NULL );
511     msg_Dbg( p_access, "answer=%s", psz_line );
512     if( psz_line == NULL || strlen( psz_line ) < 3 )
513     {
514         msg_Err( p_access, "cannot get answer" );
515         if( psz_line ) free( psz_line );
516         if( pi_answer ) *pi_answer    = 500;
517         if( ppsz_answer ) *ppsz_answer  = NULL;
518         return -1;
519     }
520
521     if( psz_line[3] == '-' )    /* Multiple response */
522     {
523         char end[4];
524
525         memcpy( end, psz_line, 3 );
526         end[3] = ' ';
527
528         for( ;; )
529         {
530             char *psz_tmp = net_Gets( p_access, p_sys->fd_cmd, NULL );
531
532             if( psz_tmp == NULL )   /* Error */
533                 break;
534
535             if( !strncmp( psz_tmp, end, 4 ) )
536             {
537                 free( psz_tmp );
538                 break;
539             }
540             free( psz_tmp );
541         }
542     }
543
544     i_answer = atoi( psz_line );
545
546     if( pi_answer ) *pi_answer = i_answer;
547     if( ppsz_answer )
548     {
549         *ppsz_answer = psz_line;
550     }
551     else
552     {
553         free( psz_line );
554     }
555     return( i_answer / 100 );
556 }
557
558 static int ftp_StartStream( access_t *p_access, off_t i_start )
559 {
560     access_sys_t *p_sys = p_access->p_sys;
561
562     char psz_ipv4[16], *psz_ip;
563     int  i_answer;
564     char *psz_arg, *psz_parser;
565     unsigned  a1, a2, a3, a4, p1, p2;
566     int  i_port;
567
568     if( ( ftp_SendCommand( p_access, p_sys->psz_epsv_ip != NULL
569                                      ? "EPSV" : "PASV" ) < 0 )
570      || ( ftp_ReadCommand( p_access, &i_answer, &psz_arg ) != 2 ) )
571     {
572         msg_Err( p_access, "cannot set passive mode" );
573         return VLC_EGENERIC;
574     }
575
576     psz_parser = strchr( psz_arg, '(' );
577     if( psz_parser == NULL )
578     {
579         free( psz_arg );
580         msg_Err( p_access, "cannot parse passive mode response" );
581         return VLC_EGENERIC;
582     }
583
584     psz_ip = p_sys->psz_epsv_ip;
585     if( psz_ip != NULL )
586     {
587         char psz_fmt[7] = "(|||%u";
588         psz_fmt[1] = psz_fmt[2] = psz_fmt[3] = psz_parser[1];
589
590         if( sscanf( psz_parser, psz_fmt, &i_port ) < 1 )
591         {
592             free( psz_arg );
593             msg_Err( p_access, "cannot parse passive mode response" );
594             return VLC_EGENERIC;
595         }
596     }
597     else
598     {
599         if( ( sscanf( psz_parser, "(%u,%u,%u,%u,%u,%u", &a1, &a2, &a3, &a4,
600                       &p1, &p2 ) < 6 ) || ( a1 > 255 ) || ( a2 > 255 )
601          || ( a3 > 255 ) || ( a4 > 255 ) || ( p1 > 255 ) || ( p2 > 255 ) )
602         {
603             free( psz_arg );
604             msg_Err( p_access, "cannot parse passive mode response" );
605             return VLC_EGENERIC;
606         }
607
608         sprintf( psz_ipv4, "%u.%u.%u.%u", a1, a2, a3, a4 );
609         psz_ip = psz_ipv4;
610         i_port = (p1 << 8) | p2;
611     }
612     free( psz_arg );
613
614     msg_Dbg( p_access, "ip:%s port:%d", psz_ip, i_port );
615
616     if( ftp_SendCommand( p_access, "TYPE I" ) < 0 ||
617         ftp_ReadCommand( p_access, &i_answer, NULL ) != 2 )
618     {
619         msg_Err( p_access, "cannot set binary transfer mode" );
620         return VLC_EGENERIC;
621     }
622
623     if( i_start > 0 )
624     {
625         if( ftp_SendCommand( p_access, "REST "I64Fu, i_start ) < 0 ||
626             ftp_ReadCommand( p_access, &i_answer, NULL ) > 3 )
627         {
628             msg_Err( p_access, "cannot set restart point" );
629             return VLC_EGENERIC;
630         }
631     }
632
633     msg_Dbg( p_access, "waiting for data connection..." );
634     p_sys->fd_data = net_OpenTCP( p_access, psz_ip, i_port );
635     if( p_sys->fd_data < 0 )
636     {
637         msg_Err( p_access, "failed to connect with server" );
638         return VLC_EGENERIC;
639     }
640     msg_Dbg( p_access, "connection with \"%s:%d\" successful",
641              psz_ip, i_port );
642
643     /* "1xx" message */
644     if( ftp_SendCommand( p_access, "RETR %s", p_sys->url.psz_path ) < 0 ||
645         ftp_ReadCommand( p_access, &i_answer, NULL ) > 2 )
646     {
647         msg_Err( p_access, "cannot retreive file" );
648         return VLC_EGENERIC;
649     }
650     return VLC_SUCCESS;
651 }
652
653 static int ftp_StopStream ( access_t *p_access )
654 {
655     access_sys_t *p_sys = p_access->p_sys;
656
657     int i_answer;
658
659     if( ftp_SendCommand( p_access, "ABOR" ) < 0 )
660     {
661         msg_Warn( p_access, "cannot abord file" );
662         if(  p_sys->fd_data > 0 )
663             net_Close( p_sys->fd_data );
664         p_sys->fd_data = -1;
665         return VLC_EGENERIC;
666     }
667     if(  p_sys->fd_data > 0 )
668     {
669         net_Close( p_sys->fd_data );
670         p_sys->fd_data = -1;
671         ftp_ReadCommand( p_access, &i_answer, NULL );
672     }
673     ftp_ReadCommand( p_access, &i_answer, NULL );
674
675     return VLC_SUCCESS;
676 }
677