httpd.c 65.6 KB
Newer Older
1 2 3
/*****************************************************************************
 * httpd.c
 *****************************************************************************
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
4
 * Copyright (C) 2004-2006 VLC authors and VideoLAN
5
 * Copyright © 2004-2007 Rémi Denis-Courmont
6
 * $Id$
7 8
 *
 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
9
 *          Rémi Denis-Courmont <rem # videolan.org>
10
 *
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
11 12 13
 * This program 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
14 15 16 17
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
18 19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
20
 *
Jean-Baptiste Kempf's avatar
LGPL  
Jean-Baptiste Kempf committed
21 22 23
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
24 25
 *****************************************************************************/

26 27 28 29
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif

30 31
#include <stdatomic.h>

32
#include <vlc_common.h>
Rafaël Carré's avatar
Rafaël Carré committed
33
#include <vlc_httpd.h>
34

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
35 36
#include <assert.h>

37
#include <vlc_list.h>
Clément Stenac's avatar
Clément Stenac committed
38 39
#include <vlc_network.h>
#include <vlc_tls.h>
40
#include <vlc_strings.h>
41
#include <vlc_rand.h>
42
#include <vlc_charset.h>
43
#include <vlc_url.h>
44
#include <vlc_mime.h>
45
#include <vlc_block.h>
46
#include "../libvlc.h"
47

48
#include <string.h>
49
#include <errno.h>
50
#include <unistd.h>
51 52 53
#ifdef HAVE_SYS_UIO_H
# include <sys/uio.h>
#endif
54

55 56 57 58
#ifdef HAVE_POLL
# include <poll.h>
#endif

Rafaël Carré's avatar
Rafaël Carré committed
59
#if defined(_WIN32)
60
#   include <winsock2.h>
61
#elif defined(HAVE_SYS_SOCKET_H)
62 63 64
#   include <sys/socket.h>
#endif

Rafaël Carré's avatar
Rafaël Carré committed
65
#if defined(_WIN32)
66 67 68 69 70 71
/* We need HUGE buffer otherwise TCP throughput is very limited */
#define HTTPD_CL_BUFSIZE 1000000
#else
#define HTTPD_CL_BUFSIZE 10000
#endif

72
static void httpd_ClientDestroy(httpd_client_t *cl);
Rafaël Carré's avatar
Rafaël Carré committed
73
static void httpd_AppendData(httpd_stream_t *stream, uint8_t *p_data, int i_data);
74

75 76 77
/* each host run in his own thread */
struct httpd_host_t
{
78
    struct vlc_common_members obj;
79
    struct vlc_list node;
80 81

    /* ref count */
82
    atomic_uint ref;
83 84

    /* address/port and socket for listening at connections */
85 86
    int         *fds;
    unsigned     nfd;
87
    unsigned     port;
88

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
89
    vlc_thread_t thread;
90
    vlc_mutex_t lock;
91
    vlc_cond_t  wait;
92 93 94 95 96

    /* all registered url (becarefull that 2 httpd_url_t could point at the same url)
     * This will slow down the url research but make my live easier
     * All url will have their cb trigger, but only the first one can answer
     * */
97
    struct vlc_list urls;
98

99 100
    size_t client_count;
    struct vlc_list clients;
101 102

    /* TLS data */
103
    vlc_tls_creds_t *p_tls;
104 105 106
};


107 108 109
struct httpd_url_t
{
    httpd_host_t *host;
110
    struct vlc_list node;
111 112
    vlc_mutex_t lock;

113 114 115
    char      *psz_url;
    char      *psz_user;
    char      *psz_password;
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135

    struct
    {
        httpd_callback_t     cb;
        httpd_callback_sys_t *p_sys;
    } catch[HTTPD_MSG_MAX];
};

/* status */
enum
{
    HTTPD_CLIENT_RECEIVING,
    HTTPD_CLIENT_RECEIVE_DONE,

    HTTPD_CLIENT_SENDING,
    HTTPD_CLIENT_SEND_DONE,

    HTTPD_CLIENT_WAITING,

    HTTPD_CLIENT_DEAD,
136 137 138

    HTTPD_CLIENT_TLS_HS_IN,
    HTTPD_CLIENT_TLS_HS_OUT
139
};
Jean-Paul Saman's avatar
Jean-Paul Saman committed
140

141 142 143
struct httpd_client_t
{
    httpd_url_t *url;
144
    vlc_tls_t   *sock;
145

146
    struct vlc_list node;
147

148 149
    bool    b_stream_mode;
    uint8_t i_state;
150 151 152 153 154 155 156 157 158

    mtime_t i_activity_date;
    mtime_t i_activity_timeout;

    /* buffer for reading header */
    int     i_buffer_size;
    int     i_buffer;
    uint8_t *p_buffer;

159 160 161 162 163 164 165
    /*
     * If waiting for a keyframe, this is the position (in bytes) of the
     * last keyframe the stream saw before this client connected.
     * Otherwise, -1.
     */
    int64_t i_keyframe_wait_to_pass;

166 167 168 169 170 171 172 173 174
    /* */
    httpd_message_t query;  /* client -> httpd */
    httpd_message_t answer; /* httpd -> client */
};


/*****************************************************************************
 * Various functions
 *****************************************************************************/
