[RFC,4/6] Add the tls protocol, using OpenSSL or gnutls

Message ID 1320067723-45345-5-git-send-email-martin@martin.st
State Superseded
Headers show

Commit Message

Martin Storsjö Oct. 31, 2011, 1:28 p.m.
Note, this protocol doesn't yet check verify the server
certificate against a local database of trusted CA root
certificates.
---
 configure                |    2 +
 libavformat/Makefile     |    1 +
 libavformat/allformats.c |    1 +
 libavformat/tls.c        |  330 ++++++++++++++++++++++++++++++++++++++++++++++
 libavformat/version.h    |    2 +-
 5 files changed, 335 insertions(+), 1 deletions(-)
 create mode 100644 libavformat/tls.c

Patch

diff --git a/configure b/configure
index 27366fd..41223d9 100755
--- a/configure
+++ b/configure
@@ -1483,6 +1483,8 @@  mmst_protocol_deps="network"
 rtmp_protocol_select="tcp_protocol"
 rtp_protocol_select="udp_protocol"
 tcp_protocol_deps="network"
+tls_protocol_deps_any="openssl gnutls"
+tls_protocol_select="tcp_protocol"
 udp_protocol_deps="network"
 
 # filters
diff --git a/libavformat/Makefile b/libavformat/Makefile
index 903b3ee..66bd863 100644
--- a/libavformat/Makefile
+++ b/libavformat/Makefile
@@ -332,6 +332,7 @@  OBJS-$(CONFIG_RTMP_PROTOCOL)             += $(RTMP-OBJS-yes)
 
 OBJS-$(CONFIG_RTP_PROTOCOL)              += rtpproto.o
 OBJS-$(CONFIG_TCP_PROTOCOL)              += tcp.o
+OBJS-$(CONFIG_TLS_PROTOCOL)              += tls.o
 OBJS-$(CONFIG_UDP_PROTOCOL)              += udp.o
 
 EXAMPLES  = metadata output
diff --git a/libavformat/allformats.c b/libavformat/allformats.c
index 8e89b2f..d078a15 100644
--- a/libavformat/allformats.c
+++ b/libavformat/allformats.c
@@ -254,5 +254,6 @@  void av_register_all(void)
 #endif
     REGISTER_PROTOCOL (RTP, rtp);
     REGISTER_PROTOCOL (TCP, tcp);
+    REGISTER_PROTOCOL (TLS, tls);
     REGISTER_PROTOCOL (UDP, udp);
 }
