Directly store alpha in font_stack_t::text_style_t (freetype).
[vlc/solaris.git] / modules / misc / gnutls.c
blobcc60b69cc43d1a747312261365525d82f05a2f2a
1 /*****************************************************************************
2 * gnutls.c
3 *****************************************************************************
4 * Copyright (C) 2004-2006 Rémi Denis-Courmont
5 * $Id$
7 * Authors: Rémi Denis-Courmont <rem # videolan.org>
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 /*****************************************************************************
25 * Preamble
26 *****************************************************************************/
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
32 #include <vlc_common.h>
33 #include <vlc_plugin.h>
34 #include <errno.h>
35 #include <time.h>
37 #include <sys/types.h>
38 #include <errno.h>
39 #ifdef HAVE_SYS_STAT_H
40 # include <sys/stat.h>
41 #endif
42 #ifdef WIN32
43 # include <io.h>
44 #else
45 # include <unistd.h>
46 #endif
47 # include <fcntl.h>
50 #include <vlc_tls.h>
51 #include <vlc_charset.h>
52 #include <vlc_fs.h>
53 #include <vlc_block.h>
55 #include <gcrypt.h>
56 #include <gnutls/gnutls.h>
57 #include <gnutls/x509.h>
59 #include <vlc_gcrypt.h>
61 #define CACHE_TIMEOUT 3600
62 #define CACHE_SIZE 64
64 #include "dhparams.h"
66 #include <assert.h>
68 /*****************************************************************************
69 * Module descriptor
70 *****************************************************************************/
71 static int OpenClient (vlc_object_t *);
72 static void CloseClient (vlc_object_t *);
73 static int OpenServer (vlc_object_t *);
74 static void CloseServer (vlc_object_t *);
76 #define PRIORITIES_TEXT N_("TLS cipher priorities")
77 #define PRIORITIES_LONGTEXT N_("Ciphers, key exchange methods, " \
78 "hash functions and compression methods can be selected. " \
79 "Refer to GNU TLS documentation for detailed syntax.")
80 static const char *const priorities_values[] = {
81 "PERFORMANCE",
82 "NORMAL",
83 "SECURE128",
84 "SECURE256",
85 "EXPORT",
87 static const char *const priorities_text[] = {
88 N_("Performance (prioritize faster ciphers)"),
89 N_("Normal"),
90 N_("Secure 128-bits (exclude 256-bits ciphers)"),
91 N_("Secure 256-bits (prioritize 256-bits ciphers)"),
92 N_("Export (include insecure ciphers)"),
95 #define CACHE_TIMEOUT_TEXT N_("Expiration time for resumed TLS sessions")
96 #define CACHE_TIMEOUT_LONGTEXT N_( \
97 "It is possible to cache the resumed TLS sessions. This is the expiration "\
98 "time of the sessions stored in this cache, in seconds." )
100 #define CACHE_SIZE_TEXT N_("Number of resumed TLS sessions")
101 #define CACHE_SIZE_LONGTEXT N_( \
102 "This is the maximum number of resumed TLS sessions that " \
103 "the cache will hold." )
105 vlc_module_begin ()
106 set_shortname( "GNU TLS" )
107 set_description( N_("GNU TLS transport layer security") )
108 set_capability( "tls client", 1 )
109 set_callbacks( OpenClient, CloseClient )
110 set_category( CAT_ADVANCED )
111 set_subcategory( SUBCAT_ADVANCED_MISC )
113 add_submodule ()
114 set_description( N_("GNU TLS server") )
115 set_capability( "tls server", 1 )
116 set_category( CAT_ADVANCED )
117 set_subcategory( SUBCAT_ADVANCED_MISC )
118 set_callbacks( OpenServer, CloseServer )
120 add_string ("gnutls-priorities", "NORMAL", PRIORITIES_TEXT,
121 PRIORITIES_LONGTEXT, false)
122 change_string_list (priorities_values, priorities_text, NULL)
123 add_integer( "gnutls-cache-timeout", CACHE_TIMEOUT,
124 CACHE_TIMEOUT_TEXT, CACHE_TIMEOUT_LONGTEXT, true )
125 add_integer( "gnutls-cache-size", CACHE_SIZE, CACHE_SIZE_TEXT,
126 CACHE_SIZE_LONGTEXT, true )
127 vlc_module_end ()
129 static vlc_mutex_t gnutls_mutex = VLC_STATIC_MUTEX;
132 * Initializes GnuTLS with proper locking.
133 * @return VLC_SUCCESS on success, a VLC error code otherwise.
135 static int gnutls_Init (vlc_object_t *p_this)
137 int ret = VLC_EGENERIC;
139 vlc_gcrypt_init (); /* GnuTLS depends on gcrypt */
141 vlc_mutex_lock (&gnutls_mutex);
142 if (gnutls_global_init ())
144 msg_Err (p_this, "cannot initialize GnuTLS");
145 goto error;
148 const char *psz_version = gnutls_check_version ("1.3.3");
149 if (psz_version == NULL)
151 msg_Err (p_this, "unsupported GnuTLS version");
152 gnutls_global_deinit ();
153 goto error;
156 msg_Dbg (p_this, "GnuTLS v%s initialized", psz_version);
157 ret = VLC_SUCCESS;
159 error:
160 vlc_mutex_unlock (&gnutls_mutex);
161 return ret;
166 * Deinitializes GnuTLS.
168 static void gnutls_Deinit (vlc_object_t *p_this)
170 vlc_mutex_lock (&gnutls_mutex);
172 gnutls_global_deinit ();
173 msg_Dbg (p_this, "GnuTLS deinitialized");
174 vlc_mutex_unlock (&gnutls_mutex);
178 static int gnutls_Error (vlc_object_t *obj, int val)
180 switch (val)
182 case GNUTLS_E_AGAIN:
183 #ifdef WIN32
184 WSASetLastError (WSAEWOULDBLOCK);
185 #else
186 errno = EAGAIN;
187 #endif
188 break;
190 case GNUTLS_E_INTERRUPTED:
191 #ifdef WIN32
192 WSASetLastError (WSAEINTR);
193 #else
194 errno = EINTR;
195 #endif
196 break;
198 default:
199 msg_Err (obj, "%s", gnutls_strerror (val));
200 #ifndef NDEBUG
201 if (!gnutls_error_is_fatal (val))
202 msg_Err (obj, "Error above should be handled");
203 #endif
204 #ifdef WIN32
205 WSASetLastError (WSAECONNRESET);
206 #else
207 errno = ECONNRESET;
208 #endif
210 return -1;
214 struct tls_session_sys_t
216 gnutls_session_t session;
217 char *psz_hostname;
218 bool b_handshaked;
223 * Sends data through a TLS session.
225 static int
226 gnutls_Send( void *p_session, const void *buf, int i_length )
228 int val;
229 tls_session_sys_t *p_sys;
231 p_sys = (tls_session_sys_t *)(((tls_session_t *)p_session)->p_sys);
233 val = gnutls_record_send( p_sys->session, buf, i_length );
234 return (val < 0) ? gnutls_Error ((vlc_object_t *)p_session, val) : val;
239 * Receives data through a TLS session.
241 static int
242 gnutls_Recv( void *p_session, void *buf, int i_length )
244 int val;
245 tls_session_sys_t *p_sys;
247 p_sys = (tls_session_sys_t *)(((tls_session_t *)p_session)->p_sys);
249 val = gnutls_record_recv( p_sys->session, buf, i_length );
250 return (val < 0) ? gnutls_Error ((vlc_object_t *)p_session, val) : val;
255 * Starts or continues the TLS handshake.
257 * @return -1 on fatal error, 0 on successful handshake completion,
258 * 1 if more would-be blocking recv is needed,
259 * 2 if more would-be blocking send is required.
261 static int
262 gnutls_ContinueHandshake (tls_session_t *p_session)
264 tls_session_sys_t *p_sys = p_session->p_sys;
265 int val;
267 #ifdef WIN32
268 WSASetLastError( 0 );
269 #endif
270 val = gnutls_handshake( p_sys->session );
271 if( ( val == GNUTLS_E_AGAIN ) || ( val == GNUTLS_E_INTERRUPTED ) )
272 return 1 + gnutls_record_get_direction( p_sys->session );
274 if( val < 0 )
276 #ifdef WIN32
277 msg_Dbg( p_session, "Winsock error %d", WSAGetLastError( ) );
278 #endif
279 msg_Err( p_session, "TLS handshake error: %s",
280 gnutls_strerror( val ) );
281 return -1;
284 p_sys->b_handshaked = true;
285 return 0;
289 typedef struct
291 int flag;
292 const char *msg;
293 } error_msg_t;
295 static const error_msg_t cert_errors[] =
297 { GNUTLS_CERT_INVALID,
298 "Certificate could not be verified" },
299 { GNUTLS_CERT_REVOKED,
300 "Certificate was revoked" },
301 { GNUTLS_CERT_SIGNER_NOT_FOUND,
302 "Certificate's signer was not found" },
303 { GNUTLS_CERT_SIGNER_NOT_CA,
304 "Certificate's signer is not a CA" },
305 { GNUTLS_CERT_INSECURE_ALGORITHM,
306 "Insecure certificate signature algorithm" },
307 { 0, NULL }
311 static int
312 gnutls_HandshakeAndValidate( tls_session_t *session )
314 int val = gnutls_ContinueHandshake( session );
315 if( val )
316 return val;
318 tls_session_sys_t *p_sys = (tls_session_sys_t *)(session->p_sys);
320 /* certificates chain verification */
321 unsigned status;
322 val = gnutls_certificate_verify_peers2( p_sys->session, &status );
324 if( val )
326 msg_Err( session, "Certificate verification failed: %s",
327 gnutls_strerror( val ) );
328 return -1;
331 if( status )
333 msg_Err( session, "TLS session: access denied" );
334 for( const error_msg_t *e = cert_errors; e->flag; e++ )
336 if( status & e->flag )
338 msg_Err( session, "%s", e->msg );
339 status &= ~e->flag;
343 if( status )
344 msg_Err( session,
345 "unknown certificate error (you found a bug in VLC)" );
347 return -1;
350 /* certificate (host)name verification */
351 const gnutls_datum_t *data;
352 data = gnutls_certificate_get_peers (p_sys->session, &(unsigned){0});
353 if( data == NULL )
355 msg_Err( session, "Peer certificate not available" );
356 return -1;
359 gnutls_x509_crt_t cert;
360 val = gnutls_x509_crt_init( &cert );
361 if( val )
363 msg_Err( session, "x509 fatal error: %s", gnutls_strerror( val ) );
364 return -1;
367 val = gnutls_x509_crt_import( cert, data, GNUTLS_X509_FMT_DER );
368 if( val )
370 msg_Err( session, "Certificate import error: %s",
371 gnutls_strerror( val ) );
372 goto error;
375 assert( p_sys->psz_hostname != NULL );
376 if ( !gnutls_x509_crt_check_hostname( cert, p_sys->psz_hostname ) )
378 msg_Err( session, "Certificate does not match \"%s\"",
379 p_sys->psz_hostname );
380 goto error;
383 if( gnutls_x509_crt_get_expiration_time( cert ) < time( NULL ) )
385 msg_Err( session, "Certificate expired" );
386 goto error;
389 if( gnutls_x509_crt_get_activation_time( cert ) > time ( NULL ) )
391 msg_Err( session, "Certificate not yet valid" );
392 goto error;
395 gnutls_x509_crt_deinit( cert );
396 msg_Dbg( session, "TLS/x509 certificate verified" );
397 return 0;
399 error:
400 gnutls_x509_crt_deinit( cert );
401 return -1;
405 * Sets the operating system file descriptor backend for the TLS sesison.
407 * @param fd stream socket already connected with the peer.
409 static void
410 gnutls_SetFD (tls_session_t *p_session, int fd)
412 gnutls_transport_set_ptr (p_session->p_sys->session,
413 (gnutls_transport_ptr_t)(intptr_t)fd);
416 static int
417 gnutls_SessionPrioritize (vlc_object_t *obj, gnutls_session_t session)
419 char *priorities = var_InheritString (obj, "gnutls-priorities");
420 if (unlikely(priorities == NULL))
421 return VLC_ENOMEM;
423 const char *errp;
424 int val = gnutls_priority_set_direct (session, priorities, &errp);
425 if (val < 0)
427 msg_Err (obj, "cannot set TLS priorities \"%s\": %s", errp,
428 gnutls_strerror (val));
429 val = VLC_EGENERIC;
431 else
432 val = VLC_SUCCESS;
433 free (priorities);
434 return val;
438 static int
439 gnutls_Addx509File( vlc_object_t *p_this,
440 gnutls_certificate_credentials_t cred,
441 const char *psz_path, bool b_priv );
443 static int
444 gnutls_Addx509Directory( vlc_object_t *p_this,
445 gnutls_certificate_credentials_t cred,
446 const char *psz_dirname,
447 bool b_priv )
449 DIR* dir;
451 if( *psz_dirname == '\0' )
452 psz_dirname = ".";
454 dir = vlc_opendir( psz_dirname );
455 if( dir == NULL )
457 if (errno != ENOENT)
459 msg_Err (p_this, "cannot open directory (%s): %m", psz_dirname);
460 return VLC_EGENERIC;
463 msg_Dbg (p_this, "creating empty certificate directory: %s",
464 psz_dirname);
465 vlc_mkdir (psz_dirname, b_priv ? 0700 : 0755);
466 return VLC_SUCCESS;
468 #ifdef S_ISLNK
469 else
471 struct stat st1, st2;
472 int fd = dirfd( dir );
475 * Gets stats for the directory path, checks that it is not a
476 * symbolic link (to avoid possibly infinite recursion), and verifies
477 * that the inode is still the same, to avoid TOCTOU race condition.
479 if( ( fd == -1)
480 || fstat( fd, &st1 ) || vlc_lstat( psz_dirname, &st2 )
481 || S_ISLNK( st2.st_mode ) || ( st1.st_ino != st2.st_ino ) )
483 closedir( dir );
484 return VLC_EGENERIC;
487 #endif
489 for (;;)
491 char *ent = vlc_readdir (dir);
492 if (ent == NULL)
493 break;
495 if ((strcmp (ent, ".") == 0) || (strcmp (ent, "..") == 0))
497 free( ent );
498 continue;
501 char path[strlen (psz_dirname) + strlen (ent) + 2];
502 sprintf (path, "%s"DIR_SEP"%s", psz_dirname, ent);
503 free (ent);
505 gnutls_Addx509File( p_this, cred, path, b_priv );
508 closedir( dir );
509 return VLC_SUCCESS;
513 static int
514 gnutls_Addx509File( vlc_object_t *p_this,
515 gnutls_certificate_credentials cred,
516 const char *psz_path, bool b_priv )
518 struct stat st;
520 int fd = vlc_open (psz_path, O_RDONLY);
521 if (fd == -1)
522 goto error;
524 block_t *block = block_File (fd);
525 if (block != NULL)
527 close (fd);
529 gnutls_datum data = {
530 .data = block->p_buffer,
531 .size = block->i_buffer,
533 int res = b_priv
534 ? gnutls_certificate_set_x509_key_mem (cred, &data, &data,
535 GNUTLS_X509_FMT_PEM)
536 : gnutls_certificate_set_x509_trust_mem (cred, &data,
537 GNUTLS_X509_FMT_PEM);
538 block_Release (block);
540 if (res < 0)
542 msg_Warn (p_this, "cannot add x509 credentials (%s): %s",
543 psz_path, gnutls_strerror (res));
544 return VLC_EGENERIC;
546 msg_Dbg (p_this, "added x509 credentials (%s)", psz_path);
547 return VLC_SUCCESS;
550 if (!fstat (fd, &st) && S_ISDIR (st.st_mode))
552 close (fd);
553 msg_Dbg (p_this, "looking recursively for x509 credentials in %s",
554 psz_path);
555 return gnutls_Addx509Directory (p_this, cred, psz_path, b_priv);
558 error:
559 msg_Warn (p_this, "cannot add x509 credentials (%s): %m", psz_path);
560 if (fd != -1)
561 close (fd);
562 return VLC_EGENERIC;
566 /** TLS client session data */
567 typedef struct tls_client_sys_t
569 struct tls_session_sys_t session;
570 gnutls_certificate_credentials_t x509_cred;
571 } tls_client_sys_t;
575 * Initializes a client-side TLS session.
577 static int OpenClient (vlc_object_t *obj)
579 tls_session_t *p_session = (tls_session_t *)obj;
580 int i_val;
582 if (gnutls_Init (obj))
583 return VLC_EGENERIC;
585 tls_client_sys_t *p_sys = malloc (sizeof (*p_sys));
586 if (p_sys == NULL)
588 gnutls_Deinit (obj);
589 return VLC_ENOMEM;
592 p_session->p_sys = &p_sys->session;
593 p_session->sock.p_sys = p_session;
594 p_session->sock.pf_send = gnutls_Send;
595 p_session->sock.pf_recv = gnutls_Recv;
596 p_session->pf_set_fd = gnutls_SetFD;
598 p_sys->session.b_handshaked = false;
600 i_val = gnutls_certificate_allocate_credentials (&p_sys->x509_cred);
601 if (i_val != 0)
603 msg_Err (obj, "cannot allocate X509 credentials: %s",
604 gnutls_strerror (i_val));
605 goto error;
608 char *userdir = config_GetUserDir ( VLC_DATA_DIR );
609 if (userdir != NULL)
611 char path[strlen (userdir) + sizeof ("/ssl/private")];
612 sprintf (path, "%s/ssl", userdir);
613 vlc_mkdir (path, 0755);
615 sprintf (path, "%s/ssl/certs", userdir);
616 gnutls_Addx509Directory (VLC_OBJECT (p_session),
617 p_sys->x509_cred, path, false);
618 sprintf (path, "%s/ssl/private", userdir);
619 gnutls_Addx509Directory (VLC_OBJECT (p_session), p_sys->x509_cred,
620 path, true);
621 free (userdir);
624 const char *confdir = config_GetConfDir ();
626 char path[strlen (confdir)
627 + sizeof ("/ssl/certs/ca-certificates.crt")];
628 sprintf (path, "%s/ssl/certs/ca-certificates.crt", confdir);
629 gnutls_Addx509File (VLC_OBJECT (p_session),
630 p_sys->x509_cred, path, false);
632 p_session->pf_handshake = gnutls_HandshakeAndValidate;
633 /*p_session->pf_handshake = gnutls_ContinueHandshake;*/
635 i_val = gnutls_init (&p_sys->session.session, GNUTLS_CLIENT);
636 if (i_val != 0)
638 msg_Err (obj, "cannot initialize TLS session: %s",
639 gnutls_strerror (i_val));
640 gnutls_certificate_free_credentials (p_sys->x509_cred);
641 goto error;
644 if (gnutls_SessionPrioritize (VLC_OBJECT (p_session),
645 p_sys->session.session))
646 goto s_error;
648 /* minimum DH prime bits */
649 gnutls_dh_set_prime_bits (p_sys->session.session, 1024);
651 i_val = gnutls_credentials_set (p_sys->session.session,
652 GNUTLS_CRD_CERTIFICATE,
653 p_sys->x509_cred);
654 if (i_val < 0)
656 msg_Err (obj, "cannot set TLS session credentials: %s",
657 gnutls_strerror (i_val));
658 goto s_error;
661 char *servername = var_GetNonEmptyString (p_session, "tls-server-name");
662 if (servername == NULL )
663 msg_Err (p_session, "server name missing for TLS session");
664 else
665 gnutls_server_name_set (p_sys->session.session, GNUTLS_NAME_DNS,
666 servername, strlen (servername));
668 p_sys->session.psz_hostname = servername;
670 return VLC_SUCCESS;
672 s_error:
673 gnutls_deinit (p_sys->session.session);
674 gnutls_certificate_free_credentials (p_sys->x509_cred);
675 error:
676 gnutls_Deinit (obj);
677 free (p_sys);
678 return VLC_EGENERIC;
682 static void CloseClient (vlc_object_t *obj)
684 tls_session_t *client = (tls_session_t *)obj;
685 tls_client_sys_t *p_sys = (tls_client_sys_t *)(client->p_sys);
687 if (p_sys->session.b_handshaked)
688 gnutls_bye (p_sys->session.session, GNUTLS_SHUT_WR);
689 gnutls_deinit (p_sys->session.session);
690 /* credentials must be free'd *after* gnutls_deinit() */
691 gnutls_certificate_free_credentials (p_sys->x509_cred);
693 gnutls_Deinit (obj);
694 free (p_sys->session.psz_hostname);
695 free (p_sys);
700 * Server-side TLS
702 struct tls_server_sys_t
704 gnutls_certificate_credentials_t x509_cred;
705 gnutls_dh_params_t dh_params;
707 struct saved_session_t *p_cache;
708 struct saved_session_t *p_store;
709 int i_cache_size;
710 vlc_mutex_t cache_lock;
712 int (*pf_handshake) (tls_session_t *);
717 * TLS session resumption callbacks (server-side)
719 #define MAX_SESSION_ID 32
720 #define MAX_SESSION_DATA 1024
722 typedef struct saved_session_t
724 char id[MAX_SESSION_ID];
725 char data[MAX_SESSION_DATA];
727 unsigned i_idlen;
728 unsigned i_datalen;
729 } saved_session_t;
732 static int cb_store( void *p_server, gnutls_datum key, gnutls_datum data )
734 tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
736 if( ( p_sys->i_cache_size == 0 )
737 || ( key.size > MAX_SESSION_ID )
738 || ( data.size > MAX_SESSION_DATA ) )
739 return -1;
741 vlc_mutex_lock( &p_sys->cache_lock );
743 memcpy( p_sys->p_store->id, key.data, key.size);
744 memcpy( p_sys->p_store->data, data.data, data.size );
745 p_sys->p_store->i_idlen = key.size;
746 p_sys->p_store->i_datalen = data.size;
748 p_sys->p_store++;
749 if( ( p_sys->p_store - p_sys->p_cache ) == p_sys->i_cache_size )
750 p_sys->p_store = p_sys->p_cache;
752 vlc_mutex_unlock( &p_sys->cache_lock );
754 return 0;
758 static gnutls_datum cb_fetch( void *p_server, gnutls_datum key )
760 static const gnutls_datum_t err_datum = { NULL, 0 };
761 tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
762 saved_session_t *p_session, *p_end;
764 p_session = p_sys->p_cache;
765 p_end = p_session + p_sys->i_cache_size;
767 vlc_mutex_lock( &p_sys->cache_lock );
769 while( p_session < p_end )
771 if( ( p_session->i_idlen == key.size )
772 && !memcmp( p_session->id, key.data, key.size ) )
774 gnutls_datum_t data;
776 data.size = p_session->i_datalen;
778 data.data = gnutls_malloc( data.size );
779 if( data.data == NULL )
781 vlc_mutex_unlock( &p_sys->cache_lock );
782 return err_datum;
785 memcpy( data.data, p_session->data, data.size );
786 vlc_mutex_unlock( &p_sys->cache_lock );
787 return data;
789 p_session++;
792 vlc_mutex_unlock( &p_sys->cache_lock );
794 return err_datum;
798 static int cb_delete( void *p_server, gnutls_datum key )
800 tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
801 saved_session_t *p_session, *p_end;
803 p_session = p_sys->p_cache;
804 p_end = p_session + p_sys->i_cache_size;
806 vlc_mutex_lock( &p_sys->cache_lock );
808 while( p_session < p_end )
810 if( ( p_session->i_idlen == key.size )
811 && !memcmp( p_session->id, key.data, key.size ) )
813 p_session->i_datalen = p_session->i_idlen = 0;
814 vlc_mutex_unlock( &p_sys->cache_lock );
815 return 0;
817 p_session++;
820 vlc_mutex_unlock( &p_sys->cache_lock );
822 return -1;
827 * Terminates TLS session and releases session data.
828 * You still have to close the socket yourself.
830 static void
831 gnutls_SessionClose (tls_server_t *p_server, tls_session_t *p_session)
833 tls_session_sys_t *p_sys = p_session->p_sys;
834 (void)p_server;
836 if( p_sys->b_handshaked )
837 gnutls_bye( p_sys->session, GNUTLS_SHUT_WR );
838 gnutls_deinit( p_sys->session );
840 vlc_object_release( p_session );
842 free( p_sys );
847 * Initializes a server-side TLS session.
849 static tls_session_t *
850 gnutls_ServerSessionPrepare( tls_server_t *p_server )
852 tls_session_t *p_session;
853 tls_server_sys_t *p_server_sys;
854 gnutls_session_t session;
855 int i_val;
857 p_session = vlc_object_create( p_server, sizeof (struct tls_session_t) );
858 if( p_session == NULL )
859 return NULL;
861 p_session->p_sys = malloc( sizeof(struct tls_session_sys_t) );
862 if( p_session->p_sys == NULL )
864 vlc_object_release( p_session );
865 return NULL;
868 p_server_sys = p_server->p_sys;
869 p_session->sock.p_sys = p_session;
870 p_session->sock.pf_send = gnutls_Send;
871 p_session->sock.pf_recv = gnutls_Recv;
872 p_session->pf_set_fd = gnutls_SetFD;
873 p_session->pf_handshake = p_server_sys->pf_handshake;
875 p_session->p_sys->b_handshaked = false;
876 p_session->p_sys->psz_hostname = NULL;
878 i_val = gnutls_init( &session, GNUTLS_SERVER );
879 if( i_val != 0 )
881 msg_Err( p_server, "cannot initialize TLS session: %s",
882 gnutls_strerror( i_val ) );
883 goto error;
886 p_session->p_sys->session = session;
888 if (gnutls_SessionPrioritize (VLC_OBJECT (p_session), session))
890 gnutls_deinit( session );
891 goto error;
894 i_val = gnutls_credentials_set( session, GNUTLS_CRD_CERTIFICATE,
895 p_server_sys->x509_cred );
896 if( i_val < 0 )
898 msg_Err( p_server, "cannot set TLS session credentials: %s",
899 gnutls_strerror( i_val ) );
900 gnutls_deinit( session );
901 goto error;
904 if (p_session->pf_handshake == gnutls_HandshakeAndValidate)
905 gnutls_certificate_server_set_request (session, GNUTLS_CERT_REQUIRE);
907 /* Session resumption support */
908 i_val = var_InheritInteger (p_server, "gnutls-cache-timeout");
909 if (i_val >= 0)
910 gnutls_db_set_cache_expiration (session, i_val);
911 gnutls_db_set_retrieve_function( session, cb_fetch );
912 gnutls_db_set_remove_function( session, cb_delete );
913 gnutls_db_set_store_function( session, cb_store );
914 gnutls_db_set_ptr( session, p_server );
916 return p_session;
918 error:
919 free( p_session->p_sys );
920 vlc_object_release( p_session );
921 return NULL;
926 * Adds one or more certificate authorities.
928 * @param psz_ca_path (Unicode) path to an x509 certificates list.
930 * @return -1 on error, 0 on success.
932 static int
933 gnutls_ServerAddCA( tls_server_t *p_server, const char *psz_ca_path )
935 tls_server_sys_t *p_sys;
936 char *psz_local_path;
937 int val;
939 p_sys = (tls_server_sys_t *)(p_server->p_sys);
941 psz_local_path = ToLocale( psz_ca_path );
942 val = gnutls_certificate_set_x509_trust_file( p_sys->x509_cred,
943 psz_local_path,
944 GNUTLS_X509_FMT_PEM );
945 LocaleFree( psz_local_path );
946 if( val < 0 )
948 msg_Err( p_server, "cannot add trusted CA (%s): %s", psz_ca_path,
949 gnutls_strerror( val ) );
950 return VLC_EGENERIC;
952 msg_Dbg( p_server, " %d trusted CA added (%s)", val, psz_ca_path );
954 /* enables peer's certificate verification */
955 p_sys->pf_handshake = gnutls_HandshakeAndValidate;
957 return VLC_SUCCESS;
962 * Adds a certificates revocation list to be sent to TLS clients.
964 * @param psz_crl_path (Unicode) path of the CRL file.
966 * @return -1 on error, 0 on success.
968 static int
969 gnutls_ServerAddCRL( tls_server_t *p_server, const char *psz_crl_path )
971 int val;
972 char *psz_local_path = ToLocale( psz_crl_path );
974 val = gnutls_certificate_set_x509_crl_file( ((tls_server_sys_t *)
975 (p_server->p_sys))->x509_cred,
976 psz_local_path,
977 GNUTLS_X509_FMT_PEM );
978 LocaleFree( psz_crl_path );
979 if( val < 0 )
981 msg_Err( p_server, "cannot add CRL (%s): %s", psz_crl_path,
982 gnutls_strerror( val ) );
983 return VLC_EGENERIC;
985 msg_Dbg( p_server, "%d CRL added (%s)", val, psz_crl_path );
986 return VLC_SUCCESS;
991 * Allocates a whole server's TLS credentials.
993 static int OpenServer (vlc_object_t *obj)
995 tls_server_t *p_server = (tls_server_t *)obj;
996 tls_server_sys_t *p_sys;
997 int val;
999 if (gnutls_Init (obj))
1000 return VLC_EGENERIC;
1002 msg_Dbg (obj, "creating TLS server");
1004 p_sys = (tls_server_sys_t *)malloc( sizeof(struct tls_server_sys_t) );
1005 if( p_sys == NULL )
1006 return VLC_ENOMEM;
1008 p_sys->i_cache_size = var_InheritInteger (obj, "gnutls-cache-size");
1009 if (p_sys->i_cache_size == -1) /* Duh, config subsystem exploded?! */
1010 p_sys->i_cache_size = 0;
1011 p_sys->p_cache = calloc (p_sys->i_cache_size,
1012 sizeof (struct saved_session_t));
1013 if (p_sys->p_cache == NULL)
1015 free (p_sys);
1016 return VLC_ENOMEM;
1019 p_sys->p_store = p_sys->p_cache;
1020 p_server->p_sys = p_sys;
1021 p_server->pf_add_CA = gnutls_ServerAddCA;
1022 p_server->pf_add_CRL = gnutls_ServerAddCRL;
1023 p_server->pf_open = gnutls_ServerSessionPrepare;
1024 p_server->pf_close = gnutls_SessionClose;
1026 /* No certificate validation by default */
1027 p_sys->pf_handshake = gnutls_ContinueHandshake;
1029 vlc_mutex_init( &p_sys->cache_lock );
1031 /* Sets server's credentials */
1032 val = gnutls_certificate_allocate_credentials( &p_sys->x509_cred );
1033 if( val != 0 )
1035 msg_Err( p_server, "cannot allocate X509 credentials: %s",
1036 gnutls_strerror( val ) );
1037 goto error;
1040 char *psz_cert_path = var_GetNonEmptyString (obj, "tls-x509-cert");
1041 char *psz_key_path = var_GetNonEmptyString (obj, "tls-x509-key");
1042 const char *psz_local_cert = ToLocale (psz_cert_path);
1043 const char *psz_local_key = ToLocale (psz_key_path);
1044 val = gnutls_certificate_set_x509_key_file (p_sys->x509_cred,
1045 psz_local_cert, psz_local_key,
1046 GNUTLS_X509_FMT_PEM );
1047 LocaleFree (psz_local_key);
1048 free (psz_key_path);
1049 LocaleFree (psz_local_cert);
1050 free (psz_cert_path);
1052 if( val < 0 )
1054 msg_Err( p_server, "cannot set certificate chain or private key: %s",
1055 gnutls_strerror( val ) );
1056 gnutls_certificate_free_credentials( p_sys->x509_cred );
1057 goto error;
1060 /* FIXME:
1061 * - support other ciper suites
1063 val = gnutls_dh_params_init (&p_sys->dh_params);
1064 if (val >= 0)
1066 const gnutls_datum_t data = {
1067 .data = (unsigned char *)dh_params,
1068 .size = sizeof (dh_params) - 1,
1071 val = gnutls_dh_params_import_pkcs3 (p_sys->dh_params, &data,
1072 GNUTLS_X509_FMT_PEM);
1073 if (val == 0)
1074 gnutls_certificate_set_dh_params (p_sys->x509_cred,
1075 p_sys->dh_params);
1077 if (val < 0)
1079 msg_Err (p_server, "cannot initialize DHE cipher suites: %s",
1080 gnutls_strerror (val));
1083 return VLC_SUCCESS;
1085 error:
1086 vlc_mutex_destroy (&p_sys->cache_lock);
1087 free (p_sys->p_cache);
1088 free (p_sys);
1089 return VLC_EGENERIC;
1093 * Destroys a TLS server object.
1095 static void CloseServer (vlc_object_t *p_server)
1097 tls_server_sys_t *p_sys = ((tls_server_t *)p_server)->p_sys;
1099 vlc_mutex_destroy (&p_sys->cache_lock);
1100 free (p_sys->p_cache);
1102 /* all sessions depending on the server are now deinitialized */
1103 gnutls_certificate_free_credentials (p_sys->x509_cred);
1104 gnutls_dh_params_deinit (p_sys->dh_params);
1105 free (p_sys);
1107 gnutls_Deinit (p_server);