1/*
2 * TLS/SSL Protocol
3 * Copyright (c) 2011 Martin Storsjo
4 *
5 * This file is part of Libav.
6 *
7 * Libav is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * Libav is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with Libav; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22#include "avformat.h"
23#include "url.h"
24#include "libavutil/avstring.h"
25#if CONFIG_GNUTLS
26#include <gnutls/gnutls.h>
27#define TLS_read(c, buf, size)  gnutls_record_recv(c->session, buf, size)
28#define TLS_write(c, buf, size) gnutls_record_send(c->session, buf, size)
29#define TLS_shutdown(c)         gnutls_bye(c->session, GNUTLS_SHUT_RDWR)
30#define TLS_free(c) do { \
31        if (c->session) \
32            gnutls_deinit(c->session); \
33        if (c->cred) \
34            gnutls_certificate_free_credentials(c->cred); \
35    } while (0)
36#elif CONFIG_OPENSSL
37#include <openssl/bio.h>
38#include <openssl/ssl.h>
39#include <openssl/err.h>
40#define TLS_read(c, buf, size)  SSL_read(c->ssl,  buf, size)
41#define TLS_write(c, buf, size) SSL_write(c->ssl, buf, size)
42#define TLS_shutdown(c)         SSL_shutdown(c->ssl)
43#define TLS_free(c) do { \
44        if (c->ssl) \
45            SSL_free(c->ssl); \
46        if (c->ctx) \
47            SSL_CTX_free(c->ctx); \
48    } while (0)
49#endif
50#include "network.h"
51#include "os_support.h"
52#include "internal.h"
53#if HAVE_POLL_H
54#include <poll.h>
55#endif
56
57typedef struct {
58    const AVClass *class;
59    URLContext *tcp;
60#if CONFIG_GNUTLS
61    gnutls_session_t session;
62    gnutls_certificate_credentials_t cred;
63#elif CONFIG_OPENSSL
64    SSL_CTX *ctx;
65    SSL *ssl;
66#endif
67    int fd;
68} TLSContext;
69
70static int do_tls_poll(URLContext *h, int ret)
71{
72    TLSContext *c = h->priv_data;
73    struct pollfd p = { c->fd, 0, 0 };
74#if CONFIG_GNUTLS
75    if (ret != GNUTLS_E_AGAIN && ret != GNUTLS_E_INTERRUPTED) {
76        av_log(h, AV_LOG_ERROR, "%s\n", gnutls_strerror(ret));
77        return AVERROR(EIO);
78    }
79    if (gnutls_record_get_direction(c->session))
80        p.events = POLLOUT;
81    else
82        p.events = POLLIN;
83#elif CONFIG_OPENSSL
84    ret = SSL_get_error(c->ssl, ret);
85    if (ret == SSL_ERROR_WANT_READ) {
86        p.events = POLLIN;
87    } else if (ret == SSL_ERROR_WANT_WRITE) {
88        p.events = POLLOUT;
89    } else {
90        av_log(h, AV_LOG_ERROR, "%s\n", ERR_error_string(ERR_get_error(), NULL));
91        return AVERROR(EIO);
92    }
93#endif
94    if (h->flags & AVIO_FLAG_NONBLOCK)
95        return AVERROR(EAGAIN);
96    while (1) {
97        int n = poll(&p, 1, 100);
98        if (n > 0)
99            break;
100        if (ff_check_interrupt(&h->interrupt_callback))
101            return AVERROR(EINTR);
102    }
103    return 0;
104}
105
106static int tls_open(URLContext *h, const char *uri, int flags)
107{
108    TLSContext *c = h->priv_data;
109    int ret;
110    int port;
111    char buf[200], host[200];
112    int numerichost = 0;
113    struct addrinfo hints = { 0 }, *ai = NULL;
114    const char *proxy_path;
115    int use_proxy;
116
117    ff_tls_init();
118
119    proxy_path = getenv("http_proxy");
120    use_proxy = (proxy_path != NULL) && !getenv("no_proxy") &&
121        av_strstart(proxy_path, "http://", NULL);
122
123    av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0, uri);
124    ff_url_join(buf, sizeof(buf), "tcp", NULL, host, port, NULL);
125
126    hints.ai_flags = AI_NUMERICHOST;
127    if (!getaddrinfo(host, NULL, &hints, &ai)) {
128        numerichost = 1;
129        freeaddrinfo(ai);
130    }
131
132    if (use_proxy) {
133        char proxy_host[200], proxy_auth[200], dest[200];
134        int proxy_port;
135        av_url_split(NULL, 0, proxy_auth, sizeof(proxy_auth),
136                     proxy_host, sizeof(proxy_host), &proxy_port, NULL, 0,
137                     proxy_path);
138        ff_url_join(dest, sizeof(dest), NULL, NULL, host, port, NULL);
139        ff_url_join(buf, sizeof(buf), "httpproxy", proxy_auth, proxy_host,
140                    proxy_port, "/%s", dest);
141    }
142
143    ret = ffurl_open(&c->tcp, buf, AVIO_FLAG_READ_WRITE,
144                     &h->interrupt_callback, NULL);
145    if (ret)
146        goto fail;
147    c->fd = ffurl_get_file_handle(c->tcp);
148
149#if CONFIG_GNUTLS
150    gnutls_init(&c->session, GNUTLS_CLIENT);
151    if (!numerichost)
152        gnutls_server_name_set(c->session, GNUTLS_NAME_DNS, host, strlen(host));
153    gnutls_certificate_allocate_credentials(&c->cred);
154    gnutls_certificate_set_verify_flags(c->cred, 0);
155    gnutls_credentials_set(c->session, GNUTLS_CRD_CERTIFICATE, c->cred);
156    gnutls_transport_set_ptr(c->session, (gnutls_transport_ptr_t)
157                                         (intptr_t) c->fd);
158    gnutls_priority_set_direct(c->session, "NORMAL", NULL);
159    while (1) {
160        ret = gnutls_handshake(c->session);
161        if (ret == 0)
162            break;
163        if ((ret = do_tls_poll(h, ret)) < 0)
164            goto fail;
165    }
166#elif CONFIG_OPENSSL
167    c->ctx = SSL_CTX_new(TLSv1_client_method());
168    if (!c->ctx) {
169        av_log(h, AV_LOG_ERROR, "%s\n", ERR_error_string(ERR_get_error(), NULL));
170        ret = AVERROR(EIO);
171        goto fail;
172    }
173    c->ssl = SSL_new(c->ctx);
174    if (!c->ssl) {
175        av_log(h, AV_LOG_ERROR, "%s\n", ERR_error_string(ERR_get_error(), NULL));
176        ret = AVERROR(EIO);
177        goto fail;
178    }
179    SSL_set_fd(c->ssl, c->fd);
180    if (!numerichost)
181        SSL_set_tlsext_host_name(c->ssl, host);
182    while (1) {
183        ret = SSL_connect(c->ssl);
184        if (ret > 0)
185            break;
186        if (ret == 0) {
187            av_log(h, AV_LOG_ERROR, "Unable to negotiate TLS/SSL session\n");
188            ret = AVERROR(EIO);
189            goto fail;
190        }
191        if ((ret = do_tls_poll(h, ret)) < 0)
192            goto fail;
193    }
194#endif
195    return 0;
196fail:
197    TLS_free(c);
198    if (c->tcp)
199        ffurl_close(c->tcp);
200    ff_tls_deinit();
201    return ret;
202}
203
204static int tls_read(URLContext *h, uint8_t *buf, int size)
205{
206    TLSContext *c = h->priv_data;
207    while (1) {
208        int ret = TLS_read(c, buf, size);
209        if (ret > 0)
210            return ret;
211        if (ret == 0)
212            return AVERROR(EIO);
213        if ((ret = do_tls_poll(h, ret)) < 0)
214            return ret;
215    }
216    return 0;
217}
218
219static int tls_write(URLContext *h, const uint8_t *buf, int size)
220{
221    TLSContext *c = h->priv_data;
222    while (1) {
223        int ret = TLS_write(c, buf, size);
224        if (ret > 0)
225            return ret;
226        if (ret == 0)
227            return AVERROR(EIO);
228        if ((ret = do_tls_poll(h, ret)) < 0)
229            return ret;
230    }
231    return 0;
232}
233
234static int tls_close(URLContext *h)
235{
236    TLSContext *c = h->priv_data;
237    TLS_shutdown(c);
238    TLS_free(c);
239    ffurl_close(c->tcp);
240    ff_tls_deinit();
241    return 0;
242}
243
244URLProtocol ff_tls_protocol = {
245    .name           = "tls",
246    .url_open       = tls_open,
247    .url_read       = tls_read,
248    .url_write      = tls_write,
249    .url_close      = tls_close,
250    .priv_data_size = sizeof(TLSContext),
251    .flags          = URL_PROTOCOL_FLAG_NETWORK,
252};
253