httpd.c 84 KB
Newer Older
1
2
3
/*****************************************************************************
 * httpd.c
 *****************************************************************************
4
 * Copyright (C) 2004-2005 the VideoLAN team
5
 * $Id$
6
7
 *
 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8
 *          Rémi Denis-Courmont <rem # videolan.org>
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (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
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
 *****************************************************************************/

#include <stdlib.h>
#include <vlc/vlc.h>

28
29
#ifdef ENABLE_HTTPD

30
#include "vlc_httpd.h"
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
31
#include "network.h"
32
#include "vlc_tls.h"
33
#include "vlc_acl.h"
34

35
#include <string.h>
36
37
#include <errno.h>

38
39
40
#ifdef HAVE_UNISTD_H
#   include <unistd.h>
#endif
gbazin's avatar
gbazin committed
41
42
43
44

#ifdef HAVE_FCNTL_H
#   include <fcntl.h>
#endif
45
46
47
48
49
50
51
52
53

#if defined( UNDER_CE )
#   include <winsock.h>
#elif defined( WIN32 )
#   include <winsock2.h>
#   include <ws2tcpip.h>
#else
#   include <netdb.h>                                         /* hostent ... */
#   include <sys/socket.h>
54
/* FIXME: should not be needed */
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
#   include <netinet/in.h>
#   ifdef HAVE_ARPA_INET_H
#       include <arpa/inet.h>                    /* inet_ntoa(), inet_aton() */
#   endif
#endif

#if 0
typedef struct httpd_t          httpd_t;

typedef struct httpd_host_t     httpd_host_t;
typedef struct httpd_url_t      httpd_url_t;
typedef struct httpd_client_t   httpd_client_t;

enum
{
    HTTPD_MSG_NONE,

    /* answer */
    HTTPD_MSG_ANSWER,

    /* channel communication */
    HTTPD_MSG_CHANNEL,

    /* http request */
    HTTPD_MSG_GET,
    HTTPD_MSG_HEAD,
    HTTPD_MSG_POST,

    /* rtsp request */
    HTTPD_MSG_OPTIONS,
    HTTPD_MSG_DESCRIBE,
    HTTPD_MSG_SETUP,
    HTTPD_MSG_PLAY,
    HTTPD_MSG_PAUSE,
    HTTPD_MSG_TEARDOWN,

    /* just to track the count of MSG */
    HTTPD_MSG_MAX
};

enum
{
    HTTPD_PROTO_NONE,
    HTTPD_PROTO_HTTP,
    HTTPD_PROTO_RTSP,
};

typedef struct
{
    httpd_client_t *cl; /* NULL if not throught a connection e vlc internal */

    int     i_type;
    int     i_proto;
    int     i_version;

    /* for an answer */
    int     i_status;
    char    *psz_status;

    /* for a query */
    char    *psz_url;
    char    *psz_args;  /* FIXME find a clean way to handle GET(psz_args) and POST(body) through the same code */

    /* for rtp over rtsp */
    int     i_channel;

    /* options */
    int     i_name;
    char    **name;
    int     i_value;
    char    **value;

    /* body */
    int64_t i_body_offset;
    int     i_body;
    uint8_t *p_body;

} httpd_message_t;

typedef struct httpd_callback_sys_t httpd_callback_sys_t;
/* answer could be null, int this case no answer is requested */
typedef int (*httpd_callback_t)( httpd_callback_sys_t *, httpd_client_t *, httpd_message_t *answer, httpd_message_t *query );


/* create a new host */
httpd_host_t *httpd_HostNew( vlc_object_t *, char *psz_host, int i_port );
/* delete a host */
void          httpd_HostDelete( httpd_host_t * );

/* register a new url */
httpd_url_t *httpd_UrlNew( httpd_host_t *, char *psz_url );
/* register callback on a url */
int          httpd_UrlCatch( httpd_url_t *, int i_msg,
                             httpd_callback_t, httpd_callback_sys_t * );
/* delete an url */
void         httpd_UrlDelete( httpd_url_t * );


153
154
155
void httpd_ClientModeStream( httpd_client_t *cl );
void httpd_ClientModeBidir( httpd_client_t *cl );
static void httpd_ClientClean( httpd_client_t *cl );
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198

/* High level */
typedef struct httpd_file_t     httpd_file_t;
typedef struct httpd_file_sys_t httpd_file_sys_t;
typedef int (*httpd_file_callback_t)( httpd_file_sys_t*, httpd_file_t *, uint8_t *psz_request, uint8_t **pp_data, int *pi_data );
httpd_file_t *httpd_FileNew( httpd_host_t *,
                             char *psz_url, char *psz_mime,
                             char *psz_user, char *psz_password,
                             httpd_file_callback_t pf_fill,
                             httpd_file_sys_t *p_sys );
void         httpd_FileDelete( httpd_file_t * );

typedef struct httpd_redirect_t httpd_redirect_t;
httpd_redirect_t *httpd_RedirectNew( httpd_host_t *, char *psz_url_dst, char *psz_url_src );
void              httpd_RedirectDelete( httpd_redirect_t * );

#if 0
typedef struct httpd_stream_t httpd_stream_t;
httpd_stream_t *httpd_StreamNew( httpd_host_t * );
int             httpd_StreamHeader( httpd_stream_t *, uint8_t *p_data, int i_data );
int             httpd_StreamSend( httpd_stream_t *, uint8_t *p_data, int i_data );
void            httpd_StreamDelete( httpd_stream_t * );
#endif

/* Msg functions facilities */
void         httpd_MsgInit( httpd_message_t * );
void         httpd_MsgAdd( httpd_message_t *, char *psz_name, char *psz_value, ... );
/* return "" if not found. The string is not allocated */
char        *httpd_MsgGet( httpd_message_t *, char *psz_name );
void         httpd_MsgClean( httpd_message_t * );
#endif

#if 0
struct httpd_t
{
    VLC_COMMON_MEMBERS

    /* vlc_mutex_t  lock; */
    int          i_host;
    httpd_host_t **host;
};
#endif

199
200
static void httpd_ClientClean( httpd_client_t *cl );

201
202
203
204
205
206
207
208
209
210
211
/* each host run in his own thread */
struct httpd_host_t
{
    VLC_COMMON_MEMBERS

    httpd_t     *httpd;

    /* ref count */
    int         i_ref;

    /* address/port and socket for listening at connections */
212
213
214
    char        *psz_hostname;
    int         i_port;
    int         *fd;
215
216
217
218
219
220
221
222
223
224
225
226

    vlc_mutex_t lock;

    /* 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
     * */
    int         i_url;
    httpd_url_t **url;