Rafaël Carré's avatar
Rafaël Carré committed
175
static const char *httpd_ReasonFromCode(unsigned i_code)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
176
{
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
    typedef struct
    {
        unsigned   i_code;
        const char psz_reason[36];
    } http_status_info;

    static const http_status_info http_reason[] =
    {
        /*{ 100, "Continue" },
          { 101, "Switching Protocols" },*/
        { 200, "OK" },
        /*{ 201, "Created" },
          { 202, "Accepted" },
          { 203, "Non-authoritative information" },
          { 204, "No content" },
Steve Lhomme's avatar
Steve Lhomme committed
192
          { 205, "Reset content" },
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
          { 206, "Partial content" },
          { 250, "Low on storage space" },
          { 300, "Multiple choices" },*/
        { 301, "Moved permanently" },
        /*{ 302, "Moved temporarily" },
          { 303, "See other" },
          { 304, "Not modified" },
          { 305, "Use proxy" },
          { 307, "Temporary redirect" },
          { 400, "Bad request" },*/
        { 401, "Unauthorized" },
        /*{ 402, "Payment Required" },*/
        { 403, "Forbidden" },
        { 404, "Not found" },
        { 405, "Method not allowed" },
        /*{ 406, "Not acceptable" },
          { 407, "Proxy authentication required" },
          { 408, "Request time-out" },
          { 409, "Conflict" },
          { 410, "Gone" },
          { 411, "Length required" },
          { 412, "Precondition failed" },
          { 413, "Request entity too large" },
          { 414, "Request-URI too large" },
          { 415, "Unsupported media Type" },
          { 416, "Requested range not satisfiable" },
          { 417, "Expectation failed" },
          { 451, "Parameter not understood" },
          { 452, "Conference not found" },
          { 453, "Not enough bandwidth" },*/
        { 454, "Session not found" },
        { 455, "Method not valid in this State" },
        { 456, "Header field not valid for resource" },
        { 457, "Invalid range" },
        /*{ 458, "Read-only parameter" },*/
        { 459, "Aggregate operation not allowed" },
        { 460, "Non-aggregate operation not allowed" },
        { 461, "Unsupported transport" },
        /*{ 462, "Destination unreachable" },*/
        { 500, "Internal server error" },
        { 501, "Not implemented" },
        /*{ 502, "Bad gateway" },*/
        { 503, "Service unavailable" },
        /*{ 504, "Gateway time-out" },*/
        { 505, "Protocol version not supported" },
        { 551, "Option not supported" },
        { 999, "" }
    };

    static const char psz_fallback_reason[5][16] = {
        "Continue", "OK", "Found", "Client error", "Server error"
    };
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
245

Rafaël Carré's avatar
Rafaël Carré committed
246
    assert((i_code >= 100) && (i_code <= 599));
247

248 249 250
    const http_status_info *p = http_reason;
    while (i_code < p->i_code)
        p++;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
251

252
    if (p->i_code == i_code)
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
253 254 255 256
        return p->psz_reason;

    return psz_fallback_reason[(i_code / 100) - 1];
}
257 258 259 260

static size_t httpd_HtmlError (char **body, int code, const char *url)
{
    const char *errname = httpd_ReasonFromCode (code);
Rafaël Carré's avatar
Rafaël Carré committed
261
    assert (errname);
262

263
    char *url_Encoded = vlc_xml_encode (url ? url : "");
264

265 266 267 268 269 270 271 272 273 274 275 276 277 278
    int res = asprintf (body,
        "<?xml version=\"1.0\" encoding=\"ascii\" ?>\n"
        "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\""
        " \"http://www.w3.org/TR/xhtml10/DTD/xhtml10strict.dtd\">\n"
        "<html lang=\"en\">\n"
        "<head>\n"
        "<title>%s</title>\n"
        "</head>\n"
        "<body>\n"
        "<h1>%d %s%s%s%s</h1>\n"
        "<hr />\n"
        "<a href=\"http://www.videolan.org\">VideoLAN</a>\n"
        "</body>\n"
        "</html>\n", errname, code, errname,
279 280 281
        (url_Encoded ? " (" : ""), (url_Encoded ? url_Encoded : ""), (url_Encoded ? ")" : ""));

    free (url_Encoded);
282

Rafaël Carré's avatar
Rafaël Carré committed
283
    if (res == -1) {
284 285 286 287 288 289 290
        *body = NULL;
        return 0;
    }

    return (size_t)res;
}

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
291

292
/*****************************************************************************
293
 * High Level Functions: httpd_file_t
294 295 296 297 298 299
 *****************************************************************************/
struct httpd_file_t
{
    httpd_url_t *url;
    httpd_file_callback_t pf_fill;
    httpd_file_sys_t      *p_sys;
300
    char mime[1];
301 302
};

303
static int
Rafaël Carré's avatar
Rafaël Carré committed
304 305
httpd_FileCallBack(httpd_callback_sys_t *p_sys, httpd_client_t *cl,
                    httpd_message_t *answer, const httpd_message_t *query)
