httpd.c 82.2 KB
Newer Older
1
2
3
/*****************************************************************************
 * httpd.c
 *****************************************************************************
4
 * Copyright (C) 2004-2005 VideoLAN
5
 * $Id$
6
7
 *
 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
8
 *          Remi 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

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

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

#ifdef HAVE_FCNTL_H
#   include <fcntl.h>
#endif
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

#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>
#   include <netinet/in.h>
#   ifdef HAVE_ARPA_INET_H
#       include <arpa/inet.h>                    /* inet_ntoa(), inet_aton() */
#   endif
#endif

59
#if defined(WIN32) && !defined(UNDER_CE)
gbazin's avatar
gbazin committed
60
static const struct in6_addr in6addr_any = {{IN6ADDR_ANY_INIT}};
61
62
#elif defined(UNDER_CE) && defined(AF_INET6)
#   undef AF_INET6
gbazin's avatar
gbazin committed
63
64
#endif

65
66
67
68
#ifndef PF_INET
#    define PF_INET AF_INET                                          /* BeOS */
#endif

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
153
154
155
156
157
158
159
160
#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 * );


161
162
163
void httpd_ClientModeStream( httpd_client_t *cl );
void httpd_ClientModeBidir( httpd_client_t *cl );
static void httpd_ClientClean( httpd_client_t *cl );
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
199
200
201
202
203
204
205
206

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

207
208
static void httpd_ClientClean( httpd_client_t *cl );

209
210
211
212
213
214
215
216
217
218
219
/* 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 */
220
221
222
    struct sockaddr_storage sock;
    int                     i_sock_size;
    int                     fd;
223
224
225
226
227
228
229
230
231
232
233
234

    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;
235
236
237
    
    /* TLS data */
    tls_server_t *p_tls;
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
};

struct httpd_url_t
{
    httpd_host_t *host;

    vlc_mutex_t lock;

    char    *psz_url;
    char    *psz_user;
    char    *psz_password;

    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,
269
270
271

    HTTPD_CLIENT_TLS_HS_IN,
    HTTPD_CLIENT_TLS_HS_OUT
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
};
/* 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;

287
288
    struct  sockaddr_storage sock;
    int     i_sock_size;
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
    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 */
306
307
308
    
    /* TLS data */
    tls_session_t *p_tls;
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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
};


/*****************************************************************************
 * 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
{
    char *psz_ext;
    char *psz_mime;
} 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" },
392
    { ".mpjpeg","multipart/x-mixed-replace; boundary=This Random String" },
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481

    /* 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 }
};
static char *httpd_MimeFromUrl( char *psz_url )
{

    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";
}

/*****************************************************************************
 * High Level Funtions: httpd_file_t
 *****************************************************************************/
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;

    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 )
    {
        char *psz_args = query->psz_args;
        if( query->i_type == HTTPD_MSG_POST )
        {
            /* Check that */
            psz_args = query->p_body;
        }
482
483
        file->pf_fill( file->p_sys, file, psz_args, &answer->p_body,
                       &answer->i_body );
484
    }
485
486
487
    /* We respect client request */
    if( strcmp( httpd_MsgGet( &cl->query, "Connection" ), "" ) )
    {
488
489
        httpd_MsgAdd( answer, "Connection",
                      httpd_MsgGet( &cl->query, "Connection" ) );
490
491
    }

492
493
494
495
496
497
498
499
500
501
502
503
504
505
    httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );

    return VLC_SUCCESS;
}


httpd_file_t *httpd_FileNew( httpd_host_t *host,
                             char *psz_url, char *psz_mime,
                             char *psz_user, char *psz_password,
                             httpd_file_callback_t pf_fill,
                             httpd_file_sys_t *p_sys )
{
    httpd_file_t *file = malloc( sizeof( httpd_file_t ) );

506
507
    if( ( file->url = httpd_UrlNewUnique( host, psz_url, psz_user,
                                          psz_password ) ) == NULL )
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
    {
        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;

526
527
528
529
530
531
    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 );
532
533
534
535

    return file;
}

