ftp.c 34.6 KB
Newer Older
1
/*****************************************************************************
Gildas Bazin's avatar
 
Gildas Bazin committed
2
 * ftp.c: FTP input module
3
 *****************************************************************************
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
4
 * Copyright (C) 2001-2006 VLC authors and VideoLAN
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
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
 *
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
11 12 13
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation; either version 2.1 of the License, or
14 15 16 17
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
18 19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
20
 *
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
21 22 23
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24 25 26 27 28
 *****************************************************************************/

/*****************************************************************************
 * Preamble
 *****************************************************************************/
29 30 31 32
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

33
#include <assert.h>
34
#include <stdint.h>
35
#include <errno.h>
36

37 38
#include <vlc_common.h>
#include <vlc_plugin.h>
Clément Stenac's avatar
Clément Stenac committed
39
#include <vlc_access.h>
40
#include <vlc_dialog.h>
Thomas Guillem's avatar
Thomas Guillem committed
41
#include <vlc_input_item.h>
Clément Stenac's avatar
Clément Stenac committed
42
#include <vlc_network.h>
Rémi Duraffort's avatar
Rémi Duraffort committed
43
#include <vlc_url.h>
44
#include <vlc_tls.h>
Clément Stenac's avatar
Clément Stenac committed
45
#include <vlc_sout.h>
46
#include <vlc_charset.h>
47
#include <vlc_interrupt.h>
Thomas Guillem's avatar
Thomas Guillem committed
48
#include <vlc_keystore.h>
49

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
50 51 52 53
#ifndef IPPORT_FTP
# define IPPORT_FTP 21u
#endif

54 55 56 57
#ifndef IPPORT_FTPS
# define IPPORT_FTPS 990u
#endif

58
/*****************************************************************************
59
 * Module descriptor
60
 *****************************************************************************/
61 62
static int   InOpen ( vlc_object_t * );
static void  InClose( vlc_object_t * );
63
#ifdef ENABLE_SOUT
64 65
static int  OutOpen ( vlc_object_t * );
static void OutClose( vlc_object_t * );
66
#endif
67

68 69 70 71 72 73
#define USER_TEXT N_("Username")
#define USER_LONGTEXT N_("Username that will be used for the connection, " \
        "if no username is set in the URL.")
#define PASS_TEXT N_("Password")
#define PASS_LONGTEXT N_("Password that will be used for the connection, " \
        "if no username or password are set in URL.")
Gildas Bazin's avatar
 
Gildas Bazin committed
74
#define ACCOUNT_TEXT N_("FTP account")
Clément Stenac's avatar
Clément Stenac committed
75
#define ACCOUNT_LONGTEXT N_("Account that will be " \
Gildas Bazin's avatar
 
Gildas Bazin committed
76
    "used for the connection.")
77

Thomas Guillem's avatar
Thomas Guillem committed
78 79 80 81
#define LOGIN_DIALOG_TITLE _("FTP authentication")
#define LOGIN_DIALOG_TEXT _("Please enter a valid login and password for " \
        "the ftp connexion to %s")

82 83 84 85 86 87
vlc_module_begin ()
    set_shortname( "FTP" )
    set_description( N_("FTP input") )
    set_capability( "access", 0 )
    set_category( CAT_INPUT )
    set_subcategory( SUBCAT_INPUT_ACCESS )
88
    add_string( "ftp-user", "anonymous", USER_TEXT, USER_LONGTEXT,
Rémi Duraffort's avatar
Rémi Duraffort committed
89
                false )
90
    add_string( "ftp-pwd", "anonymous@example.com", PASS_TEXT,
91
                PASS_LONGTEXT, false )
92
    add_string( "ftp-account", "anonymous", ACCOUNT_TEXT,
Rémi Duraffort's avatar
Rémi Duraffort committed
93
                ACCOUNT_LONGTEXT, false )
94
    add_shortcut( "ftp", "ftps", "ftpes" )
95
    set_callbacks( InOpen, InClose )
96

97
#ifdef ENABLE_SOUT
98
    add_submodule ()
Rémi Duraffort's avatar
Rémi Duraffort committed
99 100 101 102 103
        set_shortname( "FTP" )
        set_description( N_("FTP upload output") )
        set_capability( "sout access", 0 )
        set_category( CAT_SOUT )
        set_subcategory( SUBCAT_SOUT_ACO )