306 307
{
    httpd_file_t *file = (httpd_file_t*)p_sys;
308
    uint8_t **pp_body, *p_body;
309
    int *pi_body, i_body;
310

Rafaël Carré's avatar
Rafaël Carré committed
311
    if (!answer || !query )
312
        return VLC_SUCCESS;
Rafaël Carré's avatar
Rafaël Carré committed
313

314
    answer->i_proto  = HTTPD_PROTO_HTTP;
Rémi Denis-Courmont's avatar
Fixes  
Rémi Denis-Courmont committed
315
    answer->i_version= 1;
316 317 318 319
    answer->i_type   = HTTPD_MSG_ANSWER;

    answer->i_status = 200;

320
    httpd_MsgAdd(answer, "Content-type",  "%s", file->mime);
Rafaël Carré's avatar
Rafaël Carré committed
321
    httpd_MsgAdd(answer, "Cache-Control", "%s", "no-cache");
322

Rafaël Carré's avatar
Rafaël Carré committed
323
    if (query->i_type != HTTPD_MSG_HEAD) {
324 325
        pp_body = &answer->p_body;
        pi_body = &answer->i_body;
Rafaël Carré's avatar
Rafaël Carré committed
326
    } else {
327 328 329 330 331
        /* The file still needs to be executed. */
        p_body = NULL;
        i_body = 0;
        pp_body = &p_body;
        pi_body = &i_body;
332
    }
333

Rafaël Carré's avatar
Rafaël Carré committed
334
    if (query->i_type == HTTPD_MSG_POST) {
335 336 337
        /* msg_Warn not supported */
    }

338
    uint8_t *psz_args = query->psz_args;
Rafaël Carré's avatar
Rafaël Carré committed
339
    file->pf_fill(file->p_sys, file, psz_args, pp_body, pi_body);
340

Rafaël Carré's avatar
Rafaël Carré committed
341 342
    if (query->i_type == HTTPD_MSG_HEAD)
        free(p_body);
343

344
    /* We respect client request */
345 346
    if (httpd_MsgGet(&cl->query, "Connection") != NULL)
        httpd_MsgAdd(answer, "Connection", "close");
347

Rafaël Carré's avatar
Rafaël Carré committed
348
    httpd_MsgAdd(answer, "Content-Length", "%d", answer->i_body);
349 350 351 352

    return VLC_SUCCESS;
}

Rafaël Carré's avatar
Rafaël Carré committed
353
httpd_file_t *httpd_FileNew(httpd_host_t *host,
354 355
                             const char *psz_url, const char *psz_mime,
                             const char *psz_user, const char *psz_password,
356
                             httpd_file_callback_t pf_fill,
Rafaël Carré's avatar
Rafaël Carré committed
357
                             httpd_file_sys_t *p_sys)
358
{
359 360 361 362 363 364 365
    const char *mime = psz_mime;
    if (mime == NULL || mime[0] == '\0')
        mime = vlc_mime_Ext2Mime(psz_url);

    size_t mimelen = strlen(mime);
    httpd_file_t *file = malloc(sizeof(*file) + mimelen);
    if (unlikely(file == NULL))
Rafaël Carré's avatar
Rafaël Carré committed
366
        return NULL;
367

Rafaël Carré's avatar
Rafaël Carré committed
368 369 370
    file->url = httpd_UrlNew(host, psz_url, psz_user, psz_password);
    if (!file->url) {
        free(file);
371 372 373 374 375
        return NULL;
    }

    file->pf_fill = pf_fill;
    file->p_sys   = p_sys;
376
    memcpy(file->mime, mime, mimelen + 1);
377

Rafaël Carré's avatar
Rafaël Carré committed
378 379 380 381 382 383
    httpd_UrlCatch(file->url, HTTPD_MSG_HEAD, httpd_FileCallBack,
                    (httpd_callback_sys_t*)file);
    httpd_UrlCatch(file->url, HTTPD_MSG_GET,  httpd_FileCallBack,
                    (httpd_callback_sys_t*)file);
    httpd_UrlCatch(file->url, HTTPD_MSG_POST, httpd_FileCallBack,
                    (httpd_callback_sys_t*)file);
384 385 386 387

    return file;
}

Rafaël Carré's avatar
Rafaël Carré committed
388
httpd_file_sys_t *httpd_FileDelete(httpd_file_t *file)
389
{
390 391
    httpd_file_sys_t *p_sys = file->p_sys;

Rafaël Carré's avatar
Rafaël Carré committed
392 393
    httpd_UrlDelete(file->url);
    free(file);
394
    return p_sys;
395 396
}

397 398 399 400 401 402 403 404
/*****************************************************************************
 * High Level Functions: httpd_handler_t (for CGIs)
 *****************************************************************************/
struct httpd_handler_t
{
    httpd_url_t *url;

    httpd_handler_callback_t pf_fill;
405
    void                    *p_sys;
406 407 408

};

409
static int
Rafaël Carré's avatar
Rafaël Carré committed
410 411
httpd_HandlerCallBack(httpd_callback_sys_t *p_sys, httpd_client_t *cl,
                       httpd_message_t *answer, const httpd_message_t *query)