536
void httpd_FileDelete( httpd_file_t *file )
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
{
    httpd_UrlDelete( file->url );

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

    free( file );
}

/*****************************************************************************
 * High Level Funtions: httpd_redirect_t
 *****************************************************************************/
struct httpd_redirect_t
{
    httpd_url_t *url;
    char        *psz_dst;
};

555
556
557
static int httpd_RedirectCallBack( httpd_callback_sys_t *p_sys,
                                   httpd_client_t *cl, httpd_message_t *answer,
                                   httpd_message_t *query )
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
{
    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 ) );
    p += sprintf( p, "<html>\n" );
    p += sprintf( p, "<head>\n" );
    p += sprintf( p, "<title>Redirection</title>\n" );
    p += sprintf( p, "</head>\n" );
    p += sprintf( p, "<body>\n" );
    p += sprintf( p, "<h1><center>You should be <a href=\"%s\">redirected</a></center></h1>\n", rdir->psz_dst );
    p += sprintf( p, "<hr />\n" );
    p += sprintf( p, "<a href=\"http://www.videolan.org\">VideoLAN</a>\n" );
    p += sprintf( p, "</body>\n" );
    p += sprintf( p, "</html>\n" );
    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;
}

593
594
httpd_redirect_t *httpd_RedirectNew( httpd_host_t *host, char *psz_url_dst,
                                     char *psz_url_src )
595
596
597
{
    httpd_redirect_t *rdir = malloc( sizeof( httpd_redirect_t ) );

598
    if( !( rdir->url = httpd_UrlNewUnique( host, psz_url_src, NULL, NULL ) ) )
599
600
601
602
603
604
    {
        free( rdir );
        return NULL;
    }
    rdir->psz_dst = strdup( psz_url_dst );

605
606
607
608
609
610
611
612
613
    /* 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 );
614
615
616

    return rdir;
}
617
void httpd_RedirectDelete( httpd_redirect_t *rdir )
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
{
    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 */
};

645
646
647
static int httpd_StreamCallBack( httpd_callback_sys_t *p_sys,
                                 httpd_client_t *cl, httpd_message_t *answer,
                                 httpd_message_t *query )