104
        add_shortcut( "ftp", "ftps", "ftpes" )
Rémi Duraffort's avatar
Rémi Duraffort committed
105
        set_callbacks( OutOpen, OutClose )
106
#endif
107
vlc_module_end ()
108

109 110 111
/*****************************************************************************
 * Local prototypes
 *****************************************************************************/
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
112 113 114 115
static ssize_t Read( stream_t *, void *, size_t );
static int Seek( stream_t *, uint64_t );
static int Control( stream_t *, int, va_list );
static int DirRead( stream_t *, input_item_node_t * );
116 117 118 119
#ifdef ENABLE_SOUT
static int OutSeek( sout_access_out_t *, off_t );
static ssize_t Write( sout_access_out_t *, block_t * );
#endif
120

121
static int LoginUserPwd( vlc_object_t *, access_sys_t *,
Thomas Guillem's avatar
Thomas Guillem committed
122
                         const char *, const char *, bool * );
123 124 125 126 127 128
static void FeaturesCheck( void *, const char * );

typedef struct ftp_features_t
{
    bool b_unicode;
    bool b_authtls;
129
    bool b_mlst;
130 131 132 133 134 135 136 137 138
} ftp_features_t;

enum tls_mode_e
{
    NONE = 0,
    IMPLICIT,/* ftps */
    EXPLICIT /* ftpes */
};

139
struct access_sys_t
140
{
141
    vlc_url_t  url;
142

143 144 145
    ftp_features_t   features;
    vlc_tls_creds_t *p_creds;
    enum tls_mode_e  tlsmode;
146 147
    vlc_tls_t *cmd;
    vlc_tls_t *data;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
148

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
149
    char       sz_epsv_ip[NI_MAXNUMERICHOST];
150
    bool       out;
151
    uint64_t   offset;
152
    uint64_t   size;
153
};
154 155
#define GET_OUT_SYS( p_this ) \
    ((access_sys_t *)(((sout_access_out_t *)(p_this))->p_sys))
156

157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
static int ftp_SendCommand( vlc_object_t *obj, access_sys_t *sys,
                            const char *fmt, ... )
{
    size_t fmtlen = strlen( fmt );
    char fmtbuf[fmtlen + 3];

    memcpy( fmtbuf, fmt, fmtlen );
    memcpy( fmtbuf + fmtlen, "\r\n", 3 );

    va_list args;
    char *cmd;
    int val;

    va_start( args, fmt );
    val = vasprintf( &cmd, fmtbuf, args );
    va_end( args );
    if( unlikely(val == -1) )
        return -1;

176 177 178 179 180
    if( strncmp( cmd, "PASS ", 5 ) && strncmp( cmd, "ACCT ", 5 ) )
        msg_Dbg( obj, "sending request: \"%.*s\" (%d bytes)", val-2, cmd, val );
    else
        msg_Dbg( obj, "sending request: \"%.*s XXXX\" (XX bytes)", 4, cmd );

181
    if( vlc_tls_Write( sys->cmd, cmd, val ) != val )
182 183 184 185 186 187 188 189 190 191
    {
        msg_Err( obj, "request failure" );
        val = -1;
    }
    else
        val = 0;
    free( cmd );
    return val;
}

192 193
static char *ftp_GetLine( vlc_object_t *obj, access_sys_t *sys )
{
194
    char *resp = vlc_tls_GetLine( sys->cmd );
195 196 197 198 199
    if( resp == NULL )
        msg_Err( obj, "response failure" );
    return resp;
}

200 201 202 203 204 205 206 207 208 209 210 211 212 213 214
/* TODO support this s**t :
 RFC 959 allows the client to send certain TELNET strings at any moment,
 even in the middle of a request:

 * \377\377.
 * \377\376x where x is one byte.
 * \377\375x where x is one byte. The server is obliged to send \377\374x
 *                                immediately after reading x.
 * \377\374x where x is one byte.
 * \377\373x where x is one byte. The server is obliged to send \377\376x
 *                                immediately after reading x.
 * \377x for any other byte x.

 These strings are not part of the requests, except in the case \377\377,
 where the request contains one \377. */
