sftp: check vlc_UrlParseFixup return
[vlc.git] / modules / access / sftp.c
blobf35d9e1b505aca9392f790976ae46a472bfc3537
1 /*****************************************************************************
2 * sftp.c: SFTP input module
3 *****************************************************************************
4 * Copyright (C) 2009 VLC authors and VideoLAN
5 * $Id$
7 * Authors: RĂ©mi Duraffort <ivoire@videolan.org>
8 * Petri Hintukainen <phintuka@gmail.com>
10 * This program is free software; you can redistribute it and/or modify it
11 * under the terms of the GNU Lesser General Public License as published by
12 * the Free Software Foundation; either version 2.1 of the License, or
13 * (at your option) any later version.
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 Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this program; if not, write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23 *****************************************************************************/
25 /*****************************************************************************
26 * Preamble
27 *****************************************************************************/
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
32 #include <vlc_common.h>
33 #include <vlc_plugin.h>
35 #include <assert.h>
37 #include <vlc_access.h>
38 #include <vlc_input_item.h>
39 #include <vlc_network.h>
40 #include <vlc_url.h>
41 #include <vlc_keystore.h>
43 #include <libssh2.h>
44 #include <libssh2_sftp.h>
47 /*****************************************************************************
48 * Module descriptor
49 *****************************************************************************/
50 static int Open ( vlc_object_t* );
51 static void Close( vlc_object_t* );
53 #define PORT_TEXT N_("SFTP port")
54 #define PORT_LONGTEXT N_("SFTP port number to use on the server")
55 #define USER_TEXT N_("Username")
56 #define USER_LONGTEXT N_("Username that will be used for the connection, " \
57 "if no username is set in the URL.")
58 #define PASS_TEXT N_("Password")
59 #define PASS_LONGTEXT N_("Password that will be used for the connection, " \
60 "if no username or password are set in URL.")
62 vlc_module_begin ()
63 set_shortname( "SFTP" )
64 set_description( N_("SFTP input") )
65 set_capability( "access", 0 )
66 set_category( CAT_INPUT )
67 set_subcategory( SUBCAT_INPUT_ACCESS )
68 add_integer( "sftp-port", 22, PORT_TEXT, PORT_LONGTEXT, true )
69 add_string( "sftp-user", NULL, USER_TEXT, USER_LONGTEXT, false )
70 add_password( "sftp-pwd", NULL, PASS_TEXT, PASS_LONGTEXT, false )
71 add_shortcut( "sftp" )
72 set_callbacks( Open, Close )
73 vlc_module_end ()
76 /*****************************************************************************
77 * Local prototypes
78 *****************************************************************************/
79 static ssize_t Read( stream_t *, void *, size_t );
80 static int Seek( stream_t *, uint64_t );
81 static int Control( stream_t *, int, va_list );
83 static int DirRead( stream_t *, input_item_node_t * );
85 struct access_sys_t
87 int i_socket;
88 LIBSSH2_SESSION* ssh_session;
89 LIBSSH2_SFTP* sftp_session;
90 LIBSSH2_SFTP_HANDLE* file;
91 uint64_t filesize;
92 char *psz_base_url;
95 static int AuthKeyAgent( stream_t *p_access, const char *psz_username )
97 access_sys_t* p_sys = p_access->p_sys;
98 int i_result = VLC_EGENERIC;
99 LIBSSH2_AGENT *p_sshagent = NULL;
100 struct libssh2_agent_publickey *p_identity = NULL,
101 *p_prev_identity = NULL;
103 if( !psz_username || !psz_username[0] )
104 return i_result;
106 p_sshagent = libssh2_agent_init( p_sys->ssh_session );
108 if( !p_sshagent )
110 msg_Dbg( p_access, "Failed to initialize key agent" );
111 goto bailout;
113 if( libssh2_agent_connect( p_sshagent ) )
115 msg_Dbg( p_access, "Failed to connect key agent" );
116 goto bailout;
118 if( libssh2_agent_list_identities( p_sshagent ) )
120 msg_Dbg( p_access, "Failed to request identities" );
121 goto bailout;
124 while( libssh2_agent_get_identity( p_sshagent, &p_identity, p_prev_identity ) == 0 )
126 msg_Dbg( p_access, "Using key %s", p_identity->comment );
127 if( libssh2_agent_userauth( p_sshagent, psz_username, p_identity ) == 0 )
129 msg_Info( p_access, "Public key agent authentication succeeded" );
130 i_result = VLC_SUCCESS;
131 goto bailout;
133 msg_Dbg( p_access, "Public key agent authentication failed" );
134 p_prev_identity = p_identity;
137 bailout:
138 if( p_sshagent )
140 libssh2_agent_disconnect( p_sshagent );
141 libssh2_agent_free( p_sshagent );
143 return i_result;
147 static int AuthPublicKey( stream_t *p_access, const char *psz_home, const char *psz_username )
149 access_sys_t* p_sys = p_access->p_sys;
150 int i_result = VLC_EGENERIC;
151 char *psz_keyfile1 = NULL;
152 char *psz_keyfile2 = NULL;
154 if( !psz_username || !psz_username[0] )
155 return i_result;
157 if( asprintf( &psz_keyfile1, "%s/.ssh/id_rsa.pub", psz_home ) == -1 ||
158 asprintf( &psz_keyfile2, "%s/.ssh/id_rsa", psz_home ) == -1 )
159 goto bailout;
161 if( libssh2_userauth_publickey_fromfile( p_sys->ssh_session, psz_username, psz_keyfile1, psz_keyfile2, NULL ) )
163 msg_Dbg( p_access, "Public key authentication failed" );
164 goto bailout;
167 msg_Info( p_access, "Public key authentication succeeded" );
168 i_result = VLC_SUCCESS;
170 bailout:
171 free( psz_keyfile1 );
172 free( psz_keyfile2 );
173 return i_result;
176 static void SSHSessionDestroy( stream_t *p_access )
178 access_sys_t* p_sys = p_access->p_sys;
180 if( p_sys->ssh_session )
182 libssh2_session_free( p_sys->ssh_session );
183 p_sys->ssh_session = NULL;
185 if( p_sys->i_socket >= 0 )
187 net_Close( p_sys->i_socket );
188 p_sys->i_socket = -1;
192 static int SSHSessionInit( stream_t *p_access, const char *psz_host, int i_port )
194 access_sys_t* p_sys = p_access->p_sys;
196 /* Connect to the server using a regular socket */
197 assert( p_sys->i_socket == -1 );
198 p_sys->i_socket = net_ConnectTCP( p_access, psz_host, i_port );
199 if( p_sys->i_socket < 0 )
200 goto error;
202 /* Create the ssh connexion and wait until the server answer */
203 p_sys->ssh_session = libssh2_session_init();
204 if( p_sys->ssh_session == NULL )
205 goto error;
207 int i_ret;
208 while( ( i_ret = libssh2_session_startup( p_sys->ssh_session, p_sys->i_socket ) )
209 == LIBSSH2_ERROR_EAGAIN );
211 if( i_ret != 0 )
212 goto error;
214 /* Set the socket in non-blocking mode */
215 libssh2_session_set_blocking( p_sys->ssh_session, 1 );
216 return VLC_SUCCESS;
218 error:
219 msg_Err( p_access, "Impossible to open the connection to %s:%i",
220 psz_host, i_port );
221 SSHSessionDestroy( p_access );
222 return VLC_EGENERIC;
226 * Connect to the sftp server and ask for a file
227 * @param p_this: the vlc_object
228 * @return VLC_SUCCESS if everything was fine
230 static int Open( vlc_object_t* p_this )
232 stream_t* p_access = (stream_t*)p_this;
233 access_sys_t* p_sys;
234 vlc_credential credential;
235 char* psz_path = NULL;
236 char *psz_session_username = NULL;
237 char* psz_home = NULL;
238 int i_port;
239 vlc_url_t url;
240 size_t i_len;
241 int i_type;
242 int i_result = VLC_EGENERIC;
244 if( !p_access->psz_location )
245 return VLC_EGENERIC;
247 p_sys = p_access->p_sys = vlc_obj_calloc( p_this, 1, sizeof( access_sys_t ) );
248 if( !p_sys ) return VLC_ENOMEM;
250 p_sys->i_socket = -1;
252 /* Parse the URL */
253 if( vlc_UrlParseFixup( &url, p_access->psz_url ) != 0 )
255 vlc_UrlClean( &url );
256 free( p_sys );
257 return VLC_EGENERIC;
259 vlc_credential_init( &credential, &url );
260 if( url.psz_path != NULL )
262 psz_path = vlc_uri_decode_duplicate( url.psz_path );
263 if( psz_path == NULL )
264 goto error;
267 /* Check for some parameters */
268 if( EMPTY_STR( url.psz_host ) )
270 msg_Err( p_access, "Unable to extract host from %s", p_access->psz_url );
271 goto error;
274 if( url.i_port <= 0 )
275 i_port = var_InheritInteger( p_access, "sftp-port" );
276 else
277 i_port = url.i_port;
279 /* Create the ssh connexion and wait until the server answer */
280 if( SSHSessionInit( p_access, url.psz_host, i_port ) != VLC_SUCCESS )
281 goto error;
283 /* List the know hosts */
284 LIBSSH2_KNOWNHOSTS *ssh_knownhosts = libssh2_knownhost_init( p_sys->ssh_session );
285 if( !ssh_knownhosts )
286 goto error;
288 psz_home = config_GetUserDir( VLC_HOME_DIR );
289 char *psz_knownhosts_file;
290 if( asprintf( &psz_knownhosts_file, "%s/.ssh/known_hosts", psz_home ) != -1 )
292 libssh2_knownhost_readfile( ssh_knownhosts, psz_knownhosts_file,
293 LIBSSH2_KNOWNHOST_FILE_OPENSSH );
294 free( psz_knownhosts_file );
297 const char *fingerprint = libssh2_session_hostkey( p_sys->ssh_session, &i_len, &i_type );
298 struct libssh2_knownhost *host;
299 int knownhost_fingerprint_algo;
301 switch( i_type )
303 case LIBSSH2_HOSTKEY_TYPE_RSA:
304 knownhost_fingerprint_algo = LIBSSH2_KNOWNHOST_KEY_SSHRSA;
305 break;
307 case LIBSSH2_HOSTKEY_TYPE_DSS:
308 knownhost_fingerprint_algo = LIBSSH2_KNOWNHOST_KEY_SSHDSS;
309 break;
311 default:
312 msg_Err( p_access, "Host uses unrecognized session-key algorithm" );
313 libssh2_knownhost_free( ssh_knownhosts );
314 goto error;
318 int check = libssh2_knownhost_check( ssh_knownhosts, url.psz_host,
319 fingerprint, i_len,
320 LIBSSH2_KNOWNHOST_TYPE_PLAIN |
321 LIBSSH2_KNOWNHOST_KEYENC_RAW |
322 knownhost_fingerprint_algo,
323 &host );
325 libssh2_knownhost_free( ssh_knownhosts );
327 /* Check that it does match or at least that the host is unknown */
328 switch(check)
330 case LIBSSH2_KNOWNHOST_CHECK_FAILURE:
331 case LIBSSH2_KNOWNHOST_CHECK_NOTFOUND:
332 msg_Dbg( p_access, "Unable to check the remote host" );
333 break;
334 case LIBSSH2_KNOWNHOST_CHECK_MATCH:
335 msg_Dbg( p_access, "Succesfuly matched the host" );
336 break;
337 case LIBSSH2_KNOWNHOST_CHECK_MISMATCH:
338 msg_Err( p_access, "The host does not match !! The remote key changed !!" );
339 goto error;
342 vlc_credential_get( &credential, p_access, "sftp-user", "sftp-pwd",
343 NULL, NULL );
344 char* psz_userauthlist = NULL;
345 bool b_publickey_tried = false;
348 if (!credential.psz_username || !credential.psz_username[0])
349 continue;
351 if( !psz_session_username )
353 psz_session_username = strdup( credential.psz_username );
354 psz_userauthlist =
355 libssh2_userauth_list( p_sys->ssh_session, credential.psz_username,
356 strlen( credential.psz_username ) );
358 else if( strcmp( psz_session_username, credential.psz_username ) != 0 )
360 msg_Warn( p_access, "The username changed, starting a new ssh session" );
362 SSHSessionDestroy( p_access );
363 if( SSHSessionInit( p_access, url.psz_host, i_port ) != VLC_SUCCESS )
364 goto error;
366 b_publickey_tried = false;
367 free( psz_session_username );
368 psz_session_username = strdup( credential.psz_username );
369 psz_userauthlist =
370 libssh2_userauth_list( p_sys->ssh_session, credential.psz_username,
371 strlen( credential.psz_username ) );
373 if( !psz_session_username || !psz_userauthlist )
374 goto error;
376 /* TODO: Follow PreferredAuthentications in ssh_config */
378 if( strstr( psz_userauthlist, "publickey" ) != NULL && !b_publickey_tried )
380 /* Don't try public key multiple times to avoid getting black
381 * listed */
382 b_publickey_tried = true;
383 if( AuthKeyAgent( p_access, credential.psz_username ) == VLC_SUCCESS
384 || AuthPublicKey( p_access, psz_home, credential.psz_username ) == VLC_SUCCESS )
385 break;
388 if( strstr( psz_userauthlist, "password" ) != NULL
389 && credential.psz_password != NULL
390 && libssh2_userauth_password( p_sys->ssh_session,
391 credential.psz_username,
392 credential.psz_password ) == 0 )
394 vlc_credential_store( &credential, p_access );
395 break;
398 msg_Warn( p_access, "sftp auth failed for %s", credential.psz_username );
399 } while( vlc_credential_get( &credential, p_access, "sftp-user", "sftp-pwd",
400 _("SFTP authentication"),
401 _("Please enter a valid login and password for "
402 "the sftp connexion to %s"), url.psz_host ) );
404 /* Create the sftp session */
405 p_sys->sftp_session = libssh2_sftp_init( p_sys->ssh_session );
407 if( !p_sys->sftp_session )
409 msg_Err( p_access, "Unable to initialize the SFTP session" );
410 goto error;
413 /* No path, default to user Home */
414 if( !psz_path )
416 const size_t i_size = 1024;
417 int i_read;
419 char* psz_remote_home = malloc( i_size );
420 if( !psz_remote_home )
421 goto error;
423 i_read = libssh2_sftp_symlink_ex( p_sys->sftp_session, ".", 1,
424 psz_remote_home, i_size - 1,
425 LIBSSH2_SFTP_REALPATH );
426 if( i_read <= 0 )
428 msg_Err( p_access, "Impossible to get the Home directory" );
429 free( psz_remote_home );
430 goto error;
432 psz_remote_home[i_read] = '\0';
433 psz_path = psz_remote_home;
435 /* store base url for directory read */
436 char *base = vlc_path2uri( psz_path, "sftp" );
437 if( !base )
438 goto error;
439 if( -1 == asprintf( &p_sys->psz_base_url, "sftp://%s%s", p_access->psz_location, base + 7 ) )
441 free( base );
442 goto error;
444 free( base );
447 /* Get some information */
448 LIBSSH2_SFTP_ATTRIBUTES attributes;
449 if( libssh2_sftp_stat( p_sys->sftp_session, psz_path, &attributes ) )
451 msg_Err( p_access, "Impossible to get information about the remote path %s", psz_path );
452 goto error;
455 if( !LIBSSH2_SFTP_S_ISDIR( attributes.permissions ))
457 /* Open the given file */
458 p_sys->file = libssh2_sftp_open( p_sys->sftp_session, psz_path, LIBSSH2_FXF_READ, 0 );
459 p_sys->filesize = attributes.filesize;
461 ACCESS_SET_CALLBACKS( Read, NULL, Control, Seek );
463 else
465 /* Open the given directory */
466 p_sys->file = libssh2_sftp_opendir( p_sys->sftp_session, psz_path );
468 p_access->pf_readdir = DirRead;
469 p_access->pf_control = access_vaDirectoryControlHelper;
471 if( !p_sys->psz_base_url )
473 if( asprintf( &p_sys->psz_base_url, "sftp://%s", p_access->psz_location ) == -1 )
474 goto error;
476 /* trim trailing '/' */
477 size_t len = strlen( p_sys->psz_base_url );
478 if( len > 0 && p_sys->psz_base_url[ len - 1 ] == '/' )
479 p_sys->psz_base_url[ len - 1 ] = 0;
483 if( !p_sys->file )
485 msg_Err( p_access, "Unable to open the remote path %s", psz_path );
486 goto error;
489 i_result = VLC_SUCCESS;
491 error:
492 free( psz_home );
493 free( psz_session_username );
494 free( psz_path );
495 vlc_credential_clean( &credential );
496 vlc_UrlClean( &url );
497 if( i_result != VLC_SUCCESS ) {
498 Close( p_this );
500 return i_result;
504 /* Close: quit the module */
505 static void Close( vlc_object_t* p_this )
507 stream_t* p_access = (stream_t*)p_this;
508 access_sys_t* p_sys = p_access->p_sys;
510 if( p_sys->file )
511 libssh2_sftp_close_handle( p_sys->file );
512 if( p_sys->sftp_session )
513 libssh2_sftp_shutdown( p_sys->sftp_session );
514 SSHSessionDestroy( p_access );
516 free( p_sys->psz_base_url );
520 static ssize_t Read( stream_t *p_access, void *buf, size_t len )
522 access_sys_t *p_sys = p_access->p_sys;
524 ssize_t val = libssh2_sftp_read( p_sys->file, buf, len );
525 if( val < 0 )
527 msg_Err( p_access, "read failed" );
528 return 0;
531 return val;
535 static int Seek( stream_t* p_access, uint64_t i_pos )
537 access_sys_t *sys = p_access->p_sys;
539 libssh2_sftp_seek( sys->file, i_pos );
540 return VLC_SUCCESS;
544 static int Control( stream_t* p_access, int i_query, va_list args )
546 access_sys_t *sys = p_access->p_sys;
547 bool* pb_bool;
548 int64_t* pi_64;
550 switch( i_query )
552 case STREAM_CAN_SEEK:
553 pb_bool = va_arg( args, bool * );
554 *pb_bool = true;
555 break;
557 case STREAM_CAN_FASTSEEK:
558 pb_bool = va_arg( args, bool * );
559 *pb_bool = false;
560 break;
562 case STREAM_CAN_PAUSE:
563 case STREAM_CAN_CONTROL_PACE:
564 pb_bool = va_arg( args, bool * );
565 *pb_bool = true;
566 break;
568 case STREAM_GET_SIZE:
569 if( p_access->pf_readdir != NULL )
570 return VLC_EGENERIC;
571 *va_arg( args, uint64_t * ) = sys->filesize;
572 break;
574 case STREAM_GET_PTS_DELAY:
575 pi_64 = va_arg( args, int64_t * );
576 *pi_64 = INT64_C(1000)
577 * var_InheritInteger( p_access, "network-caching" );
578 break;
580 case STREAM_SET_PAUSE_STATE:
581 break;
583 default:
584 return VLC_EGENERIC;
587 return VLC_SUCCESS;
591 /*****************************************************************************
592 * Directory access
593 *****************************************************************************/
595 static int DirRead (stream_t *p_access, input_item_node_t *p_current_node)
597 access_sys_t *p_sys = p_access->p_sys;
598 LIBSSH2_SFTP_ATTRIBUTES attrs;
599 int i_ret = VLC_SUCCESS;
600 int err;
601 /* Allocate 1024 bytes for file name. Longer names are skipped.
602 * libssh2 does not support seeking in directory streams.
603 * Retrying with larger buffer is possible, but would require
604 * re-opening the directory stream.
606 size_t i_size = 1024;
607 char *psz_file = malloc( i_size );
609 if( !psz_file )
610 return VLC_ENOMEM;
612 struct vlc_readdir_helper rdh;
613 vlc_readdir_helper_init( &rdh, p_access, p_current_node );
615 while( i_ret == VLC_SUCCESS
616 && 0 != ( err = libssh2_sftp_readdir( p_sys->file, psz_file, i_size, &attrs ) ) )
618 if( err < 0 )
620 if( err == LIBSSH2_ERROR_BUFFER_TOO_SMALL )
622 /* seeking back is not possible ... */
623 msg_Dbg( p_access, "skipped too long file name" );
624 continue;
626 if( err == LIBSSH2_ERROR_EAGAIN )
628 continue;
630 msg_Err( p_access, "directory read failed" );
631 break;
634 /* Create an input item for the current entry */
636 char *psz_full_uri, *psz_uri;
638 psz_uri = vlc_uri_encode( psz_file );
639 if( psz_uri == NULL )
641 i_ret = VLC_ENOMEM;
642 break;
645 if( asprintf( &psz_full_uri, "%s/%s", p_sys->psz_base_url, psz_uri ) == -1 )
647 free( psz_uri );
648 i_ret = VLC_ENOMEM;
649 break;
651 free( psz_uri );
653 int i_type = LIBSSH2_SFTP_S_ISDIR( attrs.permissions ) ? ITEM_TYPE_DIRECTORY : ITEM_TYPE_FILE;
654 i_ret = vlc_readdir_helper_additem( &rdh, psz_full_uri, NULL, psz_file,
655 i_type, ITEM_NET );
656 free( psz_full_uri );
659 vlc_readdir_helper_finish( &rdh, i_ret == VLC_SUCCESS );
660 free( psz_file );
661 return i_ret;