648
649
650
651
652
653
654
655
656
657
658
659
{
    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;

660
661
662
663
#if 0
        fprintf( stderr, "httpd_StreamCallBack i_body_offset=%lld\n",
                 answer->i_body_offset );
#endif
664
665
666
667
668
669

        if( answer->i_body_offset >= stream->i_buffer_pos )
        {
            /* fprintf( stderr, "httpd_StreamCallBack: no data\n" ); */
            return VLC_EGENERIC;    /* wait, no data available */
        }
670
671
        if( answer->i_body_offset + stream->i_buffer_size <
            stream->i_buffer_pos )
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
        {
            /* 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 */
        }

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

693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
        /* 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 );
732
            answer->i_body_offset = 0;
733
734
735
736
737
738
739
        }

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

740
741
            httpd_MsgAdd( answer, "Content-type", "%s",
                          "application/octet-stream" );
742
743
744
745
            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\"" );
746

747
748
749
750
            /* Check if there is a xPlayStrm=1 */
            for( i = 0; i < query->i_name; i++ )
            {
                if( !strcasecmp( query->name[i],  "Pragma" ) &&
751
                    strstr( query->value[i], "xPlayStrm=1" ) )
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
                {
                    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,
                                 char *psz_url, char *psz_mime,
                                 char *psz_user, char *psz_password )
{
    httpd_stream_t *stream = malloc( sizeof( httpd_stream_t ) );

777
778
    if( ( stream->url = httpd_UrlNewUnique( host, psz_url, psz_user,
                                            psz_password ) ) == NULL )
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
    {
        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 );
796
797
    /* We set to 1 to make life simpler
     * (this way i_body_offset can never be 0) */
798
799
800
    stream->i_buffer_pos = 1;
    stream->i_buffer_last_pos = 1;

801
802
803
804
805
806
    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 );
807
808
809
810

    return stream;
}

811
int httpd_StreamHeader( httpd_stream_t *stream, uint8_t *p_data, int i_data )
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
{
    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;
}

830
int httpd_StreamSend( httpd_stream_t *stream, uint8_t *p_data, int i_data )
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
{
    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
 *****************************************************************************/
#define LISTEN_BACKLOG          100

static void httpd_HostThread( httpd_host_t * );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
static int GetAddrPort( const struct sockaddr_storage *p_ss );

#ifndef HAVE_GETADDRINFO
struct httpd_addrinfo
{
    int ai_family;
    int ai_socktype;
    int ai_protocol;
    /*int ai_flags;*/
    struct sockaddr *ai_addr;
    int ai_addrlen;
    struct httpd_addrinfo *ai_next;
};
#   define addrinfo httpd_addrinfo

static int BuildAddr( struct sockaddr_in * p_socket,
899
                      const char * psz_address, int i_port );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
900
#endif
901
902
903


/* create a new host */
904
905
906
907
908
909
910
911
httpd_host_t *httpd_HostNew( vlc_object_t *p_this, char *psz_host,
                             int i_port )
{
    return httpd_TLSHostNew( p_this, psz_host, i_port, NULL );
}

httpd_host_t *httpd_TLSHostNew( vlc_object_t *p_this, char *psz_host,
                                int i_port, tls_server_t *p_tls )
912
913
{
    httpd_t      *httpd;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
914
    httpd_host_t *host = NULL;
915
    vlc_value_t lockval;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
916
917
    int fd = -1;
    struct addrinfo *res, *ptr;
918
919

    /* resolv */
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
920
921
922
923
924
#ifdef HAVE_GETADDRINFO
    {
        vlc_value_t val;
        char psz_port[6];
        struct addrinfo hints;
925
        int check;
926
927

        memset( &hints, 0, sizeof( hints ) );
928

929
930
931
932
933
        /* Check if ipv4 or ipv6 were forced */
        var_Create( p_this, "ipv4", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
        var_Get( p_this, "ipv4", &val );
        if( val.b_bool )
            hints.ai_family = PF_INET;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
934

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
935
936
        var_Create( p_this, "ipv6", VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
        var_Get( p_this, "ipv6", &val );
937
938
        if( val.b_bool )
            hints.ai_family = PF_INET6;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
939
940
941
942
943
944
945
946
947
948

        hints.ai_socktype = SOCK_STREAM;
        hints.ai_flags = AI_PASSIVE;

        if (*psz_host == '\0')
            psz_host = NULL;

        snprintf( psz_port, sizeof( psz_port ), "%d", i_port );
        psz_port[sizeof( psz_port ) - 1] = '\0';
        
949
950
        check = getaddrinfo( psz_host, psz_port, &hints, &res );
        if( check != 0 )
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
951
        {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
952
953
#ifdef HAVE_GAI_STRERROR
            msg_Err( p_this, "cannot resolve %s:%d : %s", psz_host, i_port,
954
                     gai_strerror( check ) );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
955
#else
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
956
            msg_Err( p_this, "cannot resolve %s:%d", psz_host, i_port );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
957
#endif
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
958
959
960
            return NULL;
        }
    }
961

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
962
963
964
965
966
967
968
969
970
971
972
973
974
975
#else
    struct sockaddr_in sock;
    struct httpd_addrinfo info;
    
    info.ai_family = PF_INET;
    info.ai_socktype = SOCK_STREAM;
    info.ai_protocol = 0;
    info.ai_addr = (struct sockaddr *)&sock;
    info.ai_addrlen = sizeof( sock );
    info.ai_next = NULL;
    
    res = &info;

    if( BuildAddr( &sock, psz_host, i_port ) )
976
977
978
979
980
    {
        msg_Err( p_this, "cannot build address for %s:%d", psz_host, i_port );
        return NULL;
    }

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
981
982
983
#   define freeaddrinfo( r ) (void)0;
#endif

984
985
986
987
988
    /* 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 );

989
    if( !(httpd = vlc_object_find( p_this, VLC_OBJECT_HTTPD, FIND_ANYWHERE )) )
990
991
992
993
994
    {
        msg_Info( p_this, "creating httpd" );
        if( ( httpd = vlc_object_create( p_this, VLC_OBJECT_HTTPD ) ) == NULL )
        {
            vlc_mutex_unlock( lockval.p_address );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
995
            freeaddrinfo( res );
996
997
998
999
1000
1001
1002
1003
1004
1005
            return NULL;
        }

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

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

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1006
    for( ptr = res; (ptr != NULL) && (fd == -1); ptr = ptr->ai_next )
1007
    {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1008
        int i;
1009

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1010
1011
1012
        if( ((unsigned)ptr->ai_addrlen) > sizeof( struct sockaddr_storage ) )
        {
            msg_Dbg( p_this, "socket address too big" );
1013
            continue;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1014
1015
1016
1017
        }

        /* verify if it already exist */
        for( i = 0; i < httpd->i_host; i++ )
1018
        {
1019
            if( GetAddrPort (&httpd->host[i]->sock) != i_port )
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1020
1021
                continue;

1022
            /* Cannot re-use host if it uses TLS/SSL */
1023
            if( httpd->host[i]->p_tls != NULL )
1024
1025
                continue;

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1026
1027
#ifdef AF_INET6
            if( httpd->host[i]->sock.ss_family == AF_INET6 )
1028
            {
gbazin's avatar
gbazin committed
1029
1030
1031
                const struct sockaddr_in6 *p_hsock, *p_sock;

                p_hsock = (const struct sockaddr_in6 *)&httpd->host[i]->sock;
1032
                p_sock = (const struct sockaddr_in6 *)ptr->ai_addr;
gbazin's avatar
gbazin committed
1033
1034
1035
1036
1037
1038
1039

                if( memcmp( &p_hsock->sin6_addr, &in6addr_any,
                            sizeof( struct in6_addr ) ) &&
                            ( p_sock->sin6_family != AF_INET6 ||
                              memcmp( &p_hsock->sin6_addr, &p_sock->sin6_addr,
                                      sizeof( struct in6_addr ) ) ) )
                    continue; /* does not match */
1040
            }
1041
            else if( ptr->ai_family == PF_INET6 )
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1042
1043
1044
1045
1046
                continue;
            else
#endif
            if( httpd->host[i]->sock.ss_family == AF_INET )
            {
gbazin's avatar
gbazin committed
1047
1048
1049
                const struct sockaddr_in *p_hsock, *p_sock;

                p_hsock = (const struct sockaddr_in *)&httpd->host[i]->sock;
1050
                p_sock = (const struct sockaddr_in *)ptr->ai_addr;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1051

gbazin's avatar
gbazin committed
1052
1053
1054
1055
                if( p_hsock->sin_addr.s_addr != INADDR_ANY &&
                    ( p_sock->sin_family != AF_INET ||
                      p_hsock->sin_addr.s_addr != p_sock->sin_addr.s_addr ) )
                    continue; /* does not match */
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1056
            }
1057
            else if( ptr->ai_family == PF_INET )
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1058
1059
1060
1061
1062
1063
1064
1065
1066
                continue;
            else
            {
                msg_Dbg( p_this, "host with unknown address family" );
                continue;
            }

            freeaddrinfo( res );

1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
            /* yep found */
            host = httpd->host[i];
            host->i_ref++;

            vlc_mutex_unlock( lockval.p_address );

            msg_Dbg( p_this, "host already registered" );
            return host;
        }

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1077
        /* create the listening socket */
1078
        fd = socket( ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol );
1079
        if( fd == -1 )
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
            continue;

        /* reuse socket */
        {
            int dummy = 1;
            if( setsockopt( fd, SOL_SOCKET, SO_REUSEADDR,
                            (void *)&dummy, sizeof( dummy ) ) < 0 )
            {
                msg_Warn( p_this, "cannot configure socket (SO_REUSEADDR)" );
            }
        }

        /* bind it */
1093
        if( bind( fd, ptr->ai_addr, ptr->ai_addrlen ) )
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1094
1095
        {
            msg_Err( p_this, "cannot bind socket" );
1096
            goto socket_error;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1097
1098
        }
        /* set to non-blocking */
1099
1100
#if defined( WIN32 ) || defined( UNDER_CE )
        {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1101
1102
1103
1104
            unsigned long i_dummy = 1;
            if( ioctlsocket( fd, FIONBIO, &i_dummy ) != 0 )
            {
                msg_Err( p_this, "cannot set socket to non-blocking mode" );
1105
                goto socket_error;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1106
            }
1107
1108
1109
        }
#else
        {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1110
1111
1112
1113
            unsigned int i_flags;
            if( ( i_flags = fcntl( fd, F_GETFL, 0 ) ) < 0 )
            {
                msg_Err( p_this, "cannot F_GETFL socket" );
1114
                goto socket_error;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1115
1116
1117
1118
            }
            if( fcntl( fd, F_SETFL, i_flags | O_NONBLOCK ) < 0 )
            {
                msg_Err( p_this, "cannot F_SETFL O_NONBLOCK" );
1119
                goto socket_error;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1120
            }
1121
        }
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1122
1123
1124
#endif
        /* listen */
        if( listen( fd, LISTEN_BACKLOG ) < 0 )
1125
        {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1126
            msg_Err( p_this, "cannot listen socket" );
1127
            goto socket_error;
1128
        }
1129

1130
        break; // success
1131
1132

socket_error:
gbazin's avatar
gbazin committed
1133
        net_Close( fd );
1134
        fd = -1;
1135
1136
    }

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1137
1138

    if( fd == -1 )
1139
1140
    {
        freeaddrinfo( res );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1141
        goto error;
1142
    }
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1143
1144
1145
1146
1147
1148
1149
1150

    /* 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;
    host->fd = fd;

1151
1152
    memcpy( &host->sock, ptr->ai_addr, ptr->ai_addrlen );
    host->i_sock_size = ptr->ai_addrlen;
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1153
1154
1155
1156
    host->i_url     = 0;
    host->url       = NULL;
    host->i_client  = 0;
    host->client    = NULL;
1157
1158

    freeaddrinfo( res );
1159
    host->p_tls = p_tls;
1160

1161
    /* create the thread */
1162
1163
    if( vlc_thread_create( host, "httpd host thread", httpd_HostThread,
                           VLC_THREAD_PRIORITY_LOW, VLC_FALSE ) )
1164
1165
    {
        msg_Err( p_this, "cannot spawn http host thread" );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1166
        goto error;
1167
1168
1169
1170
1171
1172
1173
1174
    }

    /* 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
1175
error:
1176
1177
    vlc_mutex_unlock( lockval.p_address );

Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1178
1179
1180
1181
    if( fd != -1 )
        net_Close( fd );

    if( host != NULL )
1182
    {
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1183
1184
        vlc_mutex_destroy( &host->lock );
        vlc_object_destroy( host );
1185
1186
1187
1188
1189
1190
1191
1192
    }

    /* TODO destroy no more used httpd TODO */
    vlc_object_release( httpd );
    return NULL;
}

/* delete a host */
1193
void httpd_HostDelete( httpd_host_t *host )
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
{
    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 );

    vlc_object_release( httpd );

    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" );
1231
1232
1233
1234
        httpd_ClientClean( cl );
        TAB_REMOVE( host->i_client, host->client, cl );
        free( cl );
        i--;
1235
1236
1237
        /* TODO */
    }

1238
1239
    if( host->p_tls != NULL)
        tls_ServerDelete( host->p_tls );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1240
    net_Close( host->fd );
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
    vlc_mutex_destroy( &host->lock );
    vlc_object_destroy( host );

    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 */
1254
1255
1256
static httpd_url_t *httpd_UrlNewPrivate( httpd_host_t *host, char *psz_url,
                                         char *psz_user, char *psz_password,
                                         vlc_bool_t b_check )
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
{
    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 : "" );
    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;
}

1295
1296
httpd_url_t *httpd_UrlNew( httpd_host_t *host, char *psz_url,
                           char *psz_user, char *psz_password )
1297
{
1298
1299
    return httpd_UrlNewPrivate( host, psz_url, psz_user,
                                psz_password, VLC_FALSE );
1300
1301
}

1302
1303
httpd_url_t *httpd_UrlNewUnique( httpd_host_t *host, char *psz_url,
                                 char *psz_user, char *psz_password )
1304
{
1305
1306
    return httpd_UrlNewPrivate( host, psz_url, psz_user,
                                psz_password, VLC_TRUE );
1307
1308
1309
}

/* register callback on a url */
1310
1311
int httpd_UrlCatch( httpd_url_t *url, int i_msg, httpd_callback_t cb,
                    httpd_callback_sys_t *p_sys )
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
{
    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 */
1323
void httpd_UrlDelete( httpd_url_t *url )
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
{
    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 );

    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" );
1344
            httpd_ClientClean( client );
1345
            TAB_REMOVE( host->i_client, host->client, client );
1346
            free( client );
1347
1348
1349
            i--;
        }
    }