215 216 217
static int ftp_RecvReply( vlc_object_t *obj, access_sys_t *sys,
                          char **restrict strp,
                          void (*cb)(void *, const char *), void *opaque )
218
{
219
    char *resp = ftp_GetLine( obj, sys );
220
    if( resp == NULL )
221
        return -1;
222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238

    char *end;
    unsigned code = strtoul( resp, &end, 10 );
    if( (end - resp) != 3 || (*end != '-' && *end != ' ') )
    {
        msg_Err( obj, "malformatted response" );
        goto error;
    }
    msg_Dbg( obj, "received response: \"%s\"", resp );

    if( *end == '-' ) /* Multi-line response */
    {
        bool done;

        *end = ' ';
        do
        {
239
            char *line = ftp_GetLine( obj, sys );
240 241 242 243
            if( line == NULL )
                goto error;

            done = !strncmp( resp, line, 4 );
244 245
            if( !done )
                cb( opaque, line );
246 247 248 249 250 251 252 253 254
            free( line );
        }
        while( !done );
    }

    if( strp != NULL )
        *strp = resp;
    else
        free( resp );
255
    return code;
256 257 258 259 260
error:
    free( resp );
    return -1;
}

261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
static int ftp_RecvAnswer( vlc_object_t *obj, access_sys_t *sys,
                           int *restrict codep, char **restrict strp,
                           void (*cb)(void *, const char *), void *opaque )
{
    char *str;
    int val = ftp_RecvReply( obj, sys, &str, cb, opaque );
    if( (val / 100) == 1 )
    {   /* There can be zero or one preliminary reply per command */
        free( str );
        val = ftp_RecvReply( obj, sys, &str, cb, opaque );
    }

    if( val >= 0 )
    {
        if( codep != NULL )
            *codep = val;
        if( strp != NULL )
            *strp = str;
        else
            free( str );
        val /= 100;
    }
    else
    {
        if( codep != NULL )
            *codep = 500;
        if( strp != NULL )
            *strp = NULL;
    }
    return val;
}

293 294 295 296 297 298 299 300 301 302 303
static void DummyLine( void *data, const char *str )
{
    (void) data; (void) str;
}

static int ftp_RecvCommand( vlc_object_t *obj, access_sys_t *sys,
                            int *restrict codep, char **restrict strp )
{
    return ftp_RecvAnswer( obj, sys, codep, strp, DummyLine, NULL );
}

304 305 306 307 308 309 310 311
static int ftp_RecvCommandInit( vlc_object_t *obj, access_sys_t *sys )
{
    int val = ftp_RecvReply( obj, sys, NULL, DummyLine, NULL );
    if( val >= 0 )
        val /= 100;
    return val;
}

Thomas Guillem's avatar
Thomas Guillem committed
312
static int ftp_StartStream( vlc_object_t *, access_sys_t *, uint64_t, bool );
313
static int ftp_StopStream ( vlc_object_t *, access_sys_t * );
314

315 316
static int readTLSMode( vlc_object_t *obj, access_sys_t *p_sys,
                        const char * psz_access )
317 318 319 320 321 322 323
{
    if ( !strncmp( psz_access, "ftps", 4 ) )
        p_sys->tlsmode = IMPLICIT;
    else
    if ( !strncmp( psz_access, "ftpes", 5 ) )
        p_sys->tlsmode = EXPLICIT;
    else
324 325
    {
        p_sys->p_creds = NULL;
326
        p_sys->tlsmode = NONE;
327 328 329 330 331
        return 0;
    }

    p_sys->p_creds = vlc_tls_ClientCreate( obj );
    return (p_sys->p_creds != NULL) ? 0 : -1;
332 333
}

334
static int createCmdTLS( vlc_object_t *p_access, access_sys_t *p_sys,
335 336 337
                         const char *psz_session_name )
{
    /* TLS/SSL handshake */
338 339 340 341 342 343
    vlc_tls_t *secure = vlc_tls_ClientSessionCreate( p_sys->p_creds,
                                                     p_sys->cmd,
                                                     p_sys->url.psz_host,
                                                     psz_session_name,
                                                     NULL, NULL );
    if( secure == NULL )
344 345 346 347
    {
        msg_Err( p_access, "cannot establish FTP/TLS session on command channel" );
        return -1;
    }
348
    p_sys->cmd = secure;
349 350 351
    return 0;
}