    int            i_client;
    httpd_client_t **client;
227
228
229
    
    /* TLS data */
    tls_server_t *p_tls;
230
231
232
233
234
235
236
237
};

struct httpd_url_t
{
    httpd_host_t *host;

    vlc_mutex_t lock;

238
239
240
241
    char      *psz_url;
    char      *psz_user;
    char      *psz_password;
    vlc_acl_t *p_acl;
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261

    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,
262
263
264

    HTTPD_CLIENT_TLS_HS_IN,
    HTTPD_CLIENT_TLS_HS_OUT
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
};
/* mode */
enum
{
    HTTPD_CLIENT_FILE,      /* default */
    HTTPD_CLIENT_STREAM,    /* regulary get data from cb */
    HTTPD_CLIENT_BIDIR,     /* check for reading and get data from cb */
};

struct httpd_client_t
{
    httpd_url_t *url;

    int     i_ref;

280
281
    struct  sockaddr_storage sock;
    int     i_sock_size;
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
    int     fd;

    int     i_mode;
    int     i_state;
    int     b_read_waiting; /* stop as soon as possible sending */

    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;

    /* */
    httpd_message_t query;  /* client -> httpd */
    httpd_message_t answer; /* httpd -> client */
299
300
301
    
    /* TLS data */
    tls_session_t *p_tls;
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
};


/*****************************************************************************
 * Various functions
 *****************************************************************************/
/*char b64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";*/
static void b64_decode( char *dest, char *src )
{
    int  i_level;
    int  last = 0;
    int  b64[256] = {
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 00-0F */
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 10-1F */
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,62,-1,-1,-1,63,  /* 20-2F */
        52,53,54,55,56,57,58,59,60,61,-1,-1,-1,-1,-1,-1,  /* 30-3F */
        -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12,13,14,  /* 40-4F */
        15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,  /* 50-5F */
        -1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,  /* 60-6F */
        41,42,43,44,45,46,47,48,49,50,51,-1,-1,-1,-1,-1,  /* 70-7F */
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 80-8F */
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* 90-9F */
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* A0-AF */
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* B0-BF */
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* C0-CF */
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* D0-DF */
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,  /* E0-EF */
        -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1   /* F0-FF */
        };

    for( i_level = 0; *src != '\0'; src++ )
    {
        int  c;

        c = b64[(unsigned int)*src];
        if( c == -1 )
        {
            continue;
        }

        switch( i_level )
        {
            case 0:
                i_level++;
                break;
            case 1:
                *dest++ = ( last << 2 ) | ( ( c >> 4)&0x03 );
                i_level++;
                break;
            case 2:
                *dest++ = ( ( last << 4 )&0xf0 ) | ( ( c >> 2 )&0x0f );
                i_level++;
                break;
            case 3:
                *dest++ = ( ( last &0x03 ) << 6 ) | c;
                i_level = 0;
        }
        last = c;
    }

    *dest = '\0';
}

static struct
{
367
368
    const char *psz_ext;
    const char *psz_mime;
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
} http_mime[] =
{
    { ".htm",   "text/html" },
    { ".html",  "text/html" },
    { ".txt",   "text/plain" },
    { ".xml",   "text/xml" },
    { ".dtd",   "text/dtd" },

    { ".css",   "text/css" },

    /* image mime */
    { ".gif",   "image/gif" },
    { ".jpe",   "image/jpeg" },
    { ".jpg",   "image/jpeg" },
    { ".jpeg",  "image/jpeg" },
    { ".png",   "image/png" },
385
    { ".mpjpeg","multipart/x-mixed-replace; boundary=This Random String" },
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411

    /* media mime */
    { ".avi",   "video/avi" },
    { ".asf",   "video/x-ms-asf" },
    { ".m1a",   "audio/mpeg" },
    { ".m2a",   "audio/mpeg" },
    { ".m1v",   "video/mpeg" },
    { ".m2v",   "video/mpeg" },
    { ".mp2",   "audio/mpeg" },
    { ".mp3",   "audio/mpeg" },
    { ".mpa",   "audio/mpeg" },
    { ".mpg",   "video/mpeg" },
    { ".mpeg",  "video/mpeg" },
    { ".mpe",   "video/mpeg" },
    { ".mov",   "video/quicktime" },
    { ".moov",  "video/quicktime" },
    { ".ogg",   "application/ogg" },
    { ".ogm",   "application/ogg" },
    { ".wav",   "audio/wav" },
    { ".wma",   "audio/x-ms-wma" },
    { ".wmv",   "video/x-ms-wmv" },


    /* end */
    { NULL,     NULL }
};
412
static const char *httpd_MimeFromUrl( const char *psz_url )
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
{

    char *psz_ext;

    psz_ext = strrchr( psz_url, '.' );
    if( psz_ext )
    {
        int i;

        for( i = 0; http_mime[i].psz_ext != NULL ; i++ )
        {
            if( !strcasecmp( http_mime[i].psz_ext, psz_ext ) )
            {
                return http_mime[i].psz_mime;
            }
        }
    }
    return "application/octet-stream";
}

/*****************************************************************************
434
 * High Level Functions: httpd_file_t
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
 *****************************************************************************/
struct httpd_file_t
{
    httpd_url_t *url;

    char *psz_url;
    char *psz_mime;

    httpd_file_callback_t pf_fill;
    httpd_file_sys_t      *p_sys;

};


static int httpd_FileCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl, httpd_message_t *answer, httpd_message_t *query )
{
    httpd_file_t *file = (httpd_file_t*)p_sys;
452
453
454
    uint8_t *psz_args = query->psz_args;
    uint8_t **pp_body, *p_body;
    int *pi_body, i_body;
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471

    if( answer == NULL || query == NULL )
    {
        return VLC_SUCCESS;
    }
    answer->i_proto  = HTTPD_PROTO_HTTP;
    answer->i_version= query->i_version;
    answer->i_type   = HTTPD_MSG_ANSWER;

    answer->i_status = 200;
    answer->psz_status = strdup( "OK" );

    httpd_MsgAdd( answer, "Content-type",  "%s", file->psz_mime );
    httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );

    if( query->i_type != HTTPD_MSG_HEAD )
    {
472
473
474
475
476
477
478
479
480
481
        pp_body = &answer->p_body;
        pi_body = &answer->i_body;
    }
    else
    {
        /* The file still needs to be executed. */
        p_body = NULL;
        i_body = 0;
        pp_body = &p_body;
        pi_body = &i_body;
482
    }