412 413
{
    httpd_handler_t *handler = (httpd_handler_t*)p_sys;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
414
    char psz_remote_addr[NI_MAXNUMERICHOST];
415

Rafaël Carré's avatar
Rafaël Carré committed
416
    if (!answer || !query)
417
        return VLC_SUCCESS;
Rafaël Carré's avatar
Rafaël Carré committed
418

419 420 421 422 423 424
    answer->i_proto  = HTTPD_PROTO_NONE;
    answer->i_type   = HTTPD_MSG_ANSWER;

    /* We do it ourselves, thanks */
    answer->i_status = 0;

Rafaël Carré's avatar
Rafaël Carré committed
425
    if (!httpd_ClientIP(cl, psz_remote_addr, NULL))
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
426
        *psz_remote_addr = '\0';
427

428
    uint8_t *psz_args = query->psz_args;
Rafaël Carré's avatar
Rafaël Carré committed
429
    handler->pf_fill(handler->p_sys, handler, query->psz_url, psz_args,
430 431
                      query->i_type, query->p_body, query->i_body,
                      psz_remote_addr, NULL,
Rafaël Carré's avatar
Rafaël Carré committed
432
                      &answer->p_body, &answer->i_body);
433

Rafaël Carré's avatar
Rafaël Carré committed
434
    if (query->i_type == HTTPD_MSG_HEAD) {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
435
        char *p = (char *)answer->p_body;
436 437

        /* Looks for end of header (i.e. one empty line) */
Rafaël Carré's avatar
Rafaël Carré committed
438 439
        while ((p = strchr(p, '\r')))
            if (p[1] == '\n' && p[2] == '\r' && p[3] == '\n')
440
                break;
441

Rafaël Carré's avatar
Rafaël Carré committed
442
        if (p) {
443
            p[4] = '\0';
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
444
            answer->i_body = strlen((char*)answer->p_body) + 1;
Rafaël Carré's avatar
Rafaël Carré committed
445
            answer->p_body = xrealloc(answer->p_body, answer->i_body);
446 447 448
        }
    }

Rafaël Carré's avatar
Rafaël Carré committed
449
    if (strncmp((char *)answer->p_body, "HTTP/1.", 7)) {
450
        int i_status, i_headers;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
451 452
        char *psz_headers, *psz_new;
        const char *psz_status;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
453

Rafaël Carré's avatar
Rafaël Carré committed
454
        if (!strncmp((char *)answer->p_body, "Status: ", 8)) {
455
            /* Apache-style */
Rafaël Carré's avatar
Rafaël Carré committed
456 457 458
            i_status = strtol((char *)&answer->p_body[8], &psz_headers, 0);
            if (*psz_headers == '\r' || *psz_headers == '\n') psz_headers++;
            if (*psz_headers == '\n') psz_headers++;
459
            i_headers = answer->i_body - (psz_headers - (char *)answer->p_body);
Rafaël Carré's avatar
Rafaël Carré committed
460
        } else {
461
            i_status = 200;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
462
            psz_headers = (char *)answer->p_body;
463 464
            i_headers = answer->i_body;
        }
465

Rafaël Carré's avatar
Rafaël Carré committed
466
        psz_status = httpd_ReasonFromCode(i_status);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
467 468
        answer->i_body = sizeof("HTTP/1.0 xxx \r\n")
                        + strlen(psz_status) + i_headers - 1;
Rafaël Carré's avatar
Rafaël Carré committed
469 470 471 472
        psz_new = (char *)xmalloc(answer->i_body + 1);
        sprintf(psz_new, "HTTP/1.0 %03d %s\r\n", i_status, psz_status);
        memcpy(&psz_new[strlen(psz_new)], psz_headers, i_headers);
        free(answer->p_body);
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
473
        answer->p_body = (uint8_t *)psz_new;
474 475 476 477 478
    }

    return VLC_SUCCESS;
}

Rafaël Carré's avatar
Rafaël Carré committed
479
httpd_handler_t *httpd_HandlerNew(httpd_host_t *host, const char *psz_url,
480 481 482 483
                                  const char *psz_user,
                                  const char *psz_password,
                                  httpd_handler_callback_t pf_fill,
                                  void *p_sys)
484
{
Rafaël Carré's avatar
Rafaël Carré committed
485 486 487
    httpd_handler_t *handler = malloc(sizeof(*handler));
    if (!handler)
        return NULL;
488

Rafaël Carré's avatar
Rafaël Carré committed
489 490 491
    handler->url = httpd_UrlNew(host, psz_url, psz_user, psz_password);
    if (!handler->url) {
        free(handler);
492 493 494 495 496 497
        return NULL;
    }

    handler->pf_fill = pf_fill;
    handler->p_sys   = p_sys;

Rafaël Carré's avatar
Rafaël Carré committed
498 499 500 501 502 503
    httpd_UrlCatch(handler->url, HTTPD_MSG_HEAD, httpd_HandlerCallBack,
                    (httpd_callback_sys_t*)handler);
    httpd_UrlCatch(handler->url, HTTPD_MSG_GET,  httpd_HandlerCallBack,
                    (httpd_callback_sys_t*)handler);
    httpd_UrlCatch(handler->url, HTTPD_MSG_POST, httpd_HandlerCallBack,
                    (httpd_callback_sys_t*)handler);
504 505 506 507

    return handler;
}

508
void *httpd_HandlerDelete(httpd_handler_t *handler)
509
{
510
    void *p_sys = handler->p_sys;
Rafaël Carré's avatar
Rafaël Carré committed
511 512
    httpd_UrlDelete(handler->url);
    free(handler);
513
    return p_sys;
514 515
}

516
/*****************************************************************************
517
 * High Level Functions: httpd_redirect_t
518 519 520 521
 *****************************************************************************/
struct httpd_redirect_t
{
    httpd_url_t *url;
522
    char         dst[1];
523 524
};