352
static void clearCmd( access_sys_t *p_sys )
353
{
354 355 356 357 358
    if( p_sys->cmd != NULL )
    {
        vlc_tls_Close( p_sys->cmd );
        p_sys->cmd = NULL;
    }
359 360
}

361
static int Login( vlc_object_t *p_access, access_sys_t *p_sys )
362
{
363
    int i_answer;
364

365
    /* *** Open a TCP connection with server *** */
366 367 368
    p_sys->cmd = vlc_tls_SocketOpenTCP( p_access, p_sys->url.psz_host,
                                        p_sys->url.i_port );
    if( p_sys->cmd == NULL )
369
    {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
370
        msg_Err( p_access, "connection failed" );
Thomas Guillem's avatar
Thomas Guillem committed
371 372
        vlc_dialog_display_error( p_access, _("Network interaction failed"), "%s",
            _("VLC could not connect with the given server.") );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
373
        goto error;
374
    }
Laurent Aimar's avatar
Laurent Aimar committed
375

376 377
    if ( p_sys->tlsmode == IMPLICIT ) /* FTPS Mode */
    {
378
        if ( createCmdTLS( p_access, p_sys, "ftps") < 0 )
379 380 381
            goto error;
    }

382
    while( ftp_RecvCommand( p_access, p_sys, &i_answer, NULL ) == 1 );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
383

384 385
    if( i_answer / 100 != 2 )
    {
Laurent Aimar's avatar
Laurent Aimar committed
386
        msg_Err( p_access, "connection rejected" );
Thomas Guillem's avatar
Thomas Guillem committed
387 388
        vlc_dialog_display_error( p_access, _("Network interaction failed"), "%s",
            _("VLC's connection to the given server was rejected.") );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
389
        goto error;
390 391
    }

Laurent Aimar's avatar
Laurent Aimar committed
392
    msg_Dbg( p_access, "connection accepted (%d)", i_answer );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
393

394 395 396 397 398 399
    /* Features check first */
    if( ftp_SendCommand( p_access, p_sys, "FEAT" ) < 0
     || ftp_RecvAnswer( p_access, p_sys, NULL, NULL,
                        FeaturesCheck, &p_sys->features ) < 0 )
    {
         msg_Err( p_access, "cannot get server features" );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
400
         goto error;
401 402 403 404 405 406 407 408
    }

    /* Create TLS Session */
    if( p_sys->tlsmode == EXPLICIT )
    {
        if ( ! p_sys->features.b_authtls )
        {
            msg_Err( p_access, "Server does not support TLS" );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
409
            goto error;
410 411 412 413 414 415 416 417
        }

        if( ftp_SendCommand( p_access, p_sys, "AUTH TLS" ) < 0
         || ftp_RecvCommand( p_access, p_sys, &i_answer, NULL ) < 0
         || i_answer != 234 )
        {
             msg_Err( p_access, "cannot switch to TLS: server replied with code %d",
                      i_answer );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
418
             goto error;
419 420
        }

421
        if( createCmdTLS( p_access, p_sys, "ftpes") < 0 )
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
        {
            goto error;
        }
    }

    if( p_sys->tlsmode != NONE )
    {
        if( ftp_SendCommand( p_access, p_sys, "PBSZ 0" ) < 0 ||
            ftp_RecvCommand( p_access, p_sys, &i_answer, NULL ) < 0 ||
            i_answer != 200 )
        {
            msg_Err( p_access, "Can't truncate Protection buffer size for TLS" );
            goto error;
        }

        if( ftp_SendCommand( p_access, p_sys, "PROT P" ) < 0 ||
            ftp_RecvCommand( p_access, p_sys, &i_answer, NULL ) < 0 ||
            i_answer != 200 )
        {
            msg_Err( p_access, "Can't set Data channel protection" );
            goto error;
        }
    }

Thomas Guillem's avatar
Thomas Guillem committed
446 447
    vlc_url_t url;
    vlc_credential credential;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
448
    vlc_UrlParse( &url, ((stream_t *)p_access)->psz_url );
Thomas Guillem's avatar
Thomas Guillem committed
449 450 451 452 453 454 455 456 457 458
    vlc_credential_init( &credential, &url );
    bool b_logged = false;

    while( vlc_credential_get( &credential, p_access, "ftp-user", "ftp-pwd",
                               LOGIN_DIALOG_TITLE, LOGIN_DIALOG_TEXT,
                               url.psz_host )
        && LoginUserPwd( p_access, p_sys, credential.psz_username,
                         credential.psz_password, &b_logged ) == 0
        && !b_logged );
    if( b_logged )
459
    {
460
        vlc_credential_store( &credential, p_access );
Thomas Guillem's avatar
Thomas Guillem committed
461 462
        vlc_credential_clean( &credential );
        vlc_UrlClean( &url );
463 464
        return 0;
    }
Thomas Guillem's avatar
Thomas Guillem committed
465 466
    vlc_credential_clean( &credential );
    vlc_UrlClean( &url );
467
error:
468
    clearCmd( p_sys );
469 470 471 472
    return -1;
}