483
484
485
486
487
488
489
490
491
492
493
494
495

    if( query->i_type == HTTPD_MSG_POST )
    {
        /* msg_Warn not supported */
    }

    file->pf_fill( file->p_sys, file, psz_args, pp_body, pi_body );

    if( query->i_type == HTTPD_MSG_HEAD && p_body != NULL )
    {
        free( p_body );
    }

496
497
498
    /* We respect client request */
    if( strcmp( httpd_MsgGet( &cl->query, "Connection" ), "" ) )
    {
499
500
        httpd_MsgAdd( answer, "Connection",
                      httpd_MsgGet( &cl->query, "Connection" ) );
501
502
    }

503
504
505
506
507
508
509
    httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );

    return VLC_SUCCESS;
}


httpd_file_t *httpd_FileNew( httpd_host_t *host,
510
511
                             const char *psz_url, const char *psz_mime,
                             const char *psz_user, const char *psz_password,
512
                             const vlc_acl_t *p_acl, httpd_file_callback_t pf_fill,
513
514
515
516
                             httpd_file_sys_t *p_sys )
{
    httpd_file_t *file = malloc( sizeof( httpd_file_t ) );

517
    if( ( file->url = httpd_UrlNewUnique( host, psz_url, psz_user,
518
                                          psz_password, p_acl )
519
        ) == NULL )
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
    {
        free( file );
        return NULL;
    }

    file->psz_url  = strdup( psz_url );
    if( psz_mime && *psz_mime )
    {
        file->psz_mime = strdup( psz_mime );
    }
    else
    {
        file->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
    }

    file->pf_fill = pf_fill;
    file->p_sys   = p_sys;

538
539
540
541
542
543
    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 );
544
545
546
547

    return file;
}

548
void httpd_FileDelete( httpd_file_t *file )
549
550
551
552
553
554
555
556
557
{
    httpd_UrlDelete( file->url );

    free( file->psz_url );
    free( file->psz_mime );

    free( file );
}

558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
/*****************************************************************************
 * High Level Functions: httpd_handler_t (for CGIs)
 *****************************************************************************/
struct httpd_handler_t
{
    httpd_url_t *url;

    httpd_handler_callback_t pf_fill;
    httpd_handler_sys_t      *p_sys;

};

static int httpd_HandlerCallBack( httpd_callback_sys_t *p_sys, httpd_client_t *cl, httpd_message_t *answer, httpd_message_t *query )
{
    httpd_handler_t *handler = (httpd_handler_t*)p_sys;
    uint8_t *psz_args = query->psz_args;
    char psz_remote_addr[100];

    if( answer == NULL || query == NULL )
    {
        return VLC_SUCCESS;
    }
    answer->i_proto  = HTTPD_PROTO_NONE;
    answer->i_type   = HTTPD_MSG_ANSWER;

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

    switch( cl->sock.ss_family )
    {
#ifdef HAVE_INET_PTON
    case AF_INET:
        inet_ntop( cl->sock.ss_family,
                   &((struct sockaddr_in *)&cl->sock)->sin_addr,
                   psz_remote_addr, sizeof(psz_remote_addr) );
        break;
    case AF_INET6:
        inet_ntop( cl->sock.ss_family,
                   &((struct sockaddr_in6 *)&cl->sock)->sin6_addr,
                   psz_remote_addr, sizeof(psz_remote_addr) );
        break;
#else
    case AF_INET:
    {
        char *psz_tmp = inet_ntoa( ((struct sockaddr_in *)&cl->sock)->sin_addr );
        strncpy( psz_remote_addr, psz_tmp, sizeof(psz_remote_addr) );
        break;
    }
#endif
    default:
        psz_remote_addr[0] = '\0';
    }

    handler->pf_fill( handler->p_sys, handler, query->psz_url, psz_args,
                      query->i_type, query->p_body, query->i_body,
                      psz_remote_addr, NULL,
                      &answer->p_body, &answer->i_body );

    if( query->i_type == HTTPD_MSG_HEAD )
    {
        char *p = answer->p_body;
        while ( (p = strchr( p, '\r' )) != NULL )
        {
            if( p[1] && p[1] == '\n' && p[2] && p[2] == '\r'
                 && p[3] && p[3] == '\n' )
            {
                break;
            }
        }
        if( p != NULL )
        {
            p[4] = '\0';
            answer->i_body = strlen(answer->p_body) + 1;
            answer->p_body = realloc( answer->p_body, answer->i_body );
        }
    }

    if( strncmp( answer->p_body, "HTTP/1.", 7 ) )
    {
        int i_status, i_headers;
        char *psz_headers, *psz_new, *psz_status;
        char psz_code[12];
        if( !strncmp( answer->p_body, "Status: ", 8 ) )
        {
            /* Apache-style */
            i_status = strtol( &answer->p_body[8], &psz_headers, 0 );
            if( *psz_headers ) psz_headers++;
            if( *psz_headers ) psz_headers++;
            i_headers = answer->i_body - (psz_headers - (char *)answer->p_body);
        }
        else
        {
            i_status = 200;
            psz_headers = answer->p_body;
            i_headers = answer->i_body;
        }
        switch( i_status )
        {
        case 200:
            psz_status = "OK";
            break;
        case 401:
            psz_status = "Unauthorized";
            break;
        default:
            psz_status = "Undefined";
            break;
        }
        snprintf( psz_code, sizeof(psz_code), "%d", i_status );
        answer->i_body = sizeof("HTTP/1.0  \r\n") + strlen(psz_code)
                           + strlen(psz_status) + i_headers - 1;
        psz_new = malloc( answer->i_body + 1);
        sprintf( psz_new, "HTTP/1.0 %s %s\r\n", psz_code, psz_status );
        memcpy( &psz_new[strlen(psz_new)], psz_headers, i_headers );
        free( answer->p_body );
        answer->p_body = psz_new;
    }

    return VLC_SUCCESS;
}

httpd_handler_t *httpd_HandlerNew( httpd_host_t *host, const char *psz_url,
                                   const char *psz_user,
                                   const char *psz_password,
                                   const vlc_acl_t *p_acl,
                                   httpd_handler_callback_t pf_fill,
                                   httpd_handler_sys_t *p_sys )
{
    httpd_handler_t *handler = malloc( sizeof( httpd_handler_t ) );

    if( ( handler->url = httpd_UrlNewUnique( host, psz_url, psz_user,
                                             psz_password, p_acl )
        ) == NULL )
    {
        free( handler );
        return NULL;
    }

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

    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 );

    return handler;
}

void httpd_HandlerDelete( httpd_handler_t *handler )
{
    httpd_UrlDelete( handler->url );
    free( handler );
}