Rafaël Carré's avatar
Rafaël Carré committed
525
static int httpd_RedirectCallBack(httpd_callback_sys_t *p_sys,
526
                                   httpd_client_t *cl, httpd_message_t *answer,
Rafaël Carré's avatar
Rafaël Carré committed
527
                                   const httpd_message_t *query)
528 529
{
    httpd_redirect_t *rdir = (httpd_redirect_t*)p_sys;
530
    char *p_body;
531
    (void)cl;
532

Rafaël Carré's avatar
Rafaël Carré committed
533
    if (!answer || !query)
534
        return VLC_SUCCESS;
Rafaël Carré's avatar
Rafaël Carré committed
535

536
    answer->i_proto  = HTTPD_PROTO_HTTP;
Rémi Denis-Courmont's avatar
Fixes  
Rémi Denis-Courmont committed
537
    answer->i_version= 1;
538 539 540
    answer->i_type   = HTTPD_MSG_ANSWER;
    answer->i_status = 301;

541
    answer->i_body = httpd_HtmlError (&p_body, 301, rdir->dst);
542
    answer->p_body = (unsigned char *)p_body;
543 544

    /* XXX check if it's ok or we need to set an absolute url */
545
    httpd_MsgAdd(answer, "Location",  "%s", rdir->dst);
546

Rafaël Carré's avatar
Rafaël Carré committed
547
    httpd_MsgAdd(answer, "Content-Length", "%d", answer->i_body);
548

549 550 551
    if (httpd_MsgGet(&cl->query, "Connection") != NULL)
        httpd_MsgAdd(answer, "Connection", "close");

552 553 554
    return VLC_SUCCESS;
}

Rafaël Carré's avatar
Rafaël Carré committed
555 556
httpd_redirect_t *httpd_RedirectNew(httpd_host_t *host, const char *psz_url_dst,
                                     const char *psz_url_src)
557
{
558 559 560 561
    size_t dstlen = strlen(psz_url_dst);

    httpd_redirect_t *rdir = malloc(sizeof(*rdir) + dstlen);
    if (unlikely(rdir == NULL))
Rafaël Carré's avatar
Rafaël Carré committed
562
        return NULL;
563

Rafaël Carré's avatar
Rafaël Carré committed
564 565 566
    rdir->url = httpd_UrlNew(host, psz_url_src, NULL, NULL);
    if (!rdir->url) {
        free(rdir);
567 568
        return NULL;
    }
569
    memcpy(rdir->dst, psz_url_dst, dstlen + 1);
570

571
    /* Redirect apply for all HTTP request and RTSP DESCRIBE resquest */
Rafaël Carré's avatar
Rafaël Carré committed
572 573 574 575 576 577 578 579
    httpd_UrlCatch(rdir->url, HTTPD_MSG_HEAD, httpd_RedirectCallBack,
                    (httpd_callback_sys_t*)rdir);
    httpd_UrlCatch(rdir->url, HTTPD_MSG_GET, httpd_RedirectCallBack,
                    (httpd_callback_sys_t*)rdir);
    httpd_UrlCatch(rdir->url, HTTPD_MSG_POST, httpd_RedirectCallBack,
                    (httpd_callback_sys_t*)rdir);
    httpd_UrlCatch(rdir->url, HTTPD_MSG_DESCRIBE, httpd_RedirectCallBack,
                    (httpd_callback_sys_t*)rdir);
580 581 582

    return rdir;
}
Rafaël Carré's avatar
Rafaël Carré committed
583
void httpd_RedirectDelete(httpd_redirect_t *rdir)
584
{
Rafaël Carré's avatar
Rafaël Carré committed
585 586
    httpd_UrlDelete(rdir->url);
    free(rdir);
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
}

/*****************************************************************************
 * High Level Funtions: httpd_stream_t
 *****************************************************************************/
struct httpd_stream_t
{
    vlc_mutex_t lock;
    httpd_url_t *url;

    char    *psz_mime;

    /* Header to send as first packet */
    uint8_t *p_header;
    int     i_header;

603 604 605 606 607 608 609 610
    /* Some muxes, in particular the avformat mux, can mark given blocks
     * as keyframes, to ensure that the stream starts with one.
     * (This is particularly important for WebM streaming to certain
     * browsers.) Store if we've ever seen any such keyframe blocks,
     * and if so, the byte position of the start of the last one. */
    bool        b_has_keyframes;
    int64_t     i_last_keyframe_seen_pos;

611 612 613
    /* circular buffer */
    int         i_buffer_size;      /* buffer size, can't be reallocated smaller */
    uint8_t     *p_buffer;          /* buffer */
614
    int64_t     i_buffer_pos;       /* absolute position from beginning */
615
    int64_t     i_buffer_last_pos;  /* a new connection will start with that */
616 617 618 619

    /* custom headers */
    size_t        i_http_headers;
    httpd_header * p_http_headers;
620 621
};

Rafaël Carré's avatar
Rafaël Carré committed
622
static int httpd_StreamCallBack(httpd_callback_sys_t *p_sys,
623
                                 httpd_client_t *cl, httpd_message_t *answer,
Rafaël Carré's avatar
Rafaël Carré committed
624
                                 const httpd_message_t *query)