static int LoginUserPwd( vlc_object_t *p_access, access_sys_t *p_sys,
Thomas Guillem's avatar
Thomas Guillem committed
473 474
                         const char *psz_user, const char *psz_pwd,
                         bool *p_logged )
475 476 477 478 479 480 481
{
    int i_answer;

    /* Send credentials over channel */
    if( ftp_SendCommand( p_access, p_sys, "USER %s", psz_user ) < 0 ||
        ftp_RecvCommand( p_access, p_sys, &i_answer, NULL ) < 0 )
        return -1;
482

483 484 485
    switch( i_answer / 100 )
    {
        case 2:
486 487 488 489 490
            /* X.509 auth successful after AUTH TLS / RFC 2228 sec. 4 */
            if ( i_answer == 232 )
                msg_Dbg( p_access, "user accepted and authenticated" );
            else
                msg_Dbg( p_access, "user accepted" );
491 492
            break;
        case 3:
Laurent Aimar's avatar
Laurent Aimar committed
493
            msg_Dbg( p_access, "password needed" );
494

495
            if( ftp_SendCommand( p_access, p_sys, "PASS %s", psz_pwd ) < 0 ||
496
                ftp_RecvCommand( p_access, p_sys, &i_answer, NULL ) < 0 )
497
                return -1;
498

499 500 501
            switch( i_answer / 100 )
            {
                case 2:
Laurent Aimar's avatar
Laurent Aimar committed
502
                    msg_Dbg( p_access, "password accepted" );
503 504
                    break;
                case 3:
505 506
                {
                    char *psz;
Laurent Aimar's avatar
Laurent Aimar committed
507
                    msg_Dbg( p_access, "account needed" );
508
                    psz = var_InheritString( p_access, "ftp-account" );
509
                    if( ftp_SendCommand( p_access, p_sys, "ACCT %s",
510
                                         psz ) < 0 ||
511
                        ftp_RecvCommand( p_access, p_sys, &i_answer, NULL ) < 0 )
512
                    {
513
                        free( psz );
514
                        return -1;
515
                    }
516
                    free( psz );
517

518 519
                    if( i_answer / 100 != 2 )
                    {
Laurent Aimar's avatar
Laurent Aimar committed
520
                        msg_Err( p_access, "account rejected" );
Thomas Guillem's avatar
Thomas Guillem committed
521 522 523
                        vlc_dialog_display_error( p_access,
                          _("Network interaction failed"),
                          "%s", _("Your account was rejected.") );
524
                        return -1;
525
                    }
Laurent Aimar's avatar
Laurent Aimar committed
526
                    msg_Dbg( p_access, "account accepted" );
527
                    break;
528
                }
529

530
                default:
Thomas Guillem's avatar
Thomas Guillem committed
531 532 533
                    msg_Warn( p_access, "password rejected" );
                    *p_logged = false;
                    return 0;
534 535 536
            }
            break;
        default:
Thomas Guillem's avatar
Thomas Guillem committed
537 538 539
            msg_Warn( p_access, "user rejected" );
            *p_logged = false;
            return 0;
540 541
    }

Thomas Guillem's avatar
Thomas Guillem committed
542
    *p_logged = true;
543 544 545
    return 0;
}

546 547
static void FeaturesCheck( void *opaque, const char *feature )
{
548
    ftp_features_t *features = opaque;
549 550

    if( strcasestr( feature, "UTF8" ) != NULL )
551 552 553 554
        features->b_unicode = true;
    else
    if( strcasestr( feature, "AUTH TLS" ) != NULL )
        features->b_authtls = true;
555 556 557

    if( strcasestr( feature, "MLST" ) != NULL )
        features->b_mlst = true;
558 559 560 561 562 563 564 565 566 567 568
}