716
/*****************************************************************************
717
 * High Level Functions: httpd_redirect_t
718
719
720
721
722
723
724
 *****************************************************************************/
struct httpd_redirect_t
{
    httpd_url_t *url;
    char        *psz_dst;
};

725
726
727
static int httpd_RedirectCallBack( httpd_callback_sys_t *p_sys,
                                   httpd_client_t *cl, httpd_message_t *answer,
                                   httpd_message_t *query )
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
{
    httpd_redirect_t *rdir = (httpd_redirect_t*)p_sys;
    uint8_t *p;

    if( answer == NULL || query == NULL )
    {
        return VLC_SUCCESS;
    }
    answer->i_proto  = query->i_proto;
    answer->i_version= query->i_version;
    answer->i_type   = HTTPD_MSG_ANSWER;
    answer->i_status = 301;
    answer->psz_status = strdup( "Moved Permanently" );

    p = answer->p_body = malloc( 1000 + strlen( rdir->psz_dst ) );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
743
    p += sprintf( (char *)p,
744
        "<?xml version=\"1.0\" encoding=\"ascii\" ?>\n"
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
745
        "<!DOCTYPE html PUBLIC \"-//W3C//DTD  XHTML 1.0 Strict//EN\" "
746
        "\"http://www.w3.org/TR/xhtml10/DTD/xhtml10strict.dtd\">\n"
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
747
748
749
750
751
        "<html>\n"
        "<head>\n"
        "<title>Redirection</title>\n"
        "</head>\n"
        "<body>\n"
752
        "<h1>You should be " 
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
753
754
755
756
757
758
        "<a href=\"%s\">redirected</a></h1>\n"
        "<hr />\n"
        "<p><a href=\"http://www.videolan.org\">VideoLAN</a>\n</p>"
        "<hr />\n"
        "</body>\n"
        "</html>\n", rdir->psz_dst );
759
760
761
762
763
764
765
766
767
768
    answer->i_body = p - answer->p_body;

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

    httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );

    return VLC_SUCCESS;
}

769
770
httpd_redirect_t *httpd_RedirectNew( httpd_host_t *host, const char *psz_url_dst,
                                     const char *psz_url_src )
771
772
773
{
    httpd_redirect_t *rdir = malloc( sizeof( httpd_redirect_t ) );

774
    if( !( rdir->url = httpd_UrlNewUnique( host, psz_url_src, NULL, NULL, NULL ) ) )
775
776
777
778
779
780
    {
        free( rdir );
        return NULL;
    }
    rdir->psz_dst = strdup( psz_url_dst );

781
782
783
784
785
786
787
788
789
    /* Redirect apply for all HTTP request and RTSP DESCRIBE resquest */
    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 );
790
791
792

    return rdir;
}
793
void httpd_RedirectDelete( httpd_redirect_t *rdir )
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
{
    httpd_UrlDelete( rdir->url );
    free( rdir->psz_dst );
    free( rdir );
}

/*****************************************************************************
 * 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;

    /* circular buffer */
    int         i_buffer_size;      /* buffer size, can't be reallocated smaller */
    uint8_t     *p_buffer;          /* buffer */
    int64_t     i_buffer_pos;       /* absolute position from begining */
    int64_t     i_buffer_last_pos;  /* a new connection will start with that */
};

821
822
823
static int httpd_StreamCallBack( httpd_callback_sys_t *p_sys,
                                 httpd_client_t *cl, httpd_message_t *answer,
                                 httpd_message_t *query )
824
825
826
827
828
829
830
831
832
833
834
835
{
    httpd_stream_t *stream = (httpd_stream_t*)p_sys;

    if( answer == NULL || query == NULL || cl == NULL )
    {
        return VLC_SUCCESS;
    }
    if( answer->i_body_offset > 0 )
    {
        int64_t i_write;
        int     i_pos;

836
837
838
839
#if 0
        fprintf( stderr, "httpd_StreamCallBack i_body_offset=%lld\n",
                 answer->i_body_offset );
#endif
840
841
842
843
844
845

        if( answer->i_body_offset >= stream->i_buffer_pos )
        {
            /* fprintf( stderr, "httpd_StreamCallBack: no data\n" ); */
            return VLC_EGENERIC;    /* wait, no data available */
        }
846
847
        if( answer->i_body_offset + stream->i_buffer_size <
            stream->i_buffer_pos )
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
        {
            /* this client isn't fast enough */
            fprintf( stderr, "fixing i_body_offset (old=%lld new=%lld)\n",
                     answer->i_body_offset, stream->i_buffer_last_pos );
            answer->i_body_offset = stream->i_buffer_last_pos;
        }

        i_pos   = answer->i_body_offset % stream->i_buffer_size;
        i_write = stream->i_buffer_pos - answer->i_body_offset;
        if( i_write > 10000 )
        {
            i_write = 10000;
        }
        else if( i_write <= 0 )
        {
            return VLC_EGENERIC;    /* wait, no data available */
        }

866
867
868
        /* Don't go past the end of the circular buffer */
        i_write = __MIN( i_write, stream->i_buffer_size - i_pos );

869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
        /* 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;
        answer->p_body = malloc( i_write );
        memcpy( answer->p_body, &stream->p_buffer[i_pos], i_write );

        answer->i_body_offset += i_write;

        return VLC_SUCCESS;
    }
    else
    {
        answer->i_proto  = HTTPD_PROTO_HTTP;
        answer->i_version= 0;
        answer->i_type   = HTTPD_MSG_ANSWER;

        answer->i_status = 200;
        answer->psz_status = strdup( "OK" );

        if( query->i_type != HTTPD_MSG_HEAD )
        {
            httpd_ClientModeStream( cl );
            vlc_mutex_lock( &stream->lock );
            /* Send the header */
            if( stream->i_header > 0 )
            {
                answer->i_body = stream->i_header;
                answer->p_body = malloc( stream->i_header );
                memcpy( answer->p_body, stream->p_header, stream->i_header );
            }
            answer->i_body_offset = stream->i_buffer_last_pos;
            vlc_mutex_unlock( &stream->lock );
        }
        else
        {
            httpd_MsgAdd( answer, "Content-Length", "%d", 0 );
908
            answer->i_body_offset = 0;
909
910
911
912
913
914
915
        }

        if( !strcmp( stream->psz_mime, "video/x-ms-asf-stream" ) )
        {
            vlc_bool_t b_xplaystream = VLC_FALSE;
            int i;

916
917
            httpd_MsgAdd( answer, "Content-type", "%s",
                          "application/octet-stream" );
918
919
920
921
            httpd_MsgAdd( answer, "Server", "Cougar 4.1.0.3921" );
            httpd_MsgAdd( answer, "Pragma", "no-cache" );
            httpd_MsgAdd( answer, "Pragma", "client-id=%d", rand()&0x7fff );
            httpd_MsgAdd( answer, "Pragma", "features=\"broadcast\"" );
922

923
924
925
926
            /* Check if there is a xPlayStrm=1 */
            for( i = 0; i < query->i_name; i++ )
            {
                if( !strcasecmp( query->name[i],  "Pragma" ) &&
927
                    strstr( query->value[i], "xPlayStrm=1" ) )
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
                {
                    b_xplaystream = VLC_TRUE;
                }
            }

            if( !b_xplaystream )
            {
                answer->i_body_offset = 0;
            }
        }
        else
        {
            httpd_MsgAdd( answer, "Content-type",  "%s", stream->psz_mime );
        }
        httpd_MsgAdd( answer, "Cache-Control", "%s", "no-cache" );
        return VLC_SUCCESS;
    }
}