1350
    free( url );
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
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
    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();
1456
    cl->i_activity_timeout = I64C(10000000);
1457
1458
1459
1460
1461
1462
1463
1464
1465
    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 );
}
1466

1467
1468
1469
1470
void httpd_ClientModeStream( httpd_client_t *cl )
{
    cl->i_mode   = HTTPD_CLIENT_STREAM;
}
1471

1472
1473
1474
1475
1476
void httpd_ClientModeBidir( httpd_client_t *cl )
{
    cl->i_mode   = HTTPD_CLIENT_BIDIR;
}

1477
1478
char* httpd_ClientIP( httpd_client_t *cl )
{
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
#ifdef HAVE_GETNAMEINFO
    char sz_ip[INET6_ADDRSTRLEN + 2];
    int i;

    if( (cl->sock.ss_family == AF_INET6) &&
        IN6_IS_ADDR_V4MAPPED( &((const struct sockaddr_in6 *)
                              &cl->sock)->sin6_addr) )
    {
        /* If client is using IPv4 but server is using IPv6 */
        struct sockaddr_in a;
        
        memset( &a, 0, sizeof( a ) );
        a.sin_family = AF_INET;
        a.sin_port = ((const struct sockaddr_in6 *)&cl->sock)->sin6_port;
        a.sin_addr.s_addr = ((const uint32_t *)&((const struct sockaddr_in6 *)
                            &cl->sock)->sin6_addr)[3];
        i = getnameinfo( (const struct sockaddr *)&a, sizeof( a ),
                         &sz_ip[1], INET6_ADDRSTRLEN, NULL, 0, NI_NUMERICHOST );
    }
    else
        i = getnameinfo( (const struct sockaddr *)&cl->sock, cl->i_sock_size,
                         &sz_ip[1], INET6_ADDRSTRLEN, NULL, 0,
                         NI_NUMERICHOST );

    if( i != 0 )
        /* FIXME: msg_Err */
        return NULL;
        
    if( strchr( &sz_ip[1], ':' ) != NULL )
    {
        *sz_ip = '[';
        i = strlen( sz_ip );
        sz_ip[i++] = ']';
        sz_ip[i] = '\0';
       
        return strdup( sz_ip );
    }
    
    return strdup( &sz_ip[1] );
gbazin's avatar
gbazin committed
1518
1519

#else
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1520
    /* FIXME not thread safe */
1521
    return strdup( inet_ntoa( ((const struct sockaddr_in *)&cl->sock)->sin_addr ) );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1522
#endif
1523
1524
}

