1 /*****************************************************************************
2 * raop.c: Remote Audio Output Protocol streaming support
3 *****************************************************************************
4 * Copyright (C) 2008 the VideoLAN team
7 * Author: Michael Hanselmann
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22 *****************************************************************************/
24 /*****************************************************************************
26 *****************************************************************************/
35 #include <vlc_common.h>
36 #include <vlc_plugin.h>
38 #include <vlc_block.h>
39 #include <vlc_network.h>
40 #include <vlc_strings.h>
41 #include <vlc_charset.h>
42 #include <vlc_gcrypt.h>
45 #include <vlc_memory.h>
47 #define RAOP_PORT 5000
48 #define RAOP_USER_AGENT "VLC " VERSION
51 static const char ps_raop_rsa_pubkey[] =
52 "\xe7\xd7\x44\xf2\xa2\xe2\x78\x8b\x6c\x1f\x55\xa0\x8e\xb7\x05\x44"
53 "\xa8\xfa\x79\x45\xaa\x8b\xe6\xc6\x2c\xe5\xf5\x1c\xbd\xd4\xdc\x68"
54 "\x42\xfe\x3d\x10\x83\xdd\x2e\xde\xc1\xbf\xd4\x25\x2d\xc0\x2e\x6f"
55 "\x39\x8b\xdf\x0e\x61\x48\xea\x84\x85\x5e\x2e\x44\x2d\xa6\xd6\x26"
56 "\x64\xf6\x74\xa1\xf3\x04\x92\x9a\xde\x4f\x68\x93\xef\x2d\xf6\xe7"
57 "\x11\xa8\xc7\x7a\x0d\x91\xc9\xd9\x80\x82\x2e\x50\xd1\x29\x22\xaf"
58 "\xea\x40\xea\x9f\x0e\x14\xc0\xf7\x69\x38\xc5\xf3\x88\x2f\xc0\x32"
59 "\x3d\xd9\xfe\x55\x15\x5f\x51\xbb\x59\x21\xc2\x01\x62\x9f\xd7\x33"
60 "\x52\xd5\xe2\xef\xaa\xbf\x9b\xa0\x48\xd7\xb8\x13\xa2\xb6\x76\x7f"
61 "\x6c\x3c\xcf\x1e\xb4\xce\x67\x3d\x03\x7b\x0d\x2e\xa3\x0c\x5f\xff"
62 "\xeb\x06\xf8\xd0\x8a\xdd\xe4\x09\x57\x1a\x9c\x68\x9f\xef\x10\x72"
63 "\x88\x55\xdd\x8c\xfb\x9a\x8b\xef\x5c\x89\x43\xef\x3b\x5f\xaa\x15"
64 "\xdd\xe6\x98\xbe\xdd\xf3\x59\x96\x03\xeb\x3e\x6f\x61\x37\x2b\xb6"
65 "\x28\xf6\x55\x9f\x59\x9a\x78\xbf\x50\x06\x87\xaa\x7f\x49\x76\xc0"
66 "\x56\x2d\x41\x29\x56\xf8\x98\x9e\x18\xa6\x35\x5b\xd8\x15\x97\x82"
67 "\x5e\x0f\xc8\x75\x34\x3e\xc7\x82\x11\x76\x25\xcd\xbf\x98\x44\x7b";
69 static const char ps_raop_rsa_exp[] = "\x01\x00\x01";
71 static const char psz_delim_space[] = " ";
72 static const char psz_delim_colon[] = ":";
73 static const char psz_delim_equal[] = "=";
74 static const char psz_delim_semicolon[] = ";";
77 /*****************************************************************************
79 *****************************************************************************/
80 static int Open( vlc_object_t * );
81 static void Close( vlc_object_t * );
83 static sout_stream_id_t *Add( sout_stream_t *, es_format_t * );
84 static int Del( sout_stream_t *, sout_stream_id_t * );
85 static int Send( sout_stream_t *, sout_stream_id_t *, block_t* );
87 static int VolumeCallback( vlc_object_t *p_this, char const *psz_cmd,
88 vlc_value_t oldval, vlc_value_t newval,
98 struct sout_stream_sys_t
100 /* Input parameters */
106 sout_stream_id_t *p_audio_stream;
108 bool b_volume_callback;
110 /* Connection state */
114 uint8_t ps_aes_key[16];
115 uint8_t ps_aes_iv[16];
116 gcry_cipher_hd_t aes_ctx;
119 char *psz_client_instance;
121 char *psz_last_status_line;
131 size_t i_sendbuf_len;
135 struct sout_stream_id_t
141 /*****************************************************************************
143 *****************************************************************************/
144 #define SOUT_CFG_PREFIX "sout-raop-"
146 #define HOST_TEXT N_("Host")
147 #define HOST_LONGTEXT N_("Hostname or IP address of target device")
149 #define VOLUME_TEXT N_("Volume")
150 #define VOLUME_LONGTEXT N_("Output volume for analog output: 0 for silence, " \
151 "1..255 from almost silent to very loud.")
153 #define PASSWORD_TEXT N_("Password")
154 #define PASSWORD_LONGTEXT N_("Password for target device.")
156 #define PASSWORD_FILE_TEXT N_("Password file")
157 #define PASSWORD_FILE_LONGTEXT N_("Read password for target device from file.")
160 set_shortname( N_("RAOP") )
161 set_description( N_("Remote Audio Output Protocol stream output") )
162 set_capability( "sout stream", 0 )
163 add_shortcut( "raop" )
164 set_category( CAT_SOUT )
165 set_subcategory( SUBCAT_SOUT_STREAM )
166 add_string( SOUT_CFG_PREFIX "host", "", NULL,
167 HOST_TEXT, HOST_LONGTEXT, false )
168 add_password( SOUT_CFG_PREFIX "password", NULL, NULL,
169 PASSWORD_TEXT, PASSWORD_LONGTEXT, false )
170 add_file( SOUT_CFG_PREFIX "password-file", NULL, NULL,
171 PASSWORD_FILE_TEXT, PASSWORD_FILE_LONGTEXT, false )
172 add_integer_with_range( SOUT_CFG_PREFIX "volume", 100, 0, 255, NULL,
173 VOLUME_TEXT, VOLUME_LONGTEXT, false )
174 set_callbacks( Open, Close )
177 static const char *const ppsz_sout_options[] = {
186 /*****************************************************************************
188 *****************************************************************************/
189 static void FreeSys( vlc_object_t *p_this, sout_stream_sys_t *p_sys )
191 sout_stream_t *p_stream = (sout_stream_t*)p_this;
193 if ( p_sys->i_control_fd >= 0 )
194 net_Close( p_sys->i_control_fd );
195 if ( p_sys->i_stream_fd >= 0 )
196 net_Close( p_sys->i_stream_fd );
197 if ( p_sys->b_volume_callback )
198 var_DelCallback( p_stream, SOUT_CFG_PREFIX "volume",
199 VolumeCallback, NULL );
201 gcry_cipher_close( p_sys->aes_ctx );
203 free( p_sys->p_sendbuf );
204 free( p_sys->psz_host );
205 free( p_sys->psz_password );
206 free( p_sys->psz_url );
207 free( p_sys->psz_session );
208 free( p_sys->psz_client_instance );
209 free( p_sys->psz_last_status_line );
213 static void FreeId( sout_stream_id_t *id )
218 static void RemoveBase64Padding( char *str )
220 char *ps_pos = strchr( str, '=' );
221 if ( ps_pos != NULL )
225 static int CheckForGcryptErrorWithLine( sout_stream_t *p_stream,
226 gcry_error_t i_gcrypt_err,
227 unsigned int i_line )
229 if ( i_gcrypt_err != GPG_ERR_NO_ERROR )
231 msg_Err( p_stream, "gcrypt error (line %d): %s", i_line,
232 gpg_strerror( i_gcrypt_err ) );
239 /* Wrapper to pass line number for easier debugging */
240 #define CheckForGcryptError( p_this, i_gcrypt_err ) \
241 CheckForGcryptErrorWithLine( p_this, i_gcrypt_err, __LINE__ )
243 /* MGF1 is specified in RFC2437, section 10.2.1. Variables are named after the
246 static int MGF1( vlc_object_t *p_this,
247 unsigned char *mask, size_t l,
248 const unsigned char *Z, const size_t zLen,
251 sout_stream_t *p_stream = (sout_stream_t*)p_this;
252 gcry_error_t i_gcrypt_err;
253 gcry_md_hd_t md_handle = NULL;
255 unsigned char *ps_md;
256 uint32_t counter = 0;
259 int i_err = VLC_SUCCESS;
261 assert( mask != NULL );
264 hLen = gcry_md_get_algo_dlen( Hash );
266 i_gcrypt_err = gcry_md_open( &md_handle, Hash, 0 );
267 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
269 i_err = VLC_EGENERIC;
275 /* 3. For counter from 0 to \lceil{l / hLen}\rceil-1, do the following:
276 * a. Convert counter to an octet string C of length 4 with the
277 * primitive I2OSP: C = I2OSP (counter, 4)
279 C[0] = (counter >> 24) & 0xff;
280 C[1] = (counter >> 16) & 0xff;
281 C[2] = (counter >> 8) & 0xff;
282 C[3] = counter & 0xff;
285 /* b. Concatenate the hash of the seed Z and C to the octet string T:
286 * T = T || Hash (Z || C)
288 gcry_md_reset( md_handle );
289 gcry_md_write( md_handle, Z, zLen );
290 gcry_md_write( md_handle, C, 4 );
291 ps_md = gcry_md_read( md_handle, Hash );
293 /* 4. Output the leading l octets of T as the octet string mask. */
294 i_copylen = __MIN( l, hLen );
295 memcpy( mask, ps_md, i_copylen );
301 gcry_md_close( md_handle );
306 /* EME-OAEP-ENCODE is specified in RFC2437, section 9.1.1.1. Variables are
307 * named after the specification.
309 static int AddOaepPadding( vlc_object_t *p_this,
310 unsigned char *EM, const size_t emLenWithPrefix,
311 const unsigned char *M, const size_t mLen,
312 const unsigned char *P, const size_t pLen )
314 const int Hash = GCRY_MD_SHA1;
315 const unsigned int hLen = gcry_md_get_algo_dlen( Hash );
316 unsigned char *seed = NULL;
317 unsigned char *DB = NULL;
318 unsigned char *dbMask = NULL;
319 unsigned char *seedMask = NULL;
323 int i_err = VLC_SUCCESS;
325 /* Space for 0x00 prefix in EM. */
326 emLen = emLenWithPrefix - 1;
329 * If ||M|| > emLen-2hLen-1 then output "message too long" and stop.
331 if ( mLen > (emLen - (2 * hLen) - 1) )
333 msg_Err( p_this , "Message too long" );
338 * Generate an octet string PS consisting of emLen-||M||-2hLen-1 zero
339 * octets. The length of PS may be 0.
341 psLen = emLen - mLen - (2 * hLen) - 1;
345 * Concatenate pHash, PS, the message M, and other padding to form a data
346 * block DB as: DB = pHash || PS || 01 || M
348 DB = calloc( 1, hLen + psLen + 1 + mLen );
349 dbMask = calloc( 1, emLen - hLen );
350 seedMask = calloc( 1, hLen );
352 if ( DB == NULL || dbMask == NULL || seedMask == NULL )
359 * Let pHash = Hash(P), an octet string of length hLen.
361 gcry_md_hash_buffer( Hash, DB, P, pLen );
364 * Generate an octet string PS consisting of emLen-||M||-2hLen-1 zero
365 * octets. The length of PS may be 0.
367 memset( DB + hLen, 0, psLen );
370 * Concatenate pHash, PS, the message M, and other padding to form a data
371 * block DB as: DB = pHash || PS || 01 || M
373 DB[hLen + psLen] = 0x01;
374 memcpy( DB + hLen + psLen + 1, M, mLen );
377 * Generate a random octet string seed of length hLen
379 seed = gcry_random_bytes( hLen, GCRY_STRONG_RANDOM );
387 * Let dbMask = MGF(seed, emLen-hLen).
389 i_err = MGF1( p_this, dbMask, emLen - hLen, seed, hLen, Hash );
390 if ( i_err != VLC_SUCCESS )
394 * Let maskedDB = DB \xor dbMask.
396 for ( i = 0; i < (emLen - hLen); ++i )
400 * Let seedMask = MGF(maskedDB, hLen).
402 i_err = MGF1( p_this, seedMask, hLen, DB, emLen - hLen, Hash );
403 if ( i_err != VLC_SUCCESS )
407 * Let maskedSeed = seed \xor seedMask.
409 for ( i = 0; i < hLen; ++i )
410 seed[i] ^= seedMask[i];
413 * Let EM = maskedSeed || maskedDB.
415 assert( (1 + hLen + (hLen + psLen + 1 + mLen)) == emLenWithPrefix );
417 memcpy( EM + 1, seed, hLen );
418 memcpy( EM + 1 + hLen, DB, hLen + psLen + 1 + mLen );
433 static int EncryptAesKeyBase64( vlc_object_t *p_this, char **result )
435 sout_stream_t *p_stream = (sout_stream_t*)p_this;
436 sout_stream_sys_t *p_sys = p_stream->p_sys;
437 gcry_error_t i_gcrypt_err;
438 gcry_sexp_t sexp_rsa_params = NULL;
439 gcry_sexp_t sexp_input = NULL;
440 gcry_sexp_t sexp_encrypted = NULL;
441 gcry_sexp_t sexp_token_a = NULL;
442 gcry_mpi_t mpi_pubkey = NULL;
443 gcry_mpi_t mpi_exp = NULL;
444 gcry_mpi_t mpi_input = NULL;
445 gcry_mpi_t mpi_output = NULL;
446 unsigned char ps_padded_key[256];
447 unsigned char *ps_value;
451 /* Add RSA-OAES-SHA1 padding */
452 i_err = AddOaepPadding( p_this,
453 ps_padded_key, sizeof( ps_padded_key ),
454 p_sys->ps_aes_key, sizeof( p_sys->ps_aes_key ),
456 if ( i_err != VLC_SUCCESS )
458 i_err = VLC_EGENERIC;
460 /* Read public key */
461 i_gcrypt_err = gcry_mpi_scan( &mpi_pubkey, GCRYMPI_FMT_USG,
463 sizeof( ps_raop_rsa_pubkey ) - 1, NULL );
464 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
468 i_gcrypt_err = gcry_mpi_scan( &mpi_exp, GCRYMPI_FMT_USG, ps_raop_rsa_exp,
469 sizeof( ps_raop_rsa_exp ) - 1, NULL );
470 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
473 /* If the input data starts with a set bit (0x80), gcrypt thinks it's a
474 * signed integer and complains. Prefixing it with a zero byte (\0)
475 * works, but involves more work. Converting it to an MPI in our code is
478 i_gcrypt_err = gcry_mpi_scan( &mpi_input, GCRYMPI_FMT_USG,
479 ps_padded_key, sizeof( ps_padded_key ),
481 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
484 /* Build S-expression with RSA parameters */
485 i_gcrypt_err = gcry_sexp_build( &sexp_rsa_params, NULL,
486 "(public-key(rsa(n %m)(e %m)))",
487 mpi_pubkey, mpi_exp );
488 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
491 /* Build S-expression for data */
492 i_gcrypt_err = gcry_sexp_build( &sexp_input, NULL, "(data(value %m))",
494 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
498 i_gcrypt_err = gcry_pk_encrypt( &sexp_encrypted, sexp_input,
500 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
503 /* Extract encrypted data */
504 sexp_token_a = gcry_sexp_find_token( sexp_encrypted, "a", 0 );
507 msg_Err( p_this , "Token 'a' not found in result S-expression" );
511 mpi_output = gcry_sexp_nth_mpi( sexp_token_a, 1, GCRYMPI_FMT_USG );
514 msg_Err( p_this, "Unable to extract MPI from result" );
518 /* Copy encrypted data into char array */
519 i_gcrypt_err = gcry_mpi_aprint( GCRYMPI_FMT_USG, &ps_value, &i_value_size,
521 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
526 /* Encode in Base64 */
527 *result = vlc_b64_encode_binary( ps_value, i_value_size );
531 gcry_sexp_release( sexp_rsa_params );
532 gcry_sexp_release( sexp_input );
533 gcry_sexp_release( sexp_encrypted );
534 gcry_sexp_release( sexp_token_a );
535 gcry_mpi_release( mpi_pubkey );
536 gcry_mpi_release( mpi_exp );
537 gcry_mpi_release( mpi_input );
538 gcry_mpi_release( mpi_output );
543 static char *ReadPasswordFile( vlc_object_t *p_this, const char *psz_path )
546 char *psz_password = NULL;
550 p_file = utf8_fopen( psz_path, "rt" );
551 if ( p_file == NULL )
553 msg_Err( p_this, "Unable to open password file '%s': %m", psz_path );
557 /* Read one line only */
558 if ( fgets( ps_buffer, sizeof( ps_buffer ), p_file ) == NULL )
560 if ( ferror( p_file ) )
562 msg_Err( p_this, "Error reading '%s': %m", psz_path );
566 /* Nothing was read, but there was no error either. Maybe the file is
567 * empty. Not all implementations of fgets(3) write \0 to the output
568 * buffer in this case.
573 /* Replace first newline with '\0' */
574 psz_newline = strchr( ps_buffer, '\n' );
575 if ( psz_newline != NULL )
579 if ( strlen( ps_buffer ) == 0 ) {
580 msg_Err( p_this, "No password could be read from '%s'", psz_path );
584 psz_password = strdup( ps_buffer );
587 if ( p_file != NULL )
593 /* Splits the value of a received header.
595 * Example: "Transport: RTP/AVP/TCP;unicast;mode=record;server_port=6000"
597 static int SplitHeader( char **ppsz_next, char **ppsz_name,
600 /* Find semicolon (separator between assignments) */
601 *ppsz_name = strsep( ppsz_next, psz_delim_semicolon );
605 *ppsz_name += strspn( *ppsz_name, psz_delim_space );
608 *ppsz_value = *ppsz_name;
609 strsep( ppsz_value, psz_delim_equal );
617 static void FreeHeader( void *p_value, void *p_data )
619 VLC_UNUSED( p_data );
623 static int ReadStatusLine( vlc_object_t *p_this )
625 sout_stream_t *p_stream = (sout_stream_t*)p_this;
626 sout_stream_sys_t *p_sys = p_stream->p_sys;
627 char *psz_line = NULL;
630 int i_result = VLC_EGENERIC;
632 p_sys->psz_last_status_line = net_Gets( p_this, p_sys->i_control_fd,
634 if ( !p_sys->psz_last_status_line )
637 /* Create working copy */
638 psz_line = strdup( p_sys->psz_last_status_line );
642 psz_token = strsep( &psz_next, psz_delim_space );
643 if ( !psz_token || strncmp( psz_token, "RTSP/1.", 7 ) != 0 )
645 msg_Err( p_this, "Unknown protocol (%s)",
646 p_sys->psz_last_status_line );
651 psz_token = strsep( &psz_next, psz_delim_space );
654 msg_Err( p_this, "Request failed (%s)",
655 p_sys->psz_last_status_line );
659 i_result = atoi( psz_token );
667 static int ReadHeader( vlc_object_t *p_this,
668 vlc_dictionary_t *p_resp_headers,
671 sout_stream_t *p_stream = (sout_stream_t*)p_this;
672 sout_stream_sys_t *p_sys = p_stream->p_sys;
673 char *psz_original = NULL;
674 char *psz_line = NULL;
679 int i_err = VLC_SUCCESS;
681 psz_line = net_Gets( p_this, p_sys->i_control_fd, NULL );
684 i_err = VLC_EGENERIC;
688 /* Empty line for response end */
689 if ( psz_line[0] == '\0' )
693 psz_original = strdup( psz_line );
696 psz_token = strsep( &psz_next, psz_delim_colon );
697 if ( !psz_token || psz_next[0] != ' ' )
699 msg_Err( p_this, "Invalid header format (%s)", psz_original );
700 i_err = VLC_EGENERIC;
704 psz_name = psz_token;
705 psz_value = psz_next + 1;
707 vlc_dictionary_insert( p_resp_headers, psz_name, strdup( psz_value ) );
711 free( psz_original );
717 static int WriteAuxHeaders( vlc_object_t *p_this,
718 vlc_dictionary_t *p_req_headers )
720 sout_stream_t *p_stream = (sout_stream_t*)p_this;
721 sout_stream_sys_t *p_sys = p_stream->p_sys;
722 char **ppsz_keys = NULL;
725 int i_err = VLC_SUCCESS;
729 ppsz_keys = vlc_dictionary_all_keys( p_req_headers );
730 for ( i = 0; ppsz_keys[i]; ++i )
732 psz_key = ppsz_keys[i];
733 psz_value = vlc_dictionary_value_for_key( p_req_headers, psz_key );
735 i_rc = net_Printf( p_this, p_sys->i_control_fd, NULL,
736 "%s: %s\r\n", psz_key, psz_value );
739 i_err = VLC_EGENERIC;
745 for ( i = 0; ppsz_keys[i]; ++i )
746 free( ppsz_keys[i] );
752 static int SendRequest( vlc_object_t *p_this, const char *psz_method,
753 const char *psz_content_type, const char *psz_body,
754 vlc_dictionary_t *p_req_headers )
756 sout_stream_t *p_stream = (sout_stream_t*)p_this;
757 sout_stream_sys_t *p_sys = p_stream->p_sys;
758 const unsigned char psz_headers_end[] = "\r\n";
759 size_t i_body_length = 0;
760 int i_err = VLC_SUCCESS;
763 i_rc = net_Printf( p_this, p_sys->i_control_fd, NULL,
765 "User-Agent: " RAOP_USER_AGENT "\r\n"
766 "Client-Instance: %s\r\n"
768 psz_method, p_sys->psz_url,
769 p_sys->psz_client_instance,
773 i_err = VLC_EGENERIC;
777 if ( psz_content_type )
779 i_rc = net_Printf( p_this, p_sys->i_control_fd, NULL,
780 "Content-Type: %s\r\n", psz_content_type );
790 i_body_length = strlen( psz_body );
792 i_rc = net_Printf( p_this, p_sys->i_control_fd, NULL,
793 "Content-Length: %u\r\n",
794 (unsigned int)i_body_length );
802 i_err = WriteAuxHeaders( p_this, p_req_headers );
803 if ( i_err != VLC_SUCCESS )
806 i_rc = net_Write( p_this, p_sys->i_control_fd, NULL,
807 psz_headers_end, sizeof( psz_headers_end ) - 1 );
815 net_Write( p_this, p_sys->i_control_fd, NULL,
816 psz_body, i_body_length );
822 static int ParseAuthenticateHeader( vlc_object_t *p_this,
823 vlc_dictionary_t *p_resp_headers )
825 sout_stream_t *p_stream = (sout_stream_t*)p_this;
826 sout_stream_sys_t *p_sys = p_stream->p_sys;
828 int i_err = VLC_SUCCESS;
830 psz_auth = vlc_dictionary_value_for_key( p_resp_headers,
831 "WWW-Authenticate" );
832 if ( psz_auth == NULL )
834 msg_Err( p_this, "HTTP 401 response missing "
835 "WWW-Authenticate header" );
836 i_err = VLC_EGENERIC;
840 http_auth_ParseWwwAuthenticateHeader( p_this, &p_sys->auth, psz_auth );
846 static int ExecRequest( vlc_object_t *p_this, const char *psz_method,
847 const char *psz_content_type, const char *psz_body,
848 vlc_dictionary_t *p_req_headers,
849 vlc_dictionary_t *p_resp_headers )
851 sout_stream_t *p_stream = (sout_stream_t*)p_this;
852 sout_stream_sys_t *p_sys = p_stream->p_sys;
853 char *psz_authorization = NULL;
855 int i_err = VLC_SUCCESS;
859 if ( p_sys->i_control_fd < 0 )
861 msg_Err( p_this, "Control connection not open" );
862 i_err = VLC_EGENERIC;
869 /* Send header only when Digest authentication is used */
870 if ( p_sys->psz_password != NULL && p_sys->auth.psz_nonce != NULL )
872 FREENULL( psz_authorization );
875 http_auth_FormatAuthorizationHeader( p_this, &p_sys->auth,
878 p_sys->psz_password );
879 if ( psz_authorization == NULL )
881 i_err = VLC_EGENERIC;
885 vlc_dictionary_insert( p_req_headers, "Authorization",
890 i_err = SendRequest( p_this, psz_method, psz_content_type, psz_body,
892 if ( i_err != VLC_SUCCESS )
895 /* Read status line */
896 i_status = ReadStatusLine( p_this );
903 vlc_dictionary_clear( p_resp_headers, FreeHeader, NULL );
907 while ( !headers_done )
909 i_err = ReadHeader( p_this, p_resp_headers, &headers_done );
910 if ( i_err != VLC_SUCCESS )
914 if ( i_status == 200 )
915 /* Request successful */
917 else if ( i_status == 401 )
919 /* Authorization required */
920 if ( i_auth_state == 1 || p_sys->psz_password == NULL )
922 msg_Err( p_this, "Access denied, password invalid" );
923 i_err = VLC_EGENERIC;
927 i_err = ParseAuthenticateHeader( p_this, p_resp_headers );
928 if ( i_err != VLC_SUCCESS )
935 msg_Err( p_this, "Request failed (%s), status is %d",
936 p_sys->psz_last_status_line, i_status );
937 i_err = VLC_EGENERIC;
943 FREENULL( p_sys->psz_last_status_line );
944 free( psz_authorization );
949 static int AnnounceSDP( vlc_object_t *p_this, char *psz_local,
950 uint32_t i_session_id )
952 sout_stream_t *p_stream = (sout_stream_t*)p_this;
953 sout_stream_sys_t *p_sys = p_stream->p_sys;
954 vlc_dictionary_t req_headers;
955 vlc_dictionary_t resp_headers;
956 unsigned char ps_sac[16];
957 char *psz_sdp = NULL;
958 char *psz_sac_base64 = NULL;
959 char *psz_aes_key_base64 = NULL;
960 char *psz_aes_iv_base64 = NULL;
961 int i_err = VLC_SUCCESS;
964 vlc_dictionary_init( &req_headers, 0 );
965 vlc_dictionary_init( &resp_headers, 0 );
967 /* Encrypt AES key and encode it in Base64 */
968 i_rc = EncryptAesKeyBase64( p_this, &psz_aes_key_base64 );
969 if ( i_rc != VLC_SUCCESS || psz_aes_key_base64 == NULL )
971 i_err = VLC_EGENERIC;
974 RemoveBase64Padding( psz_aes_key_base64 );
976 /* Encode AES IV in Base64 */
977 psz_aes_iv_base64 = vlc_b64_encode_binary( p_sys->ps_aes_iv,
978 sizeof( p_sys->ps_aes_iv ) );
979 if ( psz_aes_iv_base64 == NULL )
981 i_err = VLC_EGENERIC;
984 RemoveBase64Padding( psz_aes_iv_base64 );
986 /* Random bytes for Apple-Challenge header */
987 gcry_randomize( ps_sac, sizeof( ps_sac ), GCRY_STRONG_RANDOM );
989 psz_sac_base64 = vlc_b64_encode_binary( ps_sac, sizeof( ps_sac ) );
990 if ( psz_sac_base64 == NULL )
992 i_err = VLC_EGENERIC;
995 RemoveBase64Padding( psz_sac_base64 );
998 * Note: IPv6 addresses also use "IP4". Make sure not to include the
1001 i_rc = asprintf( &psz_sdp,
1003 "o=iTunes %u 0 IN IP4 %s\r\n"
1007 "m=audio 0 RTP/AVP 96\r\n"
1008 "a=rtpmap:96 AppleLossless\r\n"
1009 "a=fmtp:96 4096 0 16 40 10 14 2 255 0 0 44100\r\n"
1010 "a=rsaaeskey:%s\r\n"
1012 i_session_id, psz_local, p_sys->psz_host,
1013 psz_aes_key_base64, psz_aes_iv_base64 );
1021 /* Build and send request */
1022 vlc_dictionary_insert( &req_headers, "Apple-Challenge", psz_sac_base64 );
1024 i_err = ExecRequest( p_this, "ANNOUNCE", "application/sdp", psz_sdp,
1025 &req_headers, &resp_headers);
1026 if ( i_err != VLC_SUCCESS )
1030 vlc_dictionary_clear( &req_headers, NULL, NULL );
1031 vlc_dictionary_clear( &resp_headers, FreeHeader, NULL );
1034 free( psz_sac_base64 );
1035 free( psz_aes_key_base64 );
1036 free( psz_aes_iv_base64 );
1041 static int SendSetup( vlc_object_t *p_this )
1043 sout_stream_t *p_stream = (sout_stream_t*)p_this;
1044 sout_stream_sys_t *p_sys = p_stream->p_sys;
1045 vlc_dictionary_t req_headers;
1046 vlc_dictionary_t resp_headers;
1047 int i_err = VLC_SUCCESS;
1053 vlc_dictionary_init( &req_headers, 0 );
1054 vlc_dictionary_init( &resp_headers, 0 );
1056 vlc_dictionary_insert( &req_headers, "Transport",
1057 ((void*)"RTP/AVP/TCP;unicast;interleaved=0-1;"
1060 i_err = ExecRequest( p_this, "SETUP", NULL, NULL,
1061 &req_headers, &resp_headers );
1062 if ( i_err != VLC_SUCCESS )
1065 psz_tmp = vlc_dictionary_value_for_key( &resp_headers, "Session" );
1068 msg_Err( p_this, "Missing 'Session' header during setup" );
1069 i_err = VLC_EGENERIC;
1073 free( p_sys->psz_session );
1074 p_sys->psz_session = strdup( psz_tmp );
1076 /* Get server_port */
1077 psz_next = vlc_dictionary_value_for_key( &resp_headers, "Transport" );
1078 while ( SplitHeader( &psz_next, &psz_name, &psz_value ) )
1080 if ( psz_value && strcmp( psz_name, "server_port" ) == 0 )
1082 p_sys->i_server_port = atoi( psz_value );
1087 if ( !p_sys->i_server_port )
1089 msg_Err( p_this, "Missing 'server_port' during setup" );
1090 i_err = VLC_EGENERIC;
1095 psz_next = vlc_dictionary_value_for_key( &resp_headers,
1096 "Audio-Jack-Status" );
1097 while ( SplitHeader( &psz_next, &psz_name, &psz_value ) )
1099 if ( strcmp( psz_name, "type" ) != 0 )
1102 if ( strcmp( psz_value, "analog" ) == 0 )
1103 p_sys->i_jack_type = JACK_TYPE_ANALOG;
1105 else if ( strcmp( psz_value, "digital" ) == 0 )
1106 p_sys->i_jack_type = JACK_TYPE_DIGITAL;
1112 vlc_dictionary_clear( &req_headers, NULL, NULL );
1113 vlc_dictionary_clear( &resp_headers, FreeHeader, NULL );
1118 static int SendRecord( vlc_object_t *p_this )
1120 sout_stream_t *p_stream = (sout_stream_t*)p_this;
1121 sout_stream_sys_t *p_sys = p_stream->p_sys;
1122 vlc_dictionary_t req_headers;
1123 vlc_dictionary_t resp_headers;
1124 int i_err = VLC_SUCCESS;
1127 vlc_dictionary_init( &req_headers, 0 );
1128 vlc_dictionary_init( &resp_headers, 0 );
1130 vlc_dictionary_insert( &req_headers, "Range", (void *)"npt=0-" );
1131 vlc_dictionary_insert( &req_headers, "RTP-Info",
1132 (void *)"seq=0;rtptime=0" );
1133 vlc_dictionary_insert( &req_headers, "Session",
1134 (void *)p_sys->psz_session );
1136 i_err = ExecRequest( p_this, "RECORD", NULL, NULL,
1137 &req_headers, &resp_headers );
1138 if ( i_err != VLC_SUCCESS )
1141 psz_value = vlc_dictionary_value_for_key( &resp_headers, "Audio-Latency" );
1143 p_sys->i_audio_latency = atoi( psz_value );
1145 p_sys->i_audio_latency = 0;
1148 vlc_dictionary_clear( &req_headers, NULL, NULL );
1149 vlc_dictionary_clear( &resp_headers, FreeHeader, NULL );
1154 static int SendFlush( vlc_object_t *p_this )
1156 VLC_UNUSED( p_this );
1157 vlc_dictionary_t resp_headers;
1158 vlc_dictionary_t req_headers;
1159 int i_err = VLC_SUCCESS;
1161 vlc_dictionary_init( &req_headers, 0 );
1162 vlc_dictionary_init( &resp_headers, 0 );
1164 vlc_dictionary_insert( &req_headers, "RTP-Info",
1165 (void *)"seq=0;rtptime=0" );
1167 i_err = ExecRequest( p_this, "FLUSH", NULL, NULL,
1168 &req_headers, &resp_headers );
1169 if ( i_err != VLC_SUCCESS )
1173 vlc_dictionary_clear( &req_headers, NULL, NULL );
1174 vlc_dictionary_clear( &resp_headers, FreeHeader, NULL );
1179 static int SendTeardown( vlc_object_t *p_this )
1181 vlc_dictionary_t resp_headers;
1182 vlc_dictionary_t req_headers;
1183 int i_err = VLC_SUCCESS;
1185 vlc_dictionary_init( &req_headers, 0 );
1186 vlc_dictionary_init( &resp_headers, 0 );
1188 i_err = ExecRequest( p_this, "TEARDOWN", NULL, NULL,
1189 &req_headers, &resp_headers );
1190 if ( i_err != VLC_SUCCESS )
1194 vlc_dictionary_clear( &req_headers, NULL, NULL );
1195 vlc_dictionary_clear( &resp_headers, FreeHeader, NULL );
1200 static int UpdateVolume( vlc_object_t *p_this )
1202 sout_stream_t *p_stream = (sout_stream_t*)p_this;
1203 sout_stream_sys_t *p_sys = p_stream->p_sys;
1204 vlc_dictionary_t req_headers;
1205 vlc_dictionary_t resp_headers;
1206 char *psz_parameters = NULL;
1208 int i_err = VLC_SUCCESS;
1211 vlc_dictionary_init( &req_headers, 0 );
1212 vlc_dictionary_init( &resp_headers, 0 );
1214 /* Our volume is 0..255, RAOP is -144..0 (-144 off, -30..0 on) */
1217 p_sys->i_volume = __MAX( 0, __MIN( p_sys->i_volume, 255 ) );
1219 if ( p_sys->i_volume == 0 )
1222 d_volume = -30 + ( ( (double)p_sys->i_volume ) * 30.0 / 255.0 );
1224 /* Format without using locales */
1225 i_rc = us_asprintf( &psz_parameters, "volume: %0.6f\r\n", d_volume );
1232 vlc_dictionary_insert( &req_headers, "Session",
1233 (void *)p_sys->psz_session );
1235 i_err = ExecRequest( p_this, "SET_PARAMETER",
1236 "text/parameters", psz_parameters,
1237 &req_headers, &resp_headers );
1238 if ( i_err != VLC_SUCCESS )
1242 vlc_dictionary_clear( &req_headers, NULL, NULL );
1243 vlc_dictionary_clear( &resp_headers, FreeHeader, NULL );
1244 free( psz_parameters );
1249 static void LogInfo( vlc_object_t *p_this )
1251 sout_stream_t *p_stream = (sout_stream_t*)p_this;
1252 sout_stream_sys_t *p_sys = p_stream->p_sys;
1253 const char *psz_jack_name;
1255 msg_Info( p_this, "Audio latency: %d", p_sys->i_audio_latency );
1257 switch ( p_sys->i_jack_type )
1259 case JACK_TYPE_ANALOG:
1260 psz_jack_name = "analog";
1263 case JACK_TYPE_DIGITAL:
1264 psz_jack_name = "digital";
1267 case JACK_TYPE_NONE:
1269 psz_jack_name = "none";
1273 msg_Info( p_this, "Jack type: %s", psz_jack_name );
1276 static void SendAudio( sout_stream_t *p_stream, block_t *p_buffer )
1278 sout_stream_sys_t *p_sys = p_stream->p_sys;
1279 gcry_error_t i_gcrypt_err;
1282 size_t i_payload_len;
1283 size_t i_realloc_len;
1286 const uint8_t header[16] = {
1287 0x24, 0x00, 0x00, 0x00,
1288 0xf0, 0xff, 0x00, 0x00,
1289 0x00, 0x00, 0x00, 0x00,
1290 0x00, 0x00, 0x00, 0x00,
1295 i_len = sizeof( header ) + p_buffer->i_buffer;
1297 /* Buffer resize needed? */
1298 if ( i_len > p_sys->i_sendbuf_len || p_sys->p_sendbuf == NULL )
1300 /* Grow in blocks of 4K */
1301 i_realloc_len = (1 + (i_len / 4096)) * 4096;
1303 p_sys->p_sendbuf = realloc_or_free( p_sys->p_sendbuf, i_realloc_len );
1304 if ( p_sys->p_sendbuf == NULL )
1307 p_sys->i_sendbuf_len = i_realloc_len;
1311 memcpy( p_sys->p_sendbuf, header, sizeof( header ) );
1312 memcpy( p_sys->p_sendbuf + sizeof( header ),
1313 p_buffer->p_buffer, p_buffer->i_buffer );
1315 /* Calculate payload length and update header */
1316 i_payload_len = i_len - 4;
1317 if ( i_payload_len > 0xffff )
1319 msg_Err( p_stream, "Buffer is too long (%u bytes)",
1320 (unsigned int)i_payload_len );
1324 p_sys->p_sendbuf[2] = ( i_payload_len >> 8 ) & 0xff;
1325 p_sys->p_sendbuf[3] = i_payload_len & 0xff;
1328 i_gcrypt_err = gcry_cipher_reset( p_sys->aes_ctx );
1329 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
1333 i_gcrypt_err = gcry_cipher_setiv( p_sys->aes_ctx, p_sys->ps_aes_iv,
1334 sizeof( p_sys->ps_aes_iv ) );
1335 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
1338 /* Encrypt in place. Only full blocks of 16 bytes are encrypted,
1339 * the rest (0-15 bytes) is left unencrypted.
1342 gcry_cipher_encrypt( p_sys->aes_ctx,
1343 p_sys->p_sendbuf + sizeof( header ),
1344 ( p_buffer->i_buffer / 16 ) * 16,
1346 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
1350 rc = net_Write( p_stream, p_sys->i_stream_fd, NULL,
1351 p_sys->p_sendbuf, i_len );
1355 p_next = p_buffer->p_next;
1356 block_Release( p_buffer );
1361 block_ChainRelease( p_buffer );
1366 /*****************************************************************************
1368 *****************************************************************************/
1369 static int Open( vlc_object_t *p_this )
1371 sout_stream_t *p_stream = (sout_stream_t*)p_this;
1372 sout_stream_sys_t *p_sys;
1373 char psz_local[NI_MAXNUMERICHOST];
1374 char *psz_pwfile = NULL;
1375 gcry_error_t i_gcrypt_err;
1376 int i_err = VLC_SUCCESS;
1377 uint32_t i_session_id;
1378 uint64_t i_client_instance;
1382 config_ChainParse( p_stream, SOUT_CFG_PREFIX, ppsz_sout_options,
1385 p_sys = calloc( 1, sizeof( *p_sys ) );
1386 if ( p_sys == NULL )
1392 p_stream->p_sys = p_sys;
1393 p_stream->pf_add = Add;
1394 p_stream->pf_del = Del;
1395 p_stream->pf_send = Send;
1396 p_stream->p_sout->i_out_pace_nocontrol++;
1398 p_sys->i_control_fd = -1;
1399 p_sys->i_stream_fd = -1;
1400 p_sys->i_volume = var_GetInteger( p_stream, SOUT_CFG_PREFIX "volume");
1401 p_sys->i_jack_type = JACK_TYPE_NONE;
1403 http_auth_Init( &p_sys->auth );
1405 p_sys->psz_host = var_GetNonEmptyString( p_stream,
1406 SOUT_CFG_PREFIX "host" );
1407 if ( p_sys->psz_host == NULL )
1409 msg_Err( p_this, "Missing host" );
1410 i_err = VLC_EGENERIC;
1414 p_sys->psz_password = var_GetNonEmptyString( p_stream,
1415 SOUT_CFG_PREFIX "password" );
1416 if ( p_sys->psz_password == NULL )
1418 /* Try password file instead */
1419 psz_pwfile = var_GetNonEmptyString( p_stream,
1420 SOUT_CFG_PREFIX "password-file" );
1421 if ( psz_pwfile != NULL )
1423 p_sys->psz_password = ReadPasswordFile( p_this, psz_pwfile );
1424 if ( p_sys->psz_password == NULL )
1426 i_err = VLC_EGENERIC;
1432 if ( p_sys->psz_password != NULL )
1433 msg_Info( p_this, "Using password authentication" );
1435 var_AddCallback( p_stream, SOUT_CFG_PREFIX "volume",
1436 VolumeCallback, NULL );
1437 p_sys->b_volume_callback = true;
1439 /* Open control connection */
1440 p_sys->i_control_fd = net_ConnectTCP( p_stream, p_sys->psz_host,
1442 if ( p_sys->i_control_fd < 0 )
1444 msg_Err( p_this, "Cannot establish control connection to %s:%d (%m)",
1445 p_sys->psz_host, RAOP_PORT );
1446 i_err = VLC_EGENERIC;
1450 /* Get local IP address */
1451 if ( net_GetSockAddress( p_sys->i_control_fd, psz_local, NULL ) )
1453 msg_Err( p_this, "cannot get local IP address" );
1454 i_err = VLC_EGENERIC;
1458 /* Random session ID */
1459 gcry_randomize( &i_session_id, sizeof( i_session_id ),
1460 GCRY_STRONG_RANDOM );
1462 /* Random client instance */
1463 gcry_randomize( &i_client_instance, sizeof( i_client_instance ),
1464 GCRY_STRONG_RANDOM );
1465 if ( asprintf( &p_sys->psz_client_instance, "%016"PRIX64,
1466 i_client_instance ) < 0 )
1472 /* Build session URL */
1473 if ( asprintf( &p_sys->psz_url, "rtsp://%s/%u",
1474 psz_local, i_session_id ) < 0 )
1480 /* Generate AES key and IV */
1481 gcry_randomize( p_sys->ps_aes_key, sizeof( p_sys->ps_aes_key ),
1482 GCRY_STRONG_RANDOM );
1483 gcry_randomize( p_sys->ps_aes_iv, sizeof( p_sys->ps_aes_iv ),
1484 GCRY_STRONG_RANDOM );
1487 i_gcrypt_err = gcry_cipher_open( &p_sys->aes_ctx, GCRY_CIPHER_AES,
1488 GCRY_CIPHER_MODE_CBC, 0 );
1489 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
1491 i_err = VLC_EGENERIC;
1496 i_gcrypt_err = gcry_cipher_setkey( p_sys->aes_ctx, p_sys->ps_aes_key,
1497 sizeof( p_sys->ps_aes_key ) );
1498 if ( CheckForGcryptError( p_stream, i_gcrypt_err ) )
1500 i_err = VLC_EGENERIC;
1504 /* Protocol handshake */
1505 i_err = AnnounceSDP( p_this, psz_local, i_session_id );
1506 if ( i_err != VLC_SUCCESS )
1509 i_err = SendSetup( p_this );
1510 if ( i_err != VLC_SUCCESS )
1513 i_err = SendRecord( p_this );
1514 if ( i_err != VLC_SUCCESS )
1517 i_err = UpdateVolume( p_this );
1518 if ( i_err != VLC_SUCCESS )
1523 /* Open stream connection */
1524 p_sys->i_stream_fd = net_ConnectTCP( p_stream, p_sys->psz_host,
1525 p_sys->i_server_port );
1526 if ( p_sys->i_stream_fd < 0 )
1528 msg_Err( p_this, "Cannot establish stream connection to %s:%d (%m)",
1529 p_sys->psz_host, p_sys->i_server_port );
1530 i_err = VLC_EGENERIC;
1537 if ( i_err != VLC_SUCCESS )
1538 FreeSys( p_this, p_sys );
1544 /*****************************************************************************
1546 *****************************************************************************/
1547 static void Close( vlc_object_t *p_this )
1549 sout_stream_t *p_stream = (sout_stream_t*)p_this;
1550 sout_stream_sys_t *p_sys = p_stream->p_sys;
1552 SendFlush( p_this );
1553 SendTeardown( p_this );
1555 FreeSys( p_this, p_sys );
1557 p_stream->p_sout->i_out_pace_nocontrol--;
1561 /*****************************************************************************
1563 *****************************************************************************/
1564 static sout_stream_id_t *Add( sout_stream_t *p_stream, es_format_t *p_fmt )
1566 sout_stream_sys_t *p_sys = p_stream->p_sys;
1567 sout_stream_id_t *id = NULL;
1569 id = calloc( 1, sizeof( *id ) );
1573 es_format_Copy( &id->fmt, p_fmt );
1575 switch ( id->fmt.i_cat )
1578 if ( id->fmt.i_codec == VLC_CODEC_ALAC )
1580 if ( p_sys->p_audio_stream )
1582 msg_Warn( p_stream, "Only the first Apple Lossless audio "
1585 else if ( id->fmt.audio.i_rate != 44100 ||
1586 id->fmt.audio.i_channels != 2 )
1588 msg_Err( p_stream, "The Apple Lossless audio stream must be "
1589 "encoded with 44100 Hz and 2 channels" );
1593 /* Use this stream */
1594 p_sys->p_audio_stream = id;
1597 else if ( !p_sys->b_alac_warning )
1599 msg_Err( p_stream, "Apple Lossless is the only codec supported. "
1600 "Use the \"transcode\" module for conversion "
1601 "(e.g. \"transcode{acodec=alac,"
1602 "channels=2}\")." );
1603 p_sys->b_alac_warning = true;
1609 /* Leave other stream types alone */
1622 /*****************************************************************************
1624 *****************************************************************************/
1625 static int Del( sout_stream_t *p_stream, sout_stream_id_t *id )
1627 sout_stream_sys_t *p_sys = p_stream->p_sys;
1628 int i_err = VLC_SUCCESS;
1630 if ( p_sys->p_audio_stream == id )
1631 p_sys->p_audio_stream = NULL;
1639 /*****************************************************************************
1641 *****************************************************************************/
1642 static int Send( sout_stream_t *p_stream, sout_stream_id_t *id,
1645 sout_stream_sys_t *p_sys = p_stream->p_sys;
1647 if ( id->fmt.i_cat == AUDIO_ES && id == p_sys->p_audio_stream )
1649 /* SendAudio takes care of releasing the buffers */
1650 SendAudio( p_stream, p_buffer );
1654 block_ChainRelease( p_buffer );
1661 /*****************************************************************************
1662 * VolumeCallback: called when the volume is changed on the fly.
1663 *****************************************************************************/
1664 static int VolumeCallback( vlc_object_t *p_this, char const *psz_cmd,
1665 vlc_value_t oldval, vlc_value_t newval,
1668 VLC_UNUSED(psz_cmd);
1672 sout_stream_t *p_stream = (sout_stream_t*)p_this;
1673 sout_stream_sys_t *p_sys = p_stream->p_sys;
1675 /* TODO: Implement volume change */