httpd_stream_t *httpd_StreamNew( httpd_host_t *host,
948
949
                                 const char *psz_url, const char *psz_mime,
                                 const char *psz_user, const char *psz_password,
950
                                 const vlc_acl_t *p_acl )
951
952
953
{
    httpd_stream_t *stream = malloc( sizeof( httpd_stream_t ) );

954
    if( ( stream->url = httpd_UrlNewUnique( host, psz_url, psz_user,
955
                                            psz_password, p_acl )
956
        ) == NULL )
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
    {
        free( stream );
        return NULL;
    }
    vlc_mutex_init( host, &stream->lock );
    if( psz_mime && *psz_mime )
    {
        stream->psz_mime = strdup( psz_mime );
    }
    else
    {
        stream->psz_mime = strdup( httpd_MimeFromUrl( psz_url ) );
    }
    stream->i_header = 0;
    stream->p_header = NULL;
    stream->i_buffer_size = 5000000;    /* 5 Mo per stream */
    stream->p_buffer = malloc( stream->i_buffer_size );
974
975
    /* We set to 1 to make life simpler
     * (this way i_body_offset can never be 0) */
976
977
978
    stream->i_buffer_pos = 1;
    stream->i_buffer_last_pos = 1;

979
980
981
982
983
984
    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 );
985
986
987
988

    return stream;
}

989
int httpd_StreamHeader( httpd_stream_t *stream, uint8_t *p_data, int i_data )
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
{
    vlc_mutex_lock( &stream->lock );
    if( stream->p_header )
    {
        free( stream->p_header );
        stream->p_header = NULL;
    }
    stream->i_header = i_data;
    if( i_data > 0 )
    {
        stream->p_header = malloc( i_data );
        memcpy( stream->p_header, p_data, i_data );
    }
    vlc_mutex_unlock( &stream->lock );

    return VLC_SUCCESS;
}

1008
int httpd_StreamSend( httpd_stream_t *stream, uint8_t *p_data, int i_data )
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
{
    int i_count;
    int i_pos;

    if( i_data < 0 || p_data == NULL )
    {
        return VLC_SUCCESS;
    }
    vlc_mutex_lock( &stream->lock );

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

    i_pos = stream->i_buffer_pos % stream->i_buffer_size;
    i_count = i_data;
    while( i_count > 0)
    {
        int i_copy;

        i_copy = __MIN( i_count, stream->i_buffer_size - i_pos );

        /* Ok, we can't go past the end of our buffer */
        memcpy( &stream->p_buffer[i_pos], p_data, i_copy );

        i_pos = ( i_pos + i_copy ) % stream->i_buffer_size;
        i_count -= i_copy;
        p_data  += i_copy;
    }

    stream->i_buffer_pos += i_data;

    vlc_mutex_unlock( &stream->lock );
    return VLC_SUCCESS;
}

void httpd_StreamDelete( httpd_stream_t *stream )
{
    httpd_UrlDelete( stream->url );
    vlc_mutex_destroy( &stream->lock );
    if( stream->psz_mime ) free( stream->psz_mime );
    if( stream->p_header ) free( stream->p_header );
    if( stream->p_buffer ) free( stream->p_buffer );
    free( stream );
}


/*****************************************************************************
 * Low level
 *****************************************************************************/
static void httpd_HostThread( httpd_host_t * );

/* create a new host */
1061
httpd_host_t *httpd_HostNew( vlc_object_t *p_this, const char *psz_host,
1062
1063
                             int i_port )
{
1064
1065
    return httpd_TLSHostNew( p_this, psz_host, i_port, NULL, NULL, NULL, NULL
                           );
1066
1067
}

1068
1069
1070
1071
httpd_host_t *httpd_TLSHostNew( vlc_object_t *p_this, const char *psz_hostname,
                                int i_port,
                                const char *psz_cert, const char *psz_key,
                                const char *psz_ca, const char *psz_crl )