1525
1526
static void httpd_ClientClean( httpd_client_t *cl )
{
1527
    if( cl->fd >= 0 )
1528
    {
1529
        if( cl->p_tls != NULL )
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1530
            tls_ServerSessionClose( cl->p_tls );
Rémi Denis-Courmont's avatar
Rémi Denis-Courmont committed
1531
        net_Close( cl->fd );
1532
        cl->fd = -1;
1533
1534
1535
1536
1537
1538
1539
1540
    }

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

    if( cl->p_buffer )
    {
        free( cl->p_buffer );
1541
        cl->p_buffer = NULL;
1542
1543
1544
    }
}

1545
static httpd_client_t *httpd_ClientNew( int fd, struct sockaddr_storage *sock,
1546
1547
                                        int i_sock_size,
                                        tls_session_t *p_tls )
1548
1549
1550
1551
{
    httpd_client_t *cl = malloc( sizeof( httpd_client_t ) );
    cl->i_ref   = 0;
    cl->fd      = fd;
1552
1553
    memcpy( &cl->sock, sock, sizeof( cl->sock ) );
    cl->i_sock_size = i_sock_size;
1554
    cl->url     = NULL;
1555
    cl->p_tls = p_tls;
1556
1557
1558
1559
1560
1561

    httpd_ClientInit( cl );

    return cl;
}