static const char *IsASCII( const char *str )
{
    int8_t c;
    for( const char *p = str; (c = *p) != '\0'; p++ )
        if( c < 0 )
            return NULL;
    return str;
}

569
static int Connect( vlc_object_t *p_access, access_sys_t *p_sys )
570
{
571 572
    if( Login( p_access, p_sys ) < 0 )
        return -1;
573

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
574
    /* Extended passive mode */
575
    if( ftp_SendCommand( p_access, p_sys, "EPSV ALL" ) < 0 )
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
576 577
    {
        msg_Err( p_access, "cannot request extended passive mode" );
578
        goto error;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
579 580
    }

581
    if( ftp_RecvCommand( p_access, p_sys, NULL, NULL ) == 2 )
582
    {
583 584
        int fd = vlc_tls_GetFD(p_sys->cmd);
        if( net_GetPeerAddress( fd, p_sys->sz_epsv_ip, NULL ) )
585
            goto error;
586
    }
587 588 589 590 591 592 593
    else
    {
        /* If ESPV ALL fails, we fallback to PASV.
         * We have to restart the connection in case there is a NAT that
         * understands EPSV ALL in the way, and hence won't allow PASV on
         * the initial connection.
         */
594
        msg_Info( p_access, "FTP Extended passive mode disabled" );
595
        clearCmd( p_sys );
596

Rémi Denis-Courmont's avatar
Oups  
Rémi Denis-Courmont committed
597
        if( Login( p_access, p_sys ) )
598 599 600
            goto error;
    }

601 602
    if( p_sys->url.psz_path &&
        (p_sys->features.b_unicode ? IsUTF8 : IsASCII)(p_sys->url.psz_path) == NULL )
603 604 605
    {
        msg_Err( p_access, "unsupported path: \"%s\"", p_sys->url.psz_path );
        goto error;
606
    }
607

608 609
    /* check binary mode support */
    if( ftp_SendCommand( p_access, p_sys, "TYPE I" ) < 0 ||
610
        ftp_RecvCommand( p_access, p_sys, NULL, NULL ) != 2 )
611
    {
Derk-Jan Hartman's avatar
Derk-Jan Hartman committed
612
        msg_Err( p_access, "cannot set binary transfer mode" );
613
        goto error;
614 615
    }

616
    return 0;
617

618
error:
619
    clearCmd( p_sys );
620
    return -1;
621 622 623
}


624
static int parseURL( vlc_url_t *url, const char *path, enum tls_mode_e mode )
625 626
{
    if( path == NULL )
627
        return VLC_EGENERIC;
628 629 630 631 632

    /* *** Parse URL and get server addr/port and path *** */
    while( *path == '/' )
        path++;

633
    vlc_UrlParse( url, path );
634 635

    if( url->psz_host == NULL || *url->psz_host == '\0' )
636
        return VLC_EGENERIC;
637 638

    if( url->i_port <= 0 )
639 640 641 642 643 644
    {
        if( mode == IMPLICIT )
            url->i_port = IPPORT_FTPS;
        else
            url->i_port = IPPORT_FTP; /* default port */
    }
645

646 647
    if( url->psz_path == NULL )
        return VLC_SUCCESS;
648
    /* FTP URLs are relative to user's default directory (RFC1738 §3.2)
649
    For absolute path use ftp://foo.bar//usr/local/etc/filename */
650
    /* FIXME: we should issue a series of CWD, one per slash */
651 652 653 654 655
    if( url->psz_path )
    {
        assert( url->psz_path[0] == '/' );
        url->psz_path++;
    }
656 657 658 659 660 661 662 663

    char *type = strstr( url->psz_path, ";type=" );
    if( type )
    {
        *type = '\0';
        if( strchr( "iI", type[6] ) == NULL )
            return VLC_EGENERIC; /* ASCII and directory not supported */
    }
664
    vlc_uri_decode( url->psz_path );
665
    return VLC_SUCCESS;
666 667 668 669 670 671 672 673
}


/****************************************************************************
 * Open: connect to ftp server and ask for file
 ****************************************************************************/