1072
1073
{
    httpd_t      *httpd;
1074
    httpd_host_t *host;
1075
1076
    tls_server_t *p_tls;
    char *psz_host;
1077
1078
    vlc_value_t  lockval;
    int i;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1079

1080
1081
1082
    if( psz_hostname == NULL )
        psz_hostname = "";

1083
    psz_host = strdup( psz_hostname );
1084
    if( psz_host == NULL )
1085
    {
1086
        msg_Err( p_this, "memory error" );
1087
1088
1089
1090
1091
1092
1093
1094
        return NULL;
    }

    /* to be sure to avoid multiple creation */
    var_Create( p_this->p_libvlc, "httpd_mutex", VLC_VAR_MUTEX );
    var_Get( p_this->p_libvlc, "httpd_mutex", &lockval );
    vlc_mutex_lock( lockval.p_address );

1095
    if( !(httpd = vlc_object_find( p_this, VLC_OBJECT_HTTPD, FIND_ANYWHERE )) )
1096
1097
1098
1099
1100
    {
        msg_Info( p_this, "creating httpd" );
        if( ( httpd = vlc_object_create( p_this, VLC_OBJECT_HTTPD ) ) == NULL )
        {
            vlc_mutex_unlock( lockval.p_address );
1101
            free( psz_host );
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
            return NULL;
        }

        httpd->i_host = 0;
        httpd->host   = NULL;

        vlc_object_yield( httpd );
        vlc_object_attach( httpd, p_this->p_vlc );
    }

1112
1113
    /* verify if it already exist */
    for( i = httpd->i_host - 1; i >= 0; i-- )
1114
    {
1115
        host = httpd->host[i];
1116

1117
1118
1119
1120
        /* cannot mix TLS and non-TLS hosts */
        if( ( ( httpd->host[i]->p_tls != NULL ) != ( psz_cert != NULL ) )
         || ( host->i_port != i_port )
         || strcmp( host->psz_hostname, psz_hostname ) )
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1121
1122
            continue;

1123
1124
        /* yep found */
        host->i_ref++;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1125

1126
1127
        vlc_mutex_unlock( lockval.p_address );
        return host;
1128
    }
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1129

1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
    host = NULL;

    /* determine TLS configuration */
    if ( psz_cert != NULL )
    {
        p_tls = tls_ServerCreate( p_this, psz_cert, psz_key );
        if ( p_tls == NULL )
        {
            msg_Err( p_this, "TLS initialization error" );
            goto error;
        }

        if ( ( psz_ca != NULL) && tls_ServerAddCA( p_tls, psz_ca ) )
        {
            msg_Err( p_this, "TLS CA error" );
            goto error;
        }

        if ( ( psz_crl != NULL) && tls_ServerAddCRL( p_tls, psz_crl ) )
        {
            msg_Err( p_this, "TLS CRL error" );
            goto error;
        }
    }
    else
        p_tls = NULL;

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1157
1158
1159
1160
1161
1162
    /* create the new host */
    host = vlc_object_create( p_this, sizeof( httpd_host_t ) );
    host->httpd = httpd;
    vlc_mutex_init( httpd, &host->lock );
    host->i_ref = 1;

1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
    host->fd = net_ListenTCP( p_this, psz_host, i_port );
    if( host->fd == NULL )
    {
        msg_Err( p_this, "cannot create socket(s) for HTTP host" );
        goto error;
    }
       
    host->i_port = i_port;
    host->psz_hostname = psz_host;

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1173
1174
1175
1176
    host->i_url     = 0;
    host->url       = NULL;
    host->i_client  = 0;
    host->client    = NULL;
1177

1178
    host->p_tls = p_tls;
1179

1180
    /* create the thread */
1181
1182
    if( vlc_thread_create( host, "httpd host thread", httpd_HostThread,
                           VLC_THREAD_PRIORITY_LOW, VLC_FALSE ) )
1183
1184
    {
        msg_Err( p_this, "cannot spawn http host thread" );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1185
        goto error;
1186
1187
1188
1189
1190
1191
1192
1193
    }

    /* now add it to httpd */
    TAB_APPEND( httpd->i_host, httpd->host, host );
    vlc_mutex_unlock( lockval.p_address );

    return host;

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1194
error:
1195
    free( psz_host );
1196
1197
1198
1199
1200
1201
    if( httpd->i_host <= 0 )
    {
        vlc_object_release( httpd );
        vlc_object_detach( httpd );
        vlc_object_destroy( httpd );
    }
1202
1203
    vlc_mutex_unlock( lockval.p_address );

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1204
    if( host != NULL )
1205
    {
1206
        net_ListenClose( host->fd );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1207
1208
        vlc_mutex_destroy( &host->lock );
        vlc_object_destroy( host );
1209
1210
    }

1211
1212
1213
    if( p_tls != NULL )
        tls_ServerDelete( p_tls );

1214
1215
1216
1217
    return NULL;
}

/* delete a host */
1218
void httpd_HostDelete( httpd_host_t *host )
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
{
    httpd_t *httpd = host->httpd;
    vlc_value_t lockval;
    int i;

    msg_Dbg( host, "httpd_HostDelete" );

    var_Get( httpd->p_libvlc, "httpd_mutex", &lockval );
    vlc_mutex_lock( lockval.p_address );

    host->i_ref--;
    if( host->i_ref > 0 )
    {
        /* still used */
        vlc_mutex_unlock( lockval.p_address );
        msg_Dbg( host, "httpd_HostDelete: host still used" );
        return;
    }
    TAB_REMOVE( httpd->i_host, httpd->host, host );

    msg_Dbg( host, "httpd_HostDelete: host removed from http" );

    host->b_die = 1;
    vlc_thread_join( host );

    msg_Dbg( host, "httpd_HostDelete: host thread joined" );

    for( i = 0; i < host->i_url; i++ )
    {
        msg_Err( host, "url still registered:%s", host->url[i]->psz_url );
    }
    for( i = 0; i < host->i_client; i++ )
    {
        httpd_client_t *cl = host->client[i];
        msg_Warn( host, "client still connected" );
1254
1255
1256
1257
        httpd_ClientClean( cl );
        TAB_REMOVE( host->i_client, host->client, cl );
        free( cl );
        i--;
1258
1259
1260
        /* TODO */
    }

1261
1262
    if( host->p_tls != NULL)
        tls_ServerDelete( host->p_tls );
1263
1264
1265
1266

    net_ListenClose( host->fd );
    free( host->psz_hostname );

1267
1268
1269
    vlc_mutex_destroy( &host->lock );
    vlc_object_destroy( host );

1270
    vlc_object_release( httpd );
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
    if( httpd->i_host <= 0 )
    {
        msg_Info( httpd, "httpd doesn't reference any host, deleting" );
        vlc_object_detach( httpd );
        vlc_object_destroy( httpd );
    }
    vlc_mutex_unlock( lockval.p_address );
}

/* register a new url */
1281
1282
static httpd_url_t *httpd_UrlNewPrivate( httpd_host_t *host, const char *psz_url,
                                         const char *psz_user, const char *psz_password,
1283
                                         const vlc_acl_t *p_acl, vlc_bool_t b_check )
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
{
    httpd_url_t *url;
    int         i;

    vlc_mutex_lock( &host->lock );
    if( b_check )
    {
        for( i = 0; i < host->i_url; i++ )
        {
            if( !strcmp( psz_url, host->url[i]->psz_url ) )
            {
                msg_Warn( host->httpd,
                          "cannot add '%s' (url already defined)", psz_url );
                vlc_mutex_unlock( &host->lock );
                return NULL;
            }
        }
    }

    url = malloc( sizeof( httpd_url_t ) );
    url->host = host;

    vlc_mutex_init( host->httpd, &url->lock );
    url->psz_url = strdup( psz_url );
    url->psz_user = strdup( psz_user ? psz_user : "" );
    url->psz_password = strdup( psz_password ? psz_password : "" );
1310
    url->p_acl = ACL_Duplicate( host, p_acl );
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
    for( i = 0; i < HTTPD_MSG_MAX; i++ )
    {
        url->catch[i].cb = NULL;
        url->catch[i].p_sys = NULL;
    }

    TAB_APPEND( host->i_url, host->url, url );
    vlc_mutex_unlock( &host->lock );

    return url;
}

1323
1324
httpd_url_t *httpd_UrlNew( httpd_host_t *host, const char *psz_url,
                           const char *psz_user, const char *psz_password,
1325
                           const vlc_acl_t *p_acl )