625 626 627
{
    httpd_stream_t *stream = (httpd_stream_t*)p_sys;

Rafaël Carré's avatar
Rafaël Carré committed
628
    if (!answer || !query || !cl)
629
        return VLC_SUCCESS;
Jean-Paul Saman's avatar
Jean-Paul Saman committed
630

Rafaël Carré's avatar
Rafaël Carré committed
631
    if (answer->i_body_offset > 0) {
632 633
        int     i_pos;

Rafaël Carré's avatar
Rafaël Carré committed
634
        if (answer->i_body_offset >= stream->i_buffer_pos)
635
            return VLC_EGENERIC;    /* wait, no data available */
Rafaël Carré's avatar
Rafaël Carré committed
636 637 638

        if (cl->i_keyframe_wait_to_pass >= 0) {
            if (stream->i_last_keyframe_seen_pos <= cl->i_keyframe_wait_to_pass)
639 640 641 642 643 644 645
                /* still waiting for the next keyframe */
                return VLC_EGENERIC;

            /* seek to the new keyframe */
            answer->i_body_offset = stream->i_last_keyframe_seen_pos;
            cl->i_keyframe_wait_to_pass = -1;
        }
Rafaël Carré's avatar
Rafaël Carré committed
646 647 648

        if (answer->i_body_offset + stream->i_buffer_size < stream->i_buffer_pos)
            answer->i_body_offset = stream->i_buffer_last_pos; /* this client isn't fast enough */
649 650

        i_pos   = answer->i_body_offset % stream->i_buffer_size;
Rafaël Carré's avatar
Rafaël Carré committed
651 652 653
        int64_t i_write = stream->i_buffer_pos - answer->i_body_offset;

        if (i_write > HTTPD_CL_BUFSIZE)
654
            i_write = HTTPD_CL_BUFSIZE;
Rafaël Carré's avatar
Rafaël Carré committed
655
        else if (i_write <= 0)
656 657
            return VLC_EGENERIC;    /* wait, no data available */

658
        /* Don't go past the end of the circular buffer */
Rafaël Carré's avatar
Rafaël Carré committed
659
        i_write = __MIN(i_write, stream->i_buffer_size - i_pos);
660

661 662 663 664 665 666
        /* using HTTPD_MSG_ANSWER -> data available */
        answer->i_proto  = HTTPD_PROTO_HTTP;
        answer->i_version= 0;
        answer->i_type   = HTTPD_MSG_ANSWER;

        answer->i_body = i_write;
Rafaël Carré's avatar
Rafaël Carré committed
667 668
        answer->p_body = xmalloc(i_write);
        memcpy(answer->p_body, &stream->p_buffer[i_pos], i_write);
669 670 671 672

        answer->i_body_offset += i_write;

        return VLC_SUCCESS;
Rafaël Carré's avatar
Rafaël Carré committed
673
    } else {
674 675 676 677 678 679
        answer->i_proto  = HTTPD_PROTO_HTTP;
        answer->i_version= 0;
        answer->i_type   = HTTPD_MSG_ANSWER;

        answer->i_status = 200;

680 681 682
        bool b_has_content_type = false;
        bool b_has_cache_control = false;

Rafaël Carré's avatar
Rafaël Carré committed
683 684 685
        vlc_mutex_lock(&stream->lock);
        for (size_t i = 0; i < stream->i_http_headers; i++)
            if (strncasecmp(stream->p_http_headers[i].name, "Content-Length", 14)) {
686
                httpd_MsgAdd(answer, stream->p_http_headers[i].name, "%s",
Rafaël Carré's avatar
Rafaël Carré committed
687
                              stream->p_http_headers[i].value);
688

Rafaël Carré's avatar
Rafaël Carré committed
689
                if (!strncasecmp(stream->p_http_headers[i].name, "Content-Type", 12))
690
                    b_has_content_type = true;
Rafaël Carré's avatar
Rafaël Carré committed
691
                else if (!strncasecmp(stream->p_http_headers[i].name, "Cache-Control", 13))
692 693
                    b_has_cache_control = true;
            }
Rafaël Carré's avatar
Rafaël Carré committed
694
        vlc_mutex_unlock(&stream->lock);
695

Rafaël Carré's avatar
Rafaël Carré committed
696
        if (query->i_type != HTTPD_MSG_HEAD) {
697
            cl->b_stream_mode = true;
Rafaël Carré's avatar
Rafaël Carré committed
698
            vlc_mutex_lock(&stream->lock);
699
            /* Send the header */
Rafaël Carré's avatar
Rafaël Carré committed
700
            if (stream->i_header > 0) {
701
                answer->i_body = stream->i_header;
Rafaël Carré's avatar
Rafaël Carré committed
702 703
                answer->p_body = xmalloc(stream->i_header);
                memcpy(answer->p_body, stream->p_header, stream->i_header);
704 705
            }
            answer->i_body_offset = stream->i_buffer_last_pos;
Rafaël Carré's avatar
Rafaël Carré committed
706
            if (stream->b_has_keyframes)
707 708 709
                cl->i_keyframe_wait_to_pass = stream->i_last_keyframe_seen_pos;
            else
                cl->i_keyframe_wait_to_pass = -1;
Rafaël Carré's avatar
Rafaël Carré committed
710 711 712
            vlc_mutex_unlock(&stream->lock);
        } else {
            httpd_MsgAdd(answer, "Content-Length", "0");
713
            answer->i_body_offset = 0;
714 715
        }

716
        /* FIXME: move to http access_output */
Rafaël Carré's avatar
Rafaël Carré committed
717
        if (!strcmp(stream->psz_mime, "video/x-ms-asf-stream")) {
718
            bool b_xplaystream = false;
719

Rafaël Carré's avatar
Rafaël Carré committed
720 721 722 723 724 725
            httpd_MsgAdd(answer, "Content-type", "application/octet-stream");
            httpd_MsgAdd(answer, "Server", "Cougar 4.1.0.3921");
            httpd_MsgAdd(answer, "Pragma", "no-cache");
            httpd_MsgAdd(answer, "Pragma", "client-id=%lu",
                          vlc_mrand48()&0x7fff);
            httpd_MsgAdd(answer, "Pragma", "features=\"broadcast\"");
726

727
            /* Check if there is a xPlayStrm=1 */
Rafaël Carré's avatar
Rafaël Carré committed
728 729 730
            for (size_t i = 0; i < query->i_headers; i++)
                if (!strcasecmp(query->p_headers[i].name,  "Pragma") &&
                    strstr(query->p_headers[i].value, "xPlayStrm=1"))
731
                    b_xplaystream = true;
732

Rafaël Carré's avatar
Rafaël Carré committed
733
            if (!b_xplaystream)
734
                answer->i_body_offset = 0;
Rafaël Carré's avatar
Rafaël Carré committed
735
        } else if (!b_has_content_type)
736
            httpd_MsgAdd(answer, "Content-type", "%s", stream->psz_mime);
Rafaël Carré's avatar
Rafaël Carré committed
737 738 739

        if (!b_has_cache_control)
            httpd_MsgAdd(answer, "Cache-Control", "no-cache");
740 741 742

        httpd_MsgAdd(answer, "Connection", "close");

743 744 745 746
        return VLC_SUCCESS;
    }
}