static int InOpen( vlc_object_t *p_this )
{
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
674
    stream_t     *p_access = (stream_t*)p_this;
675 676
    access_sys_t *p_sys;
    char         *psz_arg;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
677
    bool          b_directory;
678 679

    /* Init p_access */
680
    p_sys = p_access->p_sys = (access_sys_t*)vlc_calloc( p_this, 1, sizeof( access_sys_t ) );
Thomas Guillem's avatar
Thomas Guillem committed
681 682
    if( !p_sys )
        return VLC_ENOMEM;
683
    p_sys->data = NULL;
684
    p_sys->out = false;
685
    p_sys->offset = 0;
686
    p_sys->size = UINT64_MAX;
687

688
    if( readTLSMode( p_this, p_sys, p_access->psz_name ) )
689
        goto exit_error;
690

691
    if( parseURL( &p_sys->url, p_access->psz_url, p_sys->tlsmode ) )
692 693 694 695 696
        goto exit_error;

    if( Connect( p_this, p_sys ) )
        goto exit_error;

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730
    do {
        /* get size */
        if( p_sys->url.psz_path == NULL || !*p_sys->url.psz_path )
        {
            b_directory = true;
            break;
        }

        if( ftp_SendCommand( p_this, p_sys, "SIZE %s",
                             p_sys->url.psz_path ) < 0 )
            goto error;

        int val = ftp_RecvCommand( p_this, p_sys, NULL, &psz_arg );
        if( val == 2 )
        {
            b_directory = false;
            p_sys->size = atoll( &psz_arg[4] );
            free( psz_arg );
            msg_Dbg( p_access, "file size: %"PRIu64, p_sys->size );
            break;
        }
        if( val >= 0 )
            free( psz_arg );

        if( ftp_SendCommand( p_this, p_sys, "CWD %s",
                             p_sys->url.psz_path ) < 0 )
            goto error;

        if( ftp_RecvCommand( p_this, p_sys, NULL, NULL ) == 2 )
        {
            b_directory = true;
            break;
        }

731
        msg_Err( p_this, "file or directory does not exist" );
732
        goto error;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
733
    } while (0);
Thomas Guillem's avatar
Thomas Guillem committed
734 735

    if( b_directory )
736
    {
Thomas Guillem's avatar
Thomas Guillem committed
737
        p_access->pf_readdir = DirRead;
738
        p_access->pf_control = access_vaDirectoryControlHelper;
739
    } else
Thomas Guillem's avatar
Thomas Guillem committed
740
        ACCESS_SET_CALLBACKS( Read, NULL, Control, Seek ); \
741

742
    /* Start the 'stream' */
Thomas Guillem's avatar
Thomas Guillem committed
743
    if( ftp_StartStream( p_this, p_sys, 0, b_directory ) < 0 )
744
    {
745
        msg_Err( p_this, "cannot retrieve file" );
746
        goto error;
747 748
    }

749
    return VLC_SUCCESS;
750

751
error:
752
    clearCmd( p_sys );
753

754
exit_error:
755
    vlc_UrlClean( &p_sys->url );
756
    vlc_tls_Delete( p_sys->p_creds );
757
    return VLC_EGENERIC;
758 759
}

760
#ifdef ENABLE_SOUT
761 762 763 764 765
static int OutOpen( vlc_object_t *p_this )
{
    sout_access_out_t *p_access = (sout_access_out_t *)p_this;
    access_sys_t      *p_sys;

766
    p_sys = vlc_calloc( p_this, 1, sizeof( *p_sys ) );
767
    if( !p_sys )
768 769 770
        return VLC_ENOMEM;

    /* Init p_access */
771
    p_sys->data = NULL;
772
    p_sys->out = true;
773 774 775

    if( readTLSMode( p_this, p_sys, p_access->psz_access ) )
        goto exit_error;
776

777
    if( parseURL( &p_sys->url, p_access->psz_path, p_sys->tlsmode ) )
778
        goto exit_error;
779 780 781 782 783
    if( p_sys->url.psz_path == NULL )
    {
        msg_Err( p_this, "no filename specified" );
        goto exit_error;
    }
784 785 786 787 788

    if( Connect( p_this, p_sys ) )
        goto exit_error;

    /* Start the 'stream' */
Thomas Guillem's avatar
Thomas Guillem committed
789
    if( ftp_StartStream( p_this, p_sys, 0, false ) < 0 )
790 791
    {
        msg_Err( p_access, "cannot store file" );
792
        clearCmd( p_sys );
793 794 795 796 797
        goto exit_error;
    }

    p_access->pf_seek = OutSeek;
    p_access->pf_write = Write;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
798
    p_access->p_sys = (void *)p_sys;
799 800 801 802

    return VLC_SUCCESS;

exit_error:
Rémi Denis-Courmont's avatar
Oups  
Rémi Denis-Courmont committed
803
    vlc_UrlClean( &p_sys->url );
804
    vlc_tls_Delete( p_sys->p_creds );
805 806
    return VLC_EGENERIC;
}
807
#endif
808