1326
{
1327
    return httpd_UrlNewPrivate( host, psz_url, psz_user,
1328
                                psz_password, p_acl, VLC_FALSE );
1329
1330
}

1331
1332
httpd_url_t *httpd_UrlNewUnique( httpd_host_t *host, const char *psz_url,
                                 const char *psz_user, const char *psz_password,
1333
                                 const vlc_acl_t *p_acl )
1334
{
1335
    return httpd_UrlNewPrivate( host, psz_url, psz_user,
1336
                                psz_password, p_acl, VLC_TRUE );
1337
1338
1339
}

/* register callback on a url */
1340
1341
int httpd_UrlCatch( httpd_url_t *url, int i_msg, httpd_callback_t cb,
                    httpd_callback_sys_t *p_sys )
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
{
    vlc_mutex_lock( &url->lock );
    url->catch[i_msg].cb   = cb;
    url->catch[i_msg].p_sys= p_sys;
    vlc_mutex_unlock( &url->lock );

    return VLC_SUCCESS;
}


/* delete an url */
1353
void httpd_UrlDelete( httpd_url_t *url )
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
{
    httpd_host_t *host = url->host;
    int          i;

    vlc_mutex_lock( &host->lock );
    TAB_REMOVE( host->i_url, host->url, url );

    vlc_mutex_destroy( &url->lock );
    free( url->psz_url );
    free( url->psz_user );
    free( url->psz_password );
1365
    ACL_Destroy( url->p_acl );
1366
1367
1368
1369
1370
1371
1372
1373
1374

    for( i = 0; i < host->i_client; i++ )
    {
        httpd_client_t *client = host->client[i];

        if( client->url == url )
        {
            /* TODO complete it */
            msg_Warn( host, "force closing connections" );
1375
            httpd_ClientClean( client );
1376
            TAB_REMOVE( host->i_client, host->client, client );
1377
            free( client );
1378
1379
1380
            i--;
        }
    }
1381
    free( url );
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
    vlc_mutex_unlock( &host->lock );
}

void httpd_MsgInit( httpd_message_t *msg )
{
    msg->cl         = NULL;
    msg->i_type     = HTTPD_MSG_NONE;
    msg->i_proto    = HTTPD_PROTO_NONE;
    msg->i_version  = -1;

    msg->i_status   = 0;
    msg->psz_status = NULL;

    msg->psz_url = NULL;
    msg->psz_args = NULL;

    msg->i_channel = -1;

    msg->i_name = 0;
    msg->name   = NULL;
    msg->i_value= 0;
    msg->value  = NULL;

    msg->i_body_offset = 0;
    msg->i_body        = 0;
    msg->p_body        = 0;
}

void httpd_MsgClean( httpd_message_t *msg )
{
    int i;

    if( msg->psz_status )
    {
        free( msg->psz_status );
    }
    if( msg->psz_url )
    {
        free( msg->psz_url );
    }
    if( msg->psz_args )
    {
        free( msg->psz_args );
    }
    for( i = 0; i < msg->i_name; i++ )
    {
        free( msg->name[i] );
        free( msg->value[i] );
    }
    if( msg->name )
    {
        free( msg->name );
    }
    if( msg->value )
    {
        free( msg->value );
    }
    if( msg->p_body )
    {
        free( msg->p_body );
    }
    httpd_MsgInit( msg );
}

char *httpd_MsgGet( httpd_message_t *msg, char *name )
{
    int i;

    for( i = 0; i < msg->i_name; i++ )
    {
        if( !strcasecmp( msg->name[i], name ))
        {
            return msg->value[i];
        }
    }
    return "";
}
void httpd_MsgAdd( httpd_message_t *msg, char *name, char *psz_value, ... )
{
    va_list args;
    char *value = NULL;

    va_start( args, psz_value );
#if defined(HAVE_VASPRINTF) && !defined(SYS_DARWIN) && !defined(SYS_BEOS)
    vasprintf( &value, psz_value, args );
#else
    {
        int i_size = strlen( psz_value ) + 4096;    /* FIXME stupid system */
        value = calloc( i_size, sizeof( char ) );
        vsnprintf( value, i_size, psz_value, args );
        value[i_size - 1] = 0;
    }
#endif
    va_end( args );

    name = strdup( name );

    TAB_APPEND( msg->i_name,  msg->name,  name );
    TAB_APPEND( msg->i_value, msg->value, value );
}

static void httpd_ClientInit( httpd_client_t *cl )
{
    cl->i_state = HTTPD_CLIENT_RECEIVING;
    cl->i_activity_date = mdate();
1487
    cl->i_activity_timeout = I64C(10000000);
1488
1489
1490
1491
1492
1493
1494
1495
1496
    cl->i_buffer_size = 10000;
    cl->i_buffer = 0;
    cl->p_buffer = malloc( cl->i_buffer_size );
    cl->i_mode   = HTTPD_CLIENT_FILE;
    cl->b_read_waiting = VLC_FALSE;

    httpd_MsgInit( &cl->query );
    httpd_MsgInit( &cl->answer );
}
1497

1498
1499
1500
1501
void httpd_ClientModeStream( httpd_client_t *cl )
{
    cl->i_mode   = HTTPD_CLIENT_STREAM;
}
1502

1503
1504
1505
1506
1507
void httpd_ClientModeBidir( httpd_client_t *cl )
{
    cl->i_mode   = HTTPD_CLIENT_BIDIR;
}

1508
char* httpd_ClientIP( httpd_client_t *cl, char *psz_ip )
1509
{
1510
1511
    return net_GetPeerAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
}
1512

1513
1514
1515
char* httpd_ServerIP( httpd_client_t *cl, char *psz_ip )
{
    return net_GetSockAddress( cl->fd, psz_ip, NULL ) ? NULL : psz_ip;
1516
1517
}

1518
1519
static void httpd_ClientClean( httpd_client_t *cl )
{
1520
    if( cl->fd >= 0 )
1521
    {
1522
        if( cl->p_tls != NULL )
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1523
            tls_ServerSessionClose( cl->p_tls );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1524
        net_Close( cl->fd );
1525
        cl->fd = -1;
1526
1527
1528
1529
1530
1531
1532
1533
    }

    httpd_MsgClean( &cl->answer );
    httpd_MsgClean( &cl->query );

    if( cl->p_buffer )
    {
        free( cl->p_buffer );
1534
        cl->p_buffer = NULL;
1535
1536
1537
    }
}