Rafaël Carré's avatar
Rafaël Carré committed
747
httpd_stream_t *httpd_StreamNew(httpd_host_t *host,
748
                                 const char *psz_url, const char *psz_mime,
Rafaël Carré's avatar
Rafaël Carré committed
749
                                 const char *psz_user, const char *psz_password)
750
{
Rafaël Carré's avatar
Rafaël Carré committed
751 752 753
    httpd_stream_t *stream = malloc(sizeof(*stream));
    if (!stream)
        return NULL;
754

Rafaël Carré's avatar
Rafaël Carré committed
755 756 757
    stream->url = httpd_UrlNew(host, psz_url, psz_user, psz_password);
    if (!stream->url) {
        free(stream);
758 759
        return NULL;
    }
Rafaël Carré's avatar
Rafaël Carré committed
760 761

    vlc_mutex_init(&stream->lock);
762 763 764
    if (psz_mime == NULL || psz_mime[0] == '\0')
        psz_mime = vlc_mime_Ext2Mime(psz_url);
    stream->psz_mime = xstrdup(psz_mime);
Rafaël Carré's avatar
Rafaël Carré committed
765

766 767 768
    stream->i_header = 0;
    stream->p_header = NULL;
    stream->i_buffer_size = 5000000;    /* 5 Mo per stream */
Rafaël Carré's avatar
Rafaël Carré committed
769
    stream->p_buffer = xmalloc(stream->i_buffer_size);
770 771
    /* We set to 1 to make life simpler
     * (this way i_body_offset can never be 0) */
772 773
    stream->i_buffer_pos = 1;
    stream->i_buffer_last_pos = 1;
774 775
    stream->b_has_keyframes = false;
    stream->i_last_keyframe_seen_pos = 0;
776 777
    stream->i_http_headers = 0;
    stream->p_http_headers = NULL;
778

Rafaël Carré's avatar
Rafaël Carré committed
779 780 781 782 783 784
    httpd_UrlCatch(stream->url, HTTPD_MSG_HEAD, httpd_StreamCallBack,
                    (httpd_callback_sys_t*)stream);
    httpd_UrlCatch(stream->url, HTTPD_MSG_GET, httpd_StreamCallBack,
                    (httpd_callback_sys_t*)stream);
    httpd_UrlCatch(stream->url, HTTPD_MSG_POST, httpd_StreamCallBack,
                    (httpd_callback_sys_t*)stream);
785 786 787 788

    return stream;
}

Rafaël Carré's avatar
Rafaël Carré committed
789
int httpd_StreamHeader(httpd_stream_t *stream, uint8_t *p_data, int i_data)
790
{
Rafaël Carré's avatar
Rafaël Carré committed
791 792
    vlc_mutex_lock(&stream->lock);
    free(stream->p_header);
793 794
    stream->p_header = NULL;

795
    stream->i_header = i_data;
Rafaël Carré's avatar
Rafaël Carré committed
796 797 798
    if (i_data > 0) {
        stream->p_header = xmalloc(i_data);
        memcpy(stream->p_header, p_data, i_data);
799
    }
Rafaël Carré's avatar
Rafaël Carré committed
800
    vlc_mutex_unlock(&stream->lock);
801 802 803 804

    return VLC_SUCCESS;
}