809 810 811
/*****************************************************************************
 * Close: free unused data structures
 *****************************************************************************/
812
static void Close( vlc_object_t *p_access, access_sys_t *p_sys )
813
{
Laurent Aimar's avatar
Laurent Aimar committed
814
    msg_Dbg( p_access, "stopping stream" );
815
    ftp_StopStream( p_access, p_sys );
816

817
    if( ftp_SendCommand( p_access, p_sys, "QUIT" ) < 0 )
818
    {
Laurent Aimar's avatar
Laurent Aimar committed
819
        msg_Warn( p_access, "cannot quit" );
820 821 822
    }
    else
    {
823
        ftp_RecvCommand( p_access, p_sys, NULL, NULL );
824
    }
825

826
    clearCmd( p_sys );
827 828

    /* free memory */
829
    vlc_UrlClean( &p_sys->url );
830
    vlc_tls_Delete( p_sys->p_creds );
831 832
}

833 834
static void InClose( vlc_object_t *p_this )
{
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
835
    Close( p_this, ((stream_t *)p_this)->p_sys);
836 837
}

838
#ifdef ENABLE_SOUT
839 840 841 842
static void OutClose( vlc_object_t *p_this )
{
    Close( p_this, GET_OUT_SYS(p_this));
}
843
#endif
844 845


846 847 848
/*****************************************************************************
 * Seek: try to go at the right place
 *****************************************************************************/
849 850
static int SeekCommon( vlc_object_t *p_access, access_sys_t *p_sys,
                       uint64_t i_pos )
851
{
852
    msg_Dbg( p_access, "seeking to %"PRIu64, i_pos );
853

854
    ftp_StopStream( p_access, p_sys );
855

856 857
    if( ftp_StartStream( p_access, p_sys, i_pos, false ) < 0 )
        return VLC_EGENERIC;
858 859 860
    return VLC_SUCCESS;
}

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
861
static int Seek( stream_t *p_access, uint64_t i_pos )
862
{
863 864
    access_sys_t *p_sys = p_access->p_sys;

865
    int val = SeekCommon( (vlc_object_t *)p_access, p_sys, i_pos );
866 867
    if( val )
        return val;
868

869
    p_sys->offset = i_pos;
870

Laurent Aimar's avatar
Laurent Aimar committed
871
    return VLC_SUCCESS;
872 873
}

874
#ifdef ENABLE_SOUT
875 876
static int OutSeek( sout_access_out_t *p_access, off_t i_pos )
{
877
    return SeekCommon((vlc_object_t *)p_access, GET_OUT_SYS(p_access), i_pos);
878
}
879
#endif
880

881 882 883
/*****************************************************************************
 * Read:
 *****************************************************************************/
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
884
static ssize_t Read( stream_t *p_access, void *p_buffer, size_t i_len )
885
{
Laurent Aimar's avatar
Laurent Aimar committed
886 887
    access_sys_t *p_sys = p_access->p_sys;

888
    assert( p_sys->data != NULL );
889
    assert( !p_sys->out );
890

891
    ssize_t i_read = vlc_tls_Read( p_sys->data, p_buffer, i_len, false );
892
    if( i_read >= 0 )
893
        p_sys->offset += i_read;
894 895 896
    else if( errno != EINTR && errno != EAGAIN )
    {
        msg_Err( p_access, "receive error: %s", vlc_strerror_c(errno) );
897
        i_read = 0;
898
    }
Thomas Guillem's avatar
Thomas Guillem committed
899 900