1538
static httpd_client_t *httpd_ClientNew( int fd, struct sockaddr_storage *sock,
1539
1540
                                        int i_sock_size,
                                        tls_session_t *p_tls )
1541
1542
1543
1544
{
    httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
    cl->i_ref   = 0;
    cl->fd      = fd;
1545
1546
    memcpy( &cl->sock, sock, sizeof( cl->sock ) );
    cl->i_sock_size = i_sock_size;
1547
    cl->url     = NULL;
1548
    cl->p_tls = p_tls;
1549
1550
1551
1552
1553
1554

    httpd_ClientInit( cl );

    return cl;
}

1555

1556
static int httpd_NetRecv( httpd_client_t *cl, uint8_t *p, int i_len )
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
{
    tls_session_t *p_tls;
    
    p_tls = cl->p_tls;
    if( p_tls != NULL)
        return tls_Recv( p_tls, p, i_len );

    return recv( cl->fd, p, i_len, 0 );
}


1568
static int httpd_NetSend( httpd_client_t *cl, const uint8_t *p, int i_len )
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
{
    tls_session_t *p_tls;

    p_tls = cl->p_tls;
    if( p_tls != NULL)
        return tls_Send( p_tls, p, i_len );

    return send( cl->fd, p, i_len, 0 );
}


1580
1581
1582
1583
1584
1585
static void httpd_ClientRecv( httpd_client_t *cl )
{
    int i_len;

    if( cl->query.i_proto == HTTPD_PROTO_NONE )
    {
1586
        /* enough to see if it's rtp over rtsp or RTSP/HTTP */
1587
1588
        i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
                               4 - cl->i_buffer );
1589
1590
1591
1592
1593
1594
1595
        if( i_len > 0 )
        {
            cl->i_buffer += i_len;
        }

        if( cl->i_buffer >= 4 )
        {
1596
            /*fprintf( stderr, "peek=%4.4s\n", cl->p_buffer );*/
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
            /* detect type */
            if( cl->p_buffer[0] == '$' )
            {
                /* RTSP (rtp over rtsp) */
                cl->query.i_proto = HTTPD_PROTO_RTSP;
                cl->query.i_type  = HTTPD_MSG_CHANNEL;
                cl->query.i_channel = cl->p_buffer[1];
                cl->query.i_body  = (cl->p_buffer[2] << 8)|cl->p_buffer[3];
                cl->query.p_body  = malloc( cl->query.i_body );

                cl->i_buffer      = 0;
            }
1609
            else if( !memcmp( cl->p_buffer, "HTTP", 4 ) )
1610
1611
1612
1613
            {
                cl->query.i_proto = HTTPD_PROTO_HTTP;
                cl->query.i_type  = HTTPD_MSG_ANSWER;
            }
1614
            else if( !memcmp( cl->p_buffer, "RTSP", 4 ) )
1615
1616
1617
1618
            {
                cl->query.i_proto = HTTPD_PROTO_RTSP;
                cl->query.i_type  = HTTPD_MSG_ANSWER;
            }
1619
1620
1621
            else if( !memcmp( cl->p_buffer, "GET", 3 ) ||
                     !memcmp( cl->p_buffer, "HEAD", 4 ) ||
                     !memcmp( cl->p_buffer, "POST", 4 ) )
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
            {
                cl->query.i_proto = HTTPD_PROTO_HTTP;
                cl->query.i_type  = HTTPD_MSG_NONE;
            }
            else
            {
                cl->query.i_proto = HTTPD_PROTO_RTSP;
                cl->query.i_type  = HTTPD_MSG_NONE;
            }
        }
    }
    else if( cl->query.i_body > 0 )
    {
        /* we are reading the body of a request or a channel */
1636
1637
        i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
                               cl->query.i_body - cl->i_buffer );
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
        if( i_len > 0 )
        {
            cl->i_buffer += i_len;
        }
        if( cl->i_buffer >= cl->query.i_body )
        {
            cl->i_state = HTTPD_CLIENT_RECEIVE_DONE;
        }
    }
    else
    {
        /* we are reading a header -> char by char */
        for( ;; )
        {
1652
            i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
            if( i_len <= 0 )
            {
                break;
            }
            cl->i_buffer++;

            if( cl->i_buffer + 1 >= cl->i_buffer_size )
            {
                cl->i_buffer_size += 1024;
                cl->p_buffer = realloc( cl->p_buffer, cl->i_buffer_size );
            }
1664
1665
            if( ( cl->i_buffer >= 2 && !memcmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
                ( cl->i_buffer >= 4 && !memcmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
1666
1667
1668
1669
1670
1671
1672
1673
            {
                char *p;

                /* we have finished the header so parse it and set i_body */
                cl->p_buffer[cl->i_buffer] = '\0';

                if( cl->query.i_type == HTTPD_MSG_ANSWER )
                {
1674
1675
1676
                    /* FIXME:
                     * assume strlen( "HTTP/1.x" ) = 8
                     */
1677
                    cl->query.i_status =
1678
1679
                        strtol( (char *)&cl->p_buffer[8],
                                &p, 0 );
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
                    while( *p == ' ' )
                    {
                        p++;
                    }
                    cl->query.psz_status = strdup( p );
                }
                else
                {
                    static const struct
                    {
                        char *name;
                        int  i_type;
                        int  i_proto;
                    }
                    msg_type[] =
                    {
                        { "GET",        HTTPD_MSG_GET,  HTTPD_PROTO_HTTP },
                        { "HEAD",       HTTPD_MSG_HEAD, HTTPD_PROTO_HTTP },
                        { "POST",       HTTPD_MSG_POST, HTTPD_PROTO_HTTP },

                        { "OPTIONS",    HTTPD_MSG_OPTIONS,  HTTPD_PROTO_RTSP },
                        { "DESCRIBE",   HTTPD_MSG_DESCRIBE, HTTPD_PROTO_RTSP },
                        { "SETUP",      HTTPD_MSG_SETUP,    HTTPD_PROTO_RTSP },
                        { "PLAY",       HTTPD_MSG_PLAY,     HTTPD_PROTO_RTSP },
                        { "PAUSE",      HTTPD_MSG_PAUSE,    HTTPD_PROTO_RTSP },
                        { "TEARDOWN",   HTTPD_MSG_TEARDOWN, HTTPD_PROTO_RTSP },

                        { NULL,         HTTPD_MSG_NONE,     HTTPD_PROTO_NONE }
                    };
                    int  i;

                    p = NULL;
                    cl->query.i_type = HTTPD_MSG_NONE;

1714
                    /*fprintf( stderr, "received new request=%s\n", cl->p_buffer);*/
1715
1716
1717

                    for( i = 0; msg_type[i<