Rafaël Carré's avatar
Rafaël Carré committed
805
static void httpd_AppendData(httpd_stream_t *stream, uint8_t *p_data, int i_data)
806
{
807 808
    int i_pos = stream->i_buffer_pos % stream->i_buffer_size;
    int i_count = i_data;
Rafaël Carré's avatar
Rafaël Carré committed
809 810
    while (i_count > 0) {
        int i_copy = __MIN(i_count, stream->i_buffer_size - i_pos);
811 812

        /* Ok, we can't go past the end of our buffer */
Rafaël Carré's avatar
Rafaël Carré committed
813
        memcpy(&stream->p_buffer[i_pos], p_data, i_copy);
814

Rafaël Carré's avatar
Rafaël Carré committed
815
        i_pos = (i_pos + i_copy) % stream->i_buffer_size;
816 817 818 819 820
        i_count -= i_copy;
        p_data  += i_copy;
    }

    stream->i_buffer_pos += i_data;
821 822
}

Rafaël Carré's avatar
Rafaël Carré committed
823
int httpd_StreamSend(httpd_stream_t *stream, const block_t *p_block)
824
{
Rafaël Carré's avatar
Rafaël Carré committed
825
    if (!p_block || !p_block->p_buffer)
826
        return VLC_SUCCESS;
Rafaël Carré's avatar
Rafaël Carré committed
827 828

    vlc_mutex_lock(&stream->lock);
829 830 831 832

    /* save this pointer (to be used by new connection) */
    stream->i_buffer_last_pos = stream->i_buffer_pos;

Rafaël Carré's avatar
Rafaël Carré committed
833
    if (p_block->i_flags & BLOCK_FLAG_TYPE_I) {
834 835 836 837
        stream->b_has_keyframes = true;
        stream->i_last_keyframe_seen_pos = stream->i_buffer_pos;
    }

Rafaël Carré's avatar
Rafaël Carré committed
838
    httpd_AppendData(stream, p_block->p_buffer, p_block->i_buffer);
839

Rafaël Carré's avatar
Rafaël Carré committed
840
    vlc_mutex_unlock(&stream->lock);
841 842 843
    return VLC_SUCCESS;
}

Rafaël Carré's avatar
Rafaël Carré committed
844
void httpd_StreamDelete(httpd_stream_t *stream)
845
{
Rafaël Carré's avatar
Rafaël Carré committed
846 847 848 849 850 851 852 853 854 855 856
    httpd_UrlDelete(stream->url);
    for (size_t i = 0; i < stream->i_http_headers; i++) {
        free(stream->p_http_headers[i].name);
        free(stream->p_http_headers[i].value);
    }
    free(stream->p_http_headers);
    vlc_mutex_destroy(&stream->lock);
    free(stream->psz_mime);
    free(stream->p_header);
    free(stream->p_buffer);
    free(stream);
857 858 859 860 861
}

/*****************************************************************************
 * Low level
 *****************************************************************************/
Rafaël Carré's avatar
Rafaël Carré committed
862 863 864
static void* httpd_HostThread(void *);
static httpd_host_t *httpd_HostCreate(vlc_object_t *, const char *,
                                       const char *, vlc_tls_creds_t *);
865 866

/* create a new host */
Rafaël Carré's avatar
Rafaël Carré committed
867
httpd_host_t *vlc_http_HostNew(vlc_object_t *p_this)
868
{
Rafaël Carré's avatar
Rafaël Carré committed
869
    return httpd_HostCreate(p_this, "http-host", "http-port", NULL);
870 871
}

Rafaël Carré's avatar
Rafaël Carré committed
872
httpd_host_t *vlc_https_HostNew(vlc_object_t *obj)
873
{
Rafaël Carré's avatar
Rafaël Carré committed
874 875 876
    char *cert = var_InheritString(obj, "http-cert");
    if (!cert) {
        msg_Err(obj, "HTTP/TLS certificate not specified!");
877 878 879
        return NULL;
    }

Rafaël Carré's avatar
Rafaël Carré committed
880 881
    char *key = var_InheritString(obj, "http-key");
    vlc_tls_creds_t *tls = vlc_tls_ServerCreate(obj, cert, key);
882

Rafaël Carré's avatar
Rafaël Carré committed
883 884 885 886 887
    if (!tls) {
        msg_Err(obj, "HTTP/TLS certificate error (%s and %s)",
                 cert, key ? key : cert);
        free(key);
        free(cert);
888 889
        return NULL;
    }
Rafaël Carré's avatar
Rafaël Carré committed
890 891
    free(key);
    free(cert);
892

Rafaël Carré's avatar
Rafaël Carré committed
893
    return httpd_HostCreate(obj, "http-host", "https-port", tls);
894 895
}

Rafaël Carré's avatar
Rafaël Carré committed
896
httpd_host_t *vlc_rtsp_HostNew(vlc_object_t *p_this)
897
{
Rafaël Carré's avatar
Rafaël Carré committed
898
    return httpd_HostCreate(p_this, "rtsp-host", "rtsp-port", NULL);
899 900
}

901
static struct httpd
902 903
{
    vlc_mutex_t  mutex;
904 905
    struct vlc_list hosts;
} httpd = { VLC_STATIC_MUTEX, VLC_LIST_INITIALIZER(&httpd.hosts) };
906

Rafaël Carré's avatar
Rafaël Carré committed
907
static httpd_host_t *httpd_HostCreate(vlc_object_t *p_this,
908 909
                                       const char *hostvar,
                                       const char *portvar,
Rafaël Carré's avatar