1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586

static int httpd_NetRecv( httpd_client_t *cl, char *p, int i_len )
{
    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 );
}


static int httpd_NetSend( httpd_client_t *cl, const char *p, int i_len )
{
    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 );
}


1587
1588
1589
1590
1591
1592
1593
static void httpd_ClientRecv( httpd_client_t *cl )
{
    int i_len;

    if( cl->query.i_proto == HTTPD_PROTO_NONE )
    {
        /* enought to see if it's rtp over rtsp or RTSP/HTTP */
1594
1595
        i_len = httpd_NetRecv( cl, &cl->p_buffer[cl->i_buffer],
                               4 - cl->i_buffer );
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
        if( i_len > 0 )
        {
            cl->i_buffer += i_len;
        }

        if( cl->i_buffer >= 4 )
        {
            fprintf( stderr, "peek=%4.4s\n", cl->p_buffer );
            /* 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;
            }
            else if( !strncmp( cl->p_buffer, "HTTP", 4 ) )
            {
                cl->query.i_proto = HTTPD_PROTO_HTTP;
                cl->query.i_type  = HTTPD_MSG_ANSWER;
            }
            else if( !strncmp( cl->p_buffer, "RTSP", 4 ) )
            {
                cl->query.i_proto = HTTPD_PROTO_RTSP;
                cl->query.i_type  = HTTPD_MSG_ANSWER;
            }
1626
1627
1628
            else if( !strncmp( cl->p_buffer, "GET", 3 ) ||
                     !strncmp( cl->p_buffer, "HEAD", 4 ) ||
                     !strncmp( cl->p_buffer, "POST", 4 ) )
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
            {
                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 */
1643
1644
        i_len = httpd_NetRecv( cl, &cl->query.p_body[cl->i_buffer],
                               cl->query.i_body - cl->i_buffer );
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
        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( ;; )
        {
1659
            i_len = httpd_NetRecv (cl, &cl->p_buffer[cl->i_buffer], 1 );
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
            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 );
            }
            if( ( cl->i_buffer >= 2 && !strncmp( &cl->p_buffer[cl->i_buffer-2], "\n\n", 2 ) )||
                ( cl->i_buffer >= 4 && !strncmp( &cl->p_buffer[cl->i_buffer-4], "\r\n\r\n", 4 ) ) )
            {
                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 )
                {
1681
1682
                    cl->query.i_status =
                        strtol( &cl->p_buffer[strlen( "HTTP/1.x" )], &p, 0 );
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
1714
1715
1716
1717
1718
1719
1720
                    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;

                    fprintf( stderr, "received new request=%s\n", cl->p_buffer);

                    for( i = 0; msg_type[i].name != NULL; i++ )
                    {
1721
1722
                        if( !strncmp( cl->p_buffer, msg_type[i].name,
                                      strlen( msg_type[i].name ) ) )
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785