diff --git a/libavformat/tls.c b/libavformat/tls.c
new file mode 100644
index 0000000..48ba5be
--- /dev/null
+++ b/libavformat/tls.c
@@ -0,0 +1,330 @@ 
+/*
+ * TLS/SSL Protocol
+ * Copyright (c) 2011 Martin Storsjo
+ *
+ * This file is part of FFmpeg.
+ *
+ * FFmpeg 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 (at your option) any later version.
+ *
+ * FFmpeg is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with FFmpeg; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+#include "avformat.h"
+#include "url.h"
+#include "libavutil/avstring.h"
+#include "libavcodec/internal.h"
+#if CONFIG_GNUTLS
+#include <gnutls/gnutls.h>
+#define TLS_read(c, buf, size)  gnutls_record_recv(c->session, buf, size)
+#define TLS_write(c, buf, size) gnutls_record_send(c->session, buf, size)
+#define TLS_shutdown(c)         gnutls_bye(c->session, GNUTLS_SHUT_RDWR)
+#define TLS_free(c) do { \
+        if (c->session) \
+            gnutls_deinit(c->session); \
+        if (c->cred) \
+            gnutls_certificate_free_credentials(c->cred); \
+    } while (0)
+
+#if HAVE_PTHREADS && GNUTLS_VERSION_NUMBER <= 0x020b00
+#include <gcrypt.h>
+#include <errno.h>
+#include <pthread.h>
+#undef malloc
+#undef free
+GCRY_THREAD_OPTION_PTHREAD_IMPL;
+#endif
+
+static void TLS_init(void)
+{
+    avpriv_lock_avformat();
+    /* Note, these can leak memory if called simultaneously from another
+     * thread not protected by the avpriv_lock_avformat() mutex. */
+#if HAVE_PTHREADS && GNUTLS_VERSION_NUMBER <= 0x020b00
+    gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
+#endif
+    gnutls_global_init();
+    avpriv_unlock_avformat();
+}
+
+static void TLS_deinit(void)
+{
+    avpriv_lock_avformat();
+    gnutls_global_deinit();
+    avpriv_unlock_avformat();
+}
+
+#elif CONFIG_OPENSSL
+#include <openssl/bio.h>
+#include <openssl/ssl.h>
+#include <openssl/err.h>
+#define TLS_read(c, buf, size)  SSL_read(c->ssl,  buf, size)
+#define TLS_write(c, buf, size) SSL_write(c->ssl, buf, size)
+#define TLS_shutdown(c)         SSL_shutdown(c->ssl)
+#define TLS_free(c) do { \
+        if (c->ssl) \
+            SSL_free(c->ssl); \
+        if (c->ctx) \
+            SSL_CTX_free(c->ctx); \
+    } while (0)
+
+#if HAVE_PTHREADS
+static int openssl_init;
+#include <openssl/crypto.h>
+#include <pthread.h>
+#include "libavutil/avutil.h"
+pthread_mutex_t *openssl_mutexes;
+static void openssl_lock(int mode, int type, const char *file, int line)
+{
+    if (mode & CRYPTO_LOCK)
+        pthread_mutex_lock(&openssl_mutexes[type]);
+    else
+        pthread_mutex_unlock(&openssl_mutexes[type]);
+}
+static unsigned long openssl_thread_id(void)
+{
+    return (intptr_t) pthread_self();
+}
+static void openssl_mutex_init(void)
+{
+    if (!openssl_init) {
+        int i;
+        openssl_mutexes = av_malloc(sizeof(pthread_mutex_t) * CRYPTO_num_locks());
+        for (i = 0; i < CRYPTO_num_locks(); i++)
+            pthread_mutex_init(&openssl_mutexes[i], NULL);
+        CRYPTO_set_locking_callback(openssl_lock);
+        CRYPTO_set_id_callback(openssl_thread_id);
+        openssl_init++;
+    }
+}
+static void openssl_mutex_deinit(void)
+{
+    openssl_init--;
+    if (!openssl_init) {
+        int i;
+        CRYPTO_set_locking_callback(NULL);
+        for (i = 0; i < CRYPTO_num_locks(); i++)
+            pthread_mutex_destroy(&openssl_mutexes[i]);
+        av_free(openssl_mutexes);
+    }
+}
+#else
+static void openssl_mutex_init(void)
+{
+}
+static void openssl_mutex_deinit(void)
+{
+}
+#endif
+
+static void TLS_init(void)
+{
+    avpriv_lock_avformat();
+    SSL_library_init();
+    SSL_load_error_strings();
+    openssl_mutex_init();
+    avpriv_unlock_avformat();
+}
+
+static void TLS_deinit(void)
+{
+    avpriv_lock_avformat();
+    openssl_mutex_deinit();
+    avpriv_unlock_avformat();
+}
+
+#endif
+#include "network.h"
+#include "os_support.h"
+#include "internal.h"
+#if HAVE_POLL_H
+#include <poll.h>
+#endif
+
+typedef struct {
+    const AVClass *class;
+    URLContext *tcp;
+#if CONFIG_GNUTLS
+    gnutls_session_t session;
+    gnutls_certificate_credentials_t cred;
+#elif CONFIG_OPENSSL
+    SSL_CTX *ctx;
+    SSL *ssl;
+#endif
+    int fd;
+} TLSContext;
+
+static int do_tls_poll(URLContext *h, int ret)
+{
+    TLSContext *c = h->priv_data;
+    struct pollfd p = { c->fd, 0, 0 };
+#if CONFIG_GNUTLS
+    if (ret != GNUTLS_E_AGAIN && ret != GNUTLS_E_INTERRUPTED) {
+        av_log(NULL, AV_LOG_ERROR, "%s\n", gnutls_strerror(ret));
+        return AVERROR(EIO);
+    }
+    if (gnutls_record_get_direction(c->session))
+        p.events = POLLOUT;
+    else
+        p.events = POLLIN;
+#elif CONFIG_OPENSSL
+    ret = SSL_get_error(c->ssl, ret);
+    if (ret == SSL_ERROR_WANT_READ) {
+        p.events = POLLIN;
+    } else if (ret == SSL_ERROR_WANT_WRITE) {
+        p.events = POLLOUT;
+    } else {
+        av_log(NULL, AV_LOG_ERROR, "%s\n", ERR_error_string(ret, NULL));
+        return AVERROR(EIO);
+    }
+#endif
+    if (h->flags & URL_FLAG_NONBLOCK)
+        return AVERROR(EAGAIN);
+    while (1) {
+        int n = poll(&p, 1, 100);
+        if (n > 0)
+            break;
+        if (url_interrupt_cb())
+            return AVERROR(EINTR);
+    }
+    return 0;
+}
+
+static int tls_open(URLContext *h, const char *uri, int flags)
+{
+    TLSContext *c = h->priv_data;
+    int ret;
+    int port;
+    char buf[200], host[200];
+    int numerichost = 0;
+    struct addrinfo hints = { 0 }, *ai = NULL;
+
+    TLS_init();
+
+    av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0, uri);
+    ff_url_join(buf, sizeof(buf), "tcp", NULL, host, port, NULL);
+
+    hints.ai_flags = AI_NUMERICHOST;
+    if (!getaddrinfo(host, NULL, &hints, &ai)) {
+        numerichost = 1;
+        freeaddrinfo(ai);
+    }
+
+    ret = ffurl_open(&c->tcp, buf, AVIO_FLAG_READ_WRITE);
+    if (ret)
+        goto fail;
+    c->fd = ffurl_get_file_handle(c->tcp);
+
+#if CONFIG_GNUTLS
+    gnutls_init(&c->session, GNUTLS_CLIENT);
+    if (!numerichost)
+        gnutls_server_name_set(c->session, GNUTLS_NAME_DNS, host, strlen(host));
+    gnutls_certificate_allocate_credentials(&c->cred);
+    gnutls_certificate_set_verify_flags(c->cred, 0);
+    gnutls_credentials_set(c->session, GNUTLS_CRD_CERTIFICATE, c->cred);
+    gnutls_transport_set_ptr(c->session, (gnutls_transport_ptr_t)
+                                         (intptr_t) c->fd);
+    gnutls_priority_set_direct(c->session, "NORMAL", NULL);
+    while (1) {
+        ret = gnutls_handshake(c->session);
+        if (ret == 0)
+            break;
+        if ((ret = do_tls_poll(h, ret)) < 0)
+            goto fail;
+    }
+#elif CONFIG_OPENSSL
+    c->ctx = SSL_CTX_new(SSLv3_client_method());
+    if (!c->ctx) {
+        av_log(NULL, AV_LOG_ERROR, "%s\n", ERR_error_string(ERR_get_error(), NULL));
+        ret = AVERROR(EIO);
+        goto fail;
+    }
+    c->ssl = SSL_new(c->ctx);
+    if (!c->ssl) {
+        av_log(NULL, AV_LOG_ERROR, "%s\n", ERR_error_string(ERR_get_error(), NULL));
+        ret = AVERROR(EIO);
+        goto fail;
+    }
+    SSL_set_fd(c->ssl, c->fd);
+    if (!numerichost)
+        SSL_set_tlsext_host_name(c->ssl, host);
+    while (1) {
+        ret = SSL_connect(c->ssl);
+        if (ret > 0)
+            break;
+        if (ret == 0) {
+            av_log(NULL, AV_LOG_ERROR, "Unable to negotiate TLS/SSL session\n");
+            ret = AVERROR(EIO);
+            goto fail;
+        }
+        if ((ret = do_tls_poll(h, ret)) < 0)
+            goto fail;
+    }
+#endif
+    return 0;
+fail:
+    TLS_free(c);
+    if (c->tcp)
+        ffurl_close(c->tcp);
+    TLS_deinit();
+    return ret;
+}
+
+static int tls_read(URLContext *h, uint8_t *buf, int size)
+{
+    TLSContext *c = h->priv_data;
+    while (1) {
+        int ret = TLS_read(c, buf, size);
+        if (ret > 0)
+            return ret;
+        if (ret == 0)
+            return AVERROR(EIO);
+        if ((ret = do_tls_poll(h, ret)) < 0)
+            return ret;
+    }
+    return 0;
+}
+
+static int tls_write(URLContext *h, const uint8_t *buf, int size)
+{
+    TLSContext *c = h->priv_data;
+    while (1) {
+        int ret = TLS_write(c, buf, size);
+        if (ret > 0)
+            return ret;
+        if (ret == 0)
+            return AVERROR(EIO);
+        if ((ret = do_tls_poll(h, ret)) < 0)
+            return ret;
+    }
+    return 0;
+}
+
+static int tls_close(URLContext *h)
+{
+    TLSContext *c = h->priv_data;
+    TLS_shutdown(c);
+    TLS_free(c);
+    ffurl_close(c->tcp);
+    TLS_deinit();
+    return 0;
+}
+
+URLProtocol ff_tls_protocol = {
+    "tls",
+    tls_open,
+    tls_read,
+    tls_write,
+    NULL,
+    tls_close,
+    .priv_data_size = sizeof(TLSContext),
+};
diff --git a/libavformat/version.h b/libavformat/version.h
index b0c1f94..2b1ef95 100644
--- a/libavformat/version.h
+++ b/libavformat/version.h
@@ -24,7 +24,7 @@ 
 #include "libavutil/avutil.h"
 
 #define LIBAVFORMAT_VERSION_MAJOR 53
-#define LIBAVFORMAT_VERSION_MINOR 10
+#define LIBAVFORMAT_VERSION_MINOR 11
 #define LIBAVFORMAT_VERSION_MICRO  0
 
 #define LIBAVFORMAT_VERSION_INT AV_VERSION_INT(LIBAVFORMAT_VERSION_MAJOR, \