]> git.sesse.net Git - vlc/blob - modules/stream_out/rtsp.c
rtsp: fix authentication variables
[vlc] / modules / stream_out / rtsp.c
1 /*****************************************************************************
2  * rtsp.c: RTSP support for RTP stream output module
3  *****************************************************************************
4  * Copyright (C) 2003-2004, 2010 the VideoLAN team
5  * Copyright © 2007 Rémi Denis-Courmont
6  *
7  * $Id$
8  *
9  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
10  *          Pierre Ynard
11  *
12  * This program is free software; you can redistribute it and/or modify
13  * it under the terms of the GNU General Public License as published by
14  * the Free Software Foundation; either version 2 of the License, or
15  * (at your option) any later version.
16  *
17  * This program is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20  * GNU General Public License for more details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with this program; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
25  *****************************************************************************/
26
27 /*****************************************************************************
28  * Preamble
29  *****************************************************************************/
30 #ifdef HAVE_CONFIG_H
31 # include "config.h"
32 #endif
33
34 #include <vlc_common.h>
35 #include <vlc_sout.h>
36
37 #include <vlc_httpd.h>
38 #include <vlc_url.h>
39 #include <vlc_charset.h>
40 #include <vlc_fs.h>
41 #include <vlc_network.h>
42 #include <vlc_rand.h>
43 #include <assert.h>
44 #include <errno.h>
45 #include <stdlib.h>
46 #include <time.h>
47
48 #ifndef WIN32
49 # include <locale.h>
50 #endif
51 #ifdef HAVE_XLOCALE_H
52 # include <xlocale.h>
53 #endif
54
55 #include "rtp.h"
56
57 typedef struct rtsp_session_t rtsp_session_t;
58
59 struct rtsp_stream_t
60 {
61     vlc_mutex_t     lock;
62     vlc_object_t   *owner;
63     vod_media_t    *vod_media;
64     httpd_host_t   *host;
65     httpd_url_t    *url;
66     char           *psz_path;
67     unsigned        track_id;
68
69     int             sessionc;
70     rtsp_session_t **sessionv;
71
72     int             timeout;
73     vlc_timer_t     timer;
74 };
75
76
77 static int  RtspCallback( httpd_callback_sys_t *p_args,
78                           httpd_client_t *cl, httpd_message_t *answer,
79                           const httpd_message_t *query );
80 static int  RtspCallbackId( httpd_callback_sys_t *p_args,
81                             httpd_client_t *cl, httpd_message_t *answer,
82                             const httpd_message_t *query );
83 static void RtspClientDel( rtsp_stream_t *rtsp, rtsp_session_t *session );
84
85 static void RtspTimeOut( void *data );
86
87 rtsp_stream_t *RtspSetup( vlc_object_t *owner, vod_media_t *media,
88                           const char *path )
89 {
90     rtsp_stream_t *rtsp = malloc( sizeof( *rtsp ) );
91
92     if( rtsp == NULL )
93     {
94         free( rtsp );
95         return NULL;
96     }
97
98     rtsp->owner = owner;
99     rtsp->vod_media = media;
100     rtsp->sessionc = 0;
101     rtsp->sessionv = NULL;
102     rtsp->host = NULL;
103     rtsp->url = NULL;
104     rtsp->psz_path = NULL;
105     rtsp->track_id = 0;
106     vlc_mutex_init( &rtsp->lock );
107
108     rtsp->timeout = var_InheritInteger(owner, "rtsp-timeout");
109     if (rtsp->timeout > 0)
110     {
111         if (vlc_timer_create(&rtsp->timer, RtspTimeOut, rtsp))
112             goto error;
113     }
114
115     rtsp->psz_path = strdup( (path != NULL) ? path : "/" );
116     if( rtsp->psz_path == NULL )
117         goto error;
118
119     msg_Dbg( owner, "RTSP stream at %s", rtsp->psz_path );
120
121     rtsp->host = vlc_rtsp_HostNew( VLC_OBJECT(owner) );
122     if( rtsp->host == NULL )
123         goto error;
124
125     char *user = var_InheritString(owner, "sout-rtsp-user");
126     char *pwd = var_InheritString(owner, "sout-rtsp-pwd");
127
128     rtsp->url = httpd_UrlNewUnique( rtsp->host, rtsp->psz_path,
129                                     user, pwd, NULL );
130     free(user);
131     free(pwd);
132     if( rtsp->url == NULL )
133         goto error;
134
135     httpd_UrlCatch( rtsp->url, HTTPD_MSG_DESCRIBE, RtspCallback, (void*)rtsp );
136     httpd_UrlCatch( rtsp->url, HTTPD_MSG_SETUP,    RtspCallback, (void*)rtsp );
137     httpd_UrlCatch( rtsp->url, HTTPD_MSG_PLAY,     RtspCallback, (void*)rtsp );
138     httpd_UrlCatch( rtsp->url, HTTPD_MSG_PAUSE,    RtspCallback, (void*)rtsp );
139     httpd_UrlCatch( rtsp->url, HTTPD_MSG_GETPARAMETER, RtspCallback,
140                     (void*)rtsp );
141     httpd_UrlCatch( rtsp->url, HTTPD_MSG_TEARDOWN, RtspCallback, (void*)rtsp );
142     return rtsp;
143
144 error:
145     RtspUnsetup( rtsp );
146     return NULL;
147 }
148
149
150 void RtspUnsetup( rtsp_stream_t *rtsp )
151 {
152     if( rtsp->url )
153         httpd_UrlDelete( rtsp->url );
154
155     if( rtsp->host )
156         httpd_HostDelete( rtsp->host );
157
158     while( rtsp->sessionc > 0 )
159         RtspClientDel( rtsp, rtsp->sessionv[0] );
160
161     if (rtsp->timeout > 0)
162         vlc_timer_destroy(rtsp->timer);
163
164     free( rtsp->psz_path );
165     vlc_mutex_destroy( &rtsp->lock );
166
167     free( rtsp );
168 }
169
170
171 struct rtsp_stream_id_t
172 {
173     rtsp_stream_t    *stream;
174     sout_stream_id_t *sout_id;
175     httpd_url_t      *url;
176     unsigned          track_id;
177     uint32_t          ssrc;
178     unsigned          clock_rate; /* needed to compute rtptime in RTP-Info */
179     int               mcast_fd;
180 };
181
182
183 typedef struct rtsp_strack_t rtsp_strack_t;
184
185 /* For unicast streaming */
186 struct rtsp_session_t
187 {
188     rtsp_stream_t *stream;
189     uint64_t       id;
190     mtime_t        last_seen; /* for timeouts */
191
192     /* output (id-access) */
193     int            trackc;
194     rtsp_strack_t *trackv;
195 };
196
197
198 /* Unicast session track */
199 struct rtsp_strack_t
200 {
201     rtsp_stream_id_t  *id;
202     sout_stream_id_t  *sout_id;
203     int          setup_fd;  /* socket created by the SETUP request */
204     int          rtp_fd;    /* socket used by the RTP output, when playing */
205     uint32_t     ssrc;
206     uint16_t     seq_init;
207 };
208
209 static void RtspTrackClose( rtsp_strack_t *tr );
210
211 #define TRACK_PATH_SIZE (sizeof("/trackID=999") - 1)
212
213 char *RtspAppendTrackPath( rtsp_stream_id_t *id, const char *base )
214 {
215     const char *sep = strlen( base ) > 0 && base[strlen( base ) - 1] == '/' ?
216                       "" : "/";
217     char *url;
218
219     if( asprintf( &url, "%s%strackID=%u", base, sep, id->track_id ) == -1 )
220         url = NULL;
221     return url;
222 }
223
224
225 rtsp_stream_id_t *RtspAddId( rtsp_stream_t *rtsp, sout_stream_id_t *sid,
226                              uint32_t ssrc, unsigned clock_rate,
227                              int mcast_fd)
228 {
229     if (rtsp->track_id > 999)
230     {
231         msg_Err(rtsp->owner, "RTSP: too many IDs!");
232         return NULL;
233     }
234
235     char *urlbuf;
236     rtsp_stream_id_t *id = malloc( sizeof( *id ) );
237     httpd_url_t *url;
238
239     if( id == NULL )
240         return NULL;
241
242     id->stream = rtsp;
243     id->sout_id = sid;
244     id->track_id = rtsp->track_id;
245     id->ssrc = ssrc;
246     id->clock_rate = clock_rate;
247     id->mcast_fd = mcast_fd;
248
249     urlbuf = RtspAppendTrackPath( id, rtsp->psz_path );
250     if( urlbuf == NULL )
251     {
252         free( id );
253         return NULL;
254     }
255
256     msg_Dbg( rtsp->owner, "RTSP: adding %s", urlbuf );
257
258     char *user = var_InheritString(rtsp->owner, "sout-rtsp-user");
259     char *pwd = var_InheritString(rtsp->owner, "sout-rtsp-pwd");
260
261     url = id->url = httpd_UrlNewUnique( rtsp->host, urlbuf, user, pwd, NULL );
262     free( user );
263     free( pwd );
264     free( urlbuf );
265
266     if( url == NULL )
267     {
268         free( id );
269         return NULL;
270     }
271
272     httpd_UrlCatch( url, HTTPD_MSG_DESCRIBE, RtspCallbackId, (void *)id );
273     httpd_UrlCatch( url, HTTPD_MSG_SETUP,    RtspCallbackId, (void *)id );
274     httpd_UrlCatch( url, HTTPD_MSG_PLAY,     RtspCallbackId, (void *)id );
275     httpd_UrlCatch( url, HTTPD_MSG_PAUSE,    RtspCallbackId, (void *)id );
276     httpd_UrlCatch( url, HTTPD_MSG_GETPARAMETER, RtspCallbackId, (void *)id );
277     httpd_UrlCatch( url, HTTPD_MSG_TEARDOWN, RtspCallbackId, (void *)id );
278
279     rtsp->track_id++;
280
281     return id;
282 }
283
284
285 void RtspDelId( rtsp_stream_t *rtsp, rtsp_stream_id_t *id )
286 {
287     httpd_UrlDelete( id->url );
288
289     vlc_mutex_lock( &rtsp->lock );
290     for( int i = 0; i < rtsp->sessionc; i++ )
291     {
292         rtsp_session_t *ses = rtsp->sessionv[i];
293
294         for( int j = 0; j < ses->trackc; j++ )
295         {
296             if( ses->trackv[j].id == id )
297             {
298                 rtsp_strack_t *tr = ses->trackv + j;
299                 RtspTrackClose( tr );
300                 REMOVE_ELEM( ses->trackv, ses->trackc, j );
301             }
302         }
303     }
304
305     vlc_mutex_unlock( &rtsp->lock );
306     free( id );
307 }
308
309
310 /** rtsp must be locked */
311 static void RtspUpdateTimer( rtsp_stream_t *rtsp )
312 {
313     if (rtsp->timeout <= 0)
314         return;
315
316     mtime_t timeout = 0;
317     for (int i = 0; i < rtsp->sessionc; i++)
318     {
319         if (timeout == 0 || rtsp->sessionv[i]->last_seen < timeout)
320             timeout = rtsp->sessionv[i]->last_seen;
321     }
322     if (timeout != 0)
323         timeout += rtsp->timeout * CLOCK_FREQ;
324     vlc_timer_schedule(rtsp->timer, true, timeout, 0);
325 }
326
327
328 static void RtspTimeOut( void *data )
329 {
330     rtsp_stream_t *rtsp = data;
331
332     vlc_mutex_lock(&rtsp->lock);
333     mtime_t now = mdate();
334     for (int i = rtsp->sessionc - 1; i >= 0; i--)
335     {
336         if (rtsp->sessionv[i]->last_seen + rtsp->timeout * CLOCK_FREQ < now)
337         {
338             if (rtsp->vod_media != NULL)
339             {
340                 char psz_sesbuf[17];
341                 snprintf( psz_sesbuf, sizeof( psz_sesbuf ), "%"PRIx64,
342                           rtsp->sessionv[i]->id );
343                 vod_stop(rtsp->vod_media, psz_sesbuf);
344             }
345             RtspClientDel(rtsp, rtsp->sessionv[i]);
346         }
347     }
348     RtspUpdateTimer(rtsp);
349     vlc_mutex_unlock(&rtsp->lock);
350 }
351
352
353 /** rtsp must be locked */
354 static
355 rtsp_session_t *RtspClientNew( rtsp_stream_t *rtsp )
356 {
357     rtsp_session_t *s = malloc( sizeof( *s ) );
358     if( s == NULL )
359         return NULL;
360
361     s->stream = rtsp;
362     vlc_rand_bytes (&s->id, sizeof (s->id));
363     s->trackc = 0;
364     s->trackv = NULL;
365
366     TAB_APPEND( rtsp->sessionc, rtsp->sessionv, s );
367
368     return s;
369 }
370
371
372 /** rtsp must be locked */
373 static
374 rtsp_session_t *RtspClientGet( rtsp_stream_t *rtsp, const char *name )
375 {
376     char *end;
377     uint64_t id;
378     int i;
379
380     if( name == NULL )
381         return NULL;
382
383     errno = 0;
384     id = strtoull( name, &end, 0x10 );
385     if( errno || *end )
386         return NULL;
387
388     /* FIXME: use a hash/dictionary */
389     for( i = 0; i < rtsp->sessionc; i++ )
390     {
391         if( rtsp->sessionv[i]->id == id )
392             return rtsp->sessionv[i];
393     }
394     return NULL;
395 }
396
397
398 /** rtsp must be locked */
399 static
400 void RtspClientDel( rtsp_stream_t *rtsp, rtsp_session_t *session )
401 {
402     int i;
403     TAB_REMOVE( rtsp->sessionc, rtsp->sessionv, session );
404
405     for( i = 0; i < session->trackc; i++ )
406         RtspTrackClose( &session->trackv[i] );
407
408     free( session->trackv );
409     free( session );
410 }
411
412
413 /** rtsp must be locked */
414 static void RtspClientAlive( rtsp_session_t *session )
415 {
416     if (session->stream->timeout <= 0)
417         return;
418
419     session->last_seen = mdate();
420     RtspUpdateTimer(session->stream);
421 }
422
423 static int dup_socket(int oldfd)
424 {
425     int newfd;
426 #if !defined(WIN32) || defined(UNDER_CE)
427     newfd = vlc_dup(oldfd);
428 #else
429     WSAPROTOCOL_INFO info;
430     WSADuplicateSocket (oldfd, GetCurrentProcessId (), &info);
431     newfd = WSASocket (info.iAddressFamily, info.iSocketType,
432                        info.iProtocol, &info, 0, 0);
433 #endif
434     return newfd;
435 }
436
437 /* Attach a starting VoD RTP id to its RTSP track, and let it
438  * initialize with the parameters of the SETUP request */
439 int RtspTrackAttach( rtsp_stream_t *rtsp, const char *name,
440                      rtsp_stream_id_t *id, sout_stream_id_t *sout_id,
441                      uint32_t *ssrc, uint16_t *seq_init )
442 {
443     int val = VLC_EGENERIC;
444     rtsp_session_t *session;
445
446     vlc_mutex_lock(&rtsp->lock);
447     session = RtspClientGet(rtsp, name);
448
449     if (session == NULL)
450         goto out;
451
452     rtsp_strack_t *tr = NULL;
453     for (int i = 0; i < session->trackc; i++)
454     {
455         if (session->trackv[i].id == id)
456         {
457             tr = session->trackv + i;
458             break;
459         }
460     }
461
462     if (tr != NULL)
463     {
464         tr->sout_id = sout_id;
465         tr->rtp_fd = dup_socket(tr->setup_fd);
466     }
467     else
468     {
469         /* The track was not SETUP. We still create one because we'll
470          * need the sout_id if we set it up later. */
471         rtsp_strack_t track = { .id = id, .sout_id = sout_id,
472                                 .setup_fd = -1, .rtp_fd = -1 };
473         vlc_rand_bytes (&track.seq_init, sizeof (track.seq_init));
474         vlc_rand_bytes (&track.ssrc, sizeof (track.ssrc));
475
476         INSERT_ELEM(session->trackv, session->trackc, session->trackc, track);
477         tr = session->trackv + session->trackc - 1;
478     }
479
480     *ssrc = ntohl(tr->ssrc);
481     *seq_init = tr->seq_init;
482
483     if (tr->rtp_fd != -1)
484     {
485         uint16_t seq;
486         rtp_add_sink(tr->sout_id, tr->rtp_fd, false, &seq);
487         /* To avoid race conditions, sout_id->i_seq_sent_next must
488          * be set here and now. Make sure the caller did its job
489          * properly when passing seq_init. */
490         assert(tr->seq_init == seq);
491     }
492
493     val = VLC_SUCCESS;
494 out:
495     vlc_mutex_unlock(&rtsp->lock);
496     return val;
497 }
498
499
500 /* Remove references to the RTP id when it is stopped */
501 void RtspTrackDetach( rtsp_stream_t *rtsp, const char *name,
502                       sout_stream_id_t *sout_id )
503 {
504     rtsp_session_t *session;
505
506     vlc_mutex_lock(&rtsp->lock);
507     session = RtspClientGet(rtsp, name);
508
509     if (session == NULL)
510         goto out;
511
512     for (int i = 0; i < session->trackc; i++)
513     {
514         rtsp_strack_t *tr = session->trackv + i;
515         if (tr->sout_id == sout_id)
516         {
517             if (tr->setup_fd == -1)
518             {
519                 /* No (more) SETUP information: better get rid of the
520                  * track so that we can have new random ssrc and
521                  * seq_init next time. */
522                 REMOVE_ELEM( session->trackv, session->trackc, i );
523                 break;
524             }
525             /* We keep the SETUP information of the track, but stop it */
526             if (tr->rtp_fd != -1)
527             {
528                 rtp_del_sink(tr->sout_id, tr->rtp_fd);
529                 tr->rtp_fd = -1;
530             }
531             tr->sout_id = NULL;
532             break;
533         }
534     }
535
536 out:
537     vlc_mutex_unlock(&rtsp->lock);
538 }
539
540
541 /** rtsp must be locked */
542 static void RtspTrackClose( rtsp_strack_t *tr )
543 {
544     if (tr->setup_fd != -1)
545     {
546         if (tr->rtp_fd != -1)
547         {
548             rtp_del_sink(tr->sout_id, tr->rtp_fd);
549             tr->rtp_fd = -1;
550         }
551         net_Close(tr->setup_fd);
552         tr->setup_fd = -1;
553     }
554 }
555
556
557 /** Finds the next transport choice */
558 static inline const char *transport_next( const char *str )
559 {
560     /* Looks for comma */
561     str = strchr( str, ',' );
562     if( str == NULL )
563         return NULL; /* No more transport options */
564
565     str++; /* skips comma */
566     while( strchr( "\r\n\t ", *str ) )
567         str++;
568
569     return (*str) ? str : NULL;
570 }
571
572
573 /** Finds the next transport parameter */
574 static inline const char *parameter_next( const char *str )
575 {
576     while( strchr( ",;", *str ) == NULL )
577         str++;
578
579     return (*str == ';') ? (str + 1) : NULL;
580 }
581
582
583 static int64_t ParseNPT (const char *str)
584 {
585     locale_t loc = newlocale (LC_NUMERIC_MASK, "C", NULL);
586     locale_t oldloc = uselocale (loc);
587     unsigned hour, min;
588     float sec;
589
590     if (sscanf (str, "%u:%u:%f", &hour, &min, &sec) == 3)
591         sec += ((hour * 60) + min) * 60;
592     else
593     if (sscanf (str, "%f", &sec) != 1)
594         sec = -1;
595
596     if (loc != (locale_t)0)
597     {
598         uselocale (oldloc);
599         freelocale (loc);
600     }
601     return sec < 0 ? -1 : sec * CLOCK_FREQ;
602 }
603
604
605 /** RTSP requests handler
606  * @param id selected track for non-aggregate URLs,
607  *           NULL for aggregate URLs
608  */
609 static int RtspHandler( rtsp_stream_t *rtsp, rtsp_stream_id_t *id,
610                         httpd_client_t *cl,
611                         httpd_message_t *answer,
612                         const httpd_message_t *query )
613 {
614     vlc_object_t *owner = rtsp->owner;
615     char psz_sesbuf[17];
616     const char *psz_session = NULL, *psz;
617     char control[sizeof("rtsp://[]:12345") + NI_MAXNUMERICHOST
618                   + strlen( rtsp->psz_path )];
619     bool vod = rtsp->vod_media != NULL;
620     time_t now;
621
622     time (&now);
623
624     if( answer == NULL || query == NULL || cl == NULL )
625         return VLC_SUCCESS;
626     else
627     {
628         /* Build self-referential control URL */
629         char ip[NI_MAXNUMERICHOST], *ptr;
630         int port;
631
632         httpd_ServerIP( cl, ip, &port );
633         ptr = strchr( ip, '%' );
634         if( ptr != NULL )
635             *ptr = '\0';
636
637         if( strchr( ip, ':' ) != NULL )
638             sprintf( control, "rtsp://[%s]:%d%s", ip, port, rtsp->psz_path );
639         else
640             sprintf( control, "rtsp://%s:%d%s", ip, port, rtsp->psz_path );
641     }
642
643     /* */
644     answer->i_proto = HTTPD_PROTO_RTSP;
645     answer->i_version= 0;
646     answer->i_type   = HTTPD_MSG_ANSWER;
647     answer->i_body = 0;
648     answer->p_body = NULL;
649
650     httpd_MsgAdd( answer, "Server", "VLC/%s", VERSION );
651
652     /* Date: is always allowed, and sometimes mandatory with RTSP/2.0. */
653     struct tm ut;
654     if (gmtime_r (&now, &ut) != NULL)
655     {   /* RFC1123 format, GMT is mandatory */
656         static const char wdays[7][4] = {
657             "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
658         static const char mons[12][4] = {
659             "Jan", "Feb", "Mar", "Apr", "May", "Jun",
660             "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
661         httpd_MsgAdd (answer, "Date", "%s, %02u %s %04u %02u:%02u:%02u GMT",
662                       wdays[ut.tm_wday], ut.tm_mday, mons[ut.tm_mon],
663                       1900 + ut.tm_year, ut.tm_hour, ut.tm_min, ut.tm_sec);
664     }
665
666     if( query->i_proto != HTTPD_PROTO_RTSP )
667     {
668         answer->i_status = 505;
669     }
670     else
671     if( httpd_MsgGet( query, "Require" ) != NULL )
672     {
673         answer->i_status = 551;
674         httpd_MsgAdd( answer, "Unsupported", "%s",
675                       httpd_MsgGet( query, "Require" ) );
676     }
677     else
678     switch( query->i_type )
679     {
680         case HTTPD_MSG_DESCRIBE:
681         {   /* Aggregate-only */
682             if( id != NULL )
683             {
684                 answer->i_status = 460;
685                 break;
686             }
687
688             answer->i_status = 200;
689             httpd_MsgAdd( answer, "Content-Type",  "%s", "application/sdp" );
690             httpd_MsgAdd( answer, "Content-Base",  "%s", control );
691
692             answer->p_body = (uint8_t *) ( vod ?
693                 SDPGenerateVoD( rtsp->vod_media, control ) :
694                 SDPGenerate( (sout_stream_t *)owner, control ) );
695             if( answer->p_body != NULL )
696                 answer->i_body = strlen( (char *)answer->p_body );
697             else
698                 answer->i_status = 500;
699             break;
700         }
701
702         case HTTPD_MSG_SETUP:
703             /* Non-aggregate-only */
704             if( id == NULL )
705             {
706                 answer->i_status = 459;
707                 break;
708             }
709
710             psz_session = httpd_MsgGet( query, "Session" );
711             answer->i_status = 461;
712
713             for( const char *tpt = httpd_MsgGet( query, "Transport" );
714                  tpt != NULL;
715                  tpt = transport_next( tpt ) )
716             {
717                 bool b_multicast = true, b_unsupp = false;
718                 unsigned loport = 5004, hiport; /* from RFC3551 */
719
720                 /* Check transport protocol. */
721                 /* Currently, we only support RTP/AVP over UDP */
722                 if( strncmp( tpt, "RTP/AVP", 7 ) )
723                     continue;
724                 tpt += 7;
725                 if( strncmp( tpt, "/UDP", 4 ) == 0 )
726                     tpt += 4;
727                 if( strchr( ";,", *tpt ) == NULL )
728                     continue;
729
730                 /* Parse transport options */
731                 for( const char *opt = parameter_next( tpt );
732                      opt != NULL;
733                      opt = parameter_next( opt ) )
734                 {
735                     if( strncmp( opt, "multicast", 9 ) == 0)
736                         b_multicast = true;
737                     else
738                     if( strncmp( opt, "unicast", 7 ) == 0 )
739                         b_multicast = false;
740                     else
741                     if( sscanf( opt, "client_port=%u-%u", &loport, &hiport )
742                                 == 2 )
743                         ;
744                     else
745                     if( strncmp( opt, "mode=", 5 ) == 0 )
746                     {
747                         if( strncasecmp( opt + 5, "play", 4 )
748                          && strncasecmp( opt + 5, "\"PLAY\"", 6 ) )
749                         {
750                             /* Not playing?! */
751                             b_unsupp = true;
752                             break;
753                         }
754                     }
755                     else
756                     if( strncmp( opt,"destination=", 12 ) == 0 )
757                     {
758                         answer->i_status = 403;
759                         b_unsupp = true;
760                     }
761                     else
762                     {
763                     /*
764                      * Every other option is unsupported:
765                      *
766                      * "source" and "append" are invalid (server-only);
767                      * "ssrc" also (as clarified per RFC2326bis).
768                      *
769                      * For multicast, "port", "layers", "ttl" are set by the
770                      * stream output configuration.
771                      *
772                      * For unicast, we want to decide "server_port" values.
773                      *
774                      * "interleaved" is not implemented.
775                      */
776                         b_unsupp = true;
777                         break;
778                     }
779                 }
780
781                 if( b_unsupp )
782                     continue;
783
784                 if( b_multicast )
785                 {
786                     char dst[NI_MAXNUMERICHOST];
787                     int dport, ttl;
788                     if( id->mcast_fd == -1 )
789                         continue;
790
791                     net_GetPeerAddress(id->mcast_fd, dst, &dport);
792
793                     ttl = var_InheritInteger(owner, "ttl");
794                     if (ttl <= 0)
795                     /* FIXME: the TTL is left to the OS default, we can
796                      * only guess that it's 1. */
797                         ttl = 1;
798
799                     if( psz_session == NULL )
800                     {
801                         /* Create a dummy session ID */
802                         snprintf( psz_sesbuf, sizeof( psz_sesbuf ), "%lu",
803                                   vlc_mrand48() );
804                         psz_session = psz_sesbuf;
805                     }
806                     answer->i_status = 200;
807
808                     httpd_MsgAdd( answer, "Transport",
809                                   "RTP/AVP/UDP;destination=%s;port=%u-%u;"
810                                   "ttl=%d;mode=play",
811                                   dst, dport, dport + 1, ttl );
812                      /* FIXME: this doesn't work with RTP + RTCP mux */
813                 }
814                 else
815                 {
816                     char ip[NI_MAXNUMERICHOST], src[NI_MAXNUMERICHOST];
817                     rtsp_session_t *ses = NULL;
818                     int fd, sport;
819                     uint32_t ssrc;
820
821                     if( httpd_ClientIP( cl, ip, NULL ) == NULL )
822                     {
823                         answer->i_status = 500;
824                         continue;
825                     }
826
827                     fd = net_ConnectDgram( owner, ip, loport, -1,
828                                            IPPROTO_UDP );
829                     if( fd == -1 )
830                     {
831                         msg_Err( owner,
832                                  "cannot create RTP socket for %s port %u",
833                                  ip, loport );
834                         answer->i_status = 500;
835                         continue;
836                     }
837
838                     /* Ignore any unexpected incoming packet */
839                     setsockopt (fd, SOL_SOCKET, SO_RCVBUF, &(int){ 0 },
840                                 sizeof (int));
841                     net_GetSockAddress( fd, src, &sport );
842
843                     vlc_mutex_lock( &rtsp->lock );
844                     if( psz_session == NULL )
845                     {
846                         ses = RtspClientNew( rtsp );
847                         snprintf( psz_sesbuf, sizeof( psz_sesbuf ), "%"PRIx64,
848                                   ses->id );
849                         psz_session = psz_sesbuf;
850                     }
851                     else
852                     {
853                         ses = RtspClientGet( rtsp, psz_session );
854                         if( ses == NULL )
855                         {
856                             answer->i_status = 454;
857                             vlc_mutex_unlock( &rtsp->lock );
858                             net_Close( fd );
859                             continue;
860                         }
861                     }
862                     RtspClientAlive(ses);
863
864                     rtsp_strack_t *tr = NULL;
865                     for (int i = 0; i < ses->trackc; i++)
866                     {
867                         if (ses->trackv[i].id == id)
868                         {
869                             tr = ses->trackv + i;
870                             break;
871                         }
872                     }
873
874                     if (tr == NULL)
875                     {
876                         /* Set up a new track */
877                         rtsp_strack_t track = { .id = id,
878                                                 .sout_id = id->sout_id,
879                                                 .setup_fd = fd,
880                                                 .rtp_fd = -1 };
881
882                         if (vod)
883                         {
884                             vlc_rand_bytes (&track.seq_init,
885                                             sizeof (track.seq_init));
886                             vlc_rand_bytes (&track.ssrc, sizeof (track.ssrc));
887                             ssrc = track.ssrc;
888                         }
889                         else
890                             ssrc = id->ssrc;
891
892                         INSERT_ELEM( ses->trackv, ses->trackc, ses->trackc,
893                                      track );
894                     }
895                     else if (tr->setup_fd == -1)
896                     {
897                         /* The track was not SETUP, but it exists
898                          * because there is a sout_id running for it */
899                         tr->setup_fd = fd;
900                         ssrc = tr->ssrc;
901                     }
902                     else
903                     {
904                         /* The track is already set up, and we don't
905                          * support changing the transport parameters on
906                          * the fly */
907                         vlc_mutex_unlock( &rtsp->lock );
908                         answer->i_status = 455;
909                         net_Close( fd );
910                         break;
911                     }
912                     vlc_mutex_unlock( &rtsp->lock );
913
914                     httpd_ServerIP( cl, ip, NULL );
915
916                     /* Specify source IP only if it is different from the
917                      * RTSP control connection server address */
918                     if( strcmp( src, ip ) )
919                     {
920                         char *ptr = strchr( src, '%' );
921                         if( ptr != NULL ) *ptr = '\0'; /* remove scope ID */
922                     }
923                     else
924                         src[0] = '\0';
925
926                     httpd_MsgAdd( answer, "Transport",
927                                   "RTP/AVP/UDP;unicast%s%s;"
928                                   "client_port=%u-%u;server_port=%u-%u;"
929                                   "ssrc=%08X;mode=play",
930                                   src[0] ? ";source=" : "", src,
931                                   loport, loport + 1, sport, sport + 1, ssrc );
932
933                     answer->i_status = 200;
934                 }
935                 break;
936             }
937             break;
938
939         case HTTPD_MSG_PLAY:
940         {
941             rtsp_session_t *ses;
942             answer->i_status = 200;
943
944             psz_session = httpd_MsgGet( query, "Session" );
945             int64_t start = -1, end = -1, npt;
946             const char *range = httpd_MsgGet (query, "Range");
947             if (range != NULL)
948             {
949                 if (strncmp (range, "npt=", 4))
950                 {
951                     answer->i_status = 501;
952                     break;
953                 }
954
955                 start = ParseNPT (range + 4);
956                 range = strchr(range, '-');
957                 if (range != NULL && *(range + 1))
958                     end = ParseNPT (range + 1);
959
960                 if (end >= 0 && end < start)
961                 {
962                     answer->i_status = 457;
963                     break;
964                 }
965
966                 if (vod)
967                 {
968                     if (vod_check_range(rtsp->vod_media, psz_session,
969                                         start, end) != VLC_SUCCESS)
970                     {
971                         answer->i_status = 457;
972                         break;
973                     }
974                 }
975                 /* We accept start times of 0 even for broadcast streams
976                  * that already started */
977                 else if (start > 0 || end >= 0)
978                 {
979                     answer->i_status = 456;
980                     break;
981                 }
982             }
983             vlc_mutex_lock( &rtsp->lock );
984             ses = RtspClientGet( rtsp, psz_session );
985             if( ses != NULL )
986             {
987                 char info[ses->trackc * ( strlen( control ) + TRACK_PATH_SIZE
988                           + sizeof("url=;seq=65535;rtptime=4294967295, ")
989                                           - 1 ) + 1];
990                 size_t infolen = 0;
991                 RtspClientAlive(ses);
992
993                 sout_stream_id_t *sout_id = NULL;
994                 if (vod)
995                 {
996                     /* We don't keep a reference to the sout_stream_t,
997                      * so we check if a sout_id is available instead. */
998                     for (int i = 0; i < ses->trackc; i++)
999                     {
1000                         sout_id = ses->trackv[i].sout_id;
1001                         if (sout_id != NULL)
1002                             break;
1003                     }
1004                 }
1005                 int64_t ts = rtp_get_ts(vod ? NULL : (sout_stream_t *)owner,
1006                                         sout_id, rtsp->vod_media, psz_session,
1007                                         vod ? NULL : &npt);
1008
1009                 for( int i = 0; i < ses->trackc; i++ )
1010                 {
1011                     rtsp_strack_t *tr = ses->trackv + i;
1012                     if( ( id == NULL ) || ( tr->id == id ) )
1013                     {
1014                         if (tr->setup_fd == -1)
1015                             /* Track not SETUP */
1016                             continue;
1017
1018                         uint16_t seq;
1019                         if( tr->rtp_fd == -1 )
1020                         {
1021                             /* Track not PLAYing yet */
1022                             if (tr->sout_id == NULL)
1023                                 /* Instance not running yet (VoD) */
1024                                 seq = tr->seq_init;
1025                             else
1026                             {
1027                                 /* Instance running, add a sink to it */
1028                                 tr->rtp_fd = dup_socket(tr->setup_fd);
1029                                 if (tr->rtp_fd == -1)
1030                                     continue;
1031
1032                                 rtp_add_sink( tr->sout_id, tr->rtp_fd,
1033                                               false, &seq );
1034                             }
1035                         }
1036                         else
1037                         {
1038                             /* Track already playing */
1039                             assert( tr->sout_id != NULL );
1040                             seq = rtp_get_seq( tr->sout_id );
1041                         }
1042                         char *url = RtspAppendTrackPath( tr->id, control );
1043                         infolen += sprintf( info + infolen,
1044                                     "url=%s;seq=%u;rtptime=%u, ",
1045                                     url != NULL ? url : "", seq,
1046                                     rtp_compute_ts( tr->id->clock_rate, ts ) );
1047                         free( url );
1048                     }
1049                 }
1050                 if( infolen > 0 )
1051                 {
1052                     info[infolen - 2] = '\0'; /* remove trailing ", " */
1053                     httpd_MsgAdd( answer, "RTP-Info", "%s", info );
1054                 }
1055                 if (vod)
1056                 {
1057                     vod_play(rtsp->vod_media, psz_session, &start, end);
1058                     npt = start;
1059                 }
1060             }
1061             vlc_mutex_unlock( &rtsp->lock );
1062
1063             if (ses != NULL)
1064             {
1065                 double f_npt = (double) npt / CLOCK_FREQ;
1066                 httpd_MsgAdd( answer, "Range", "npt=%f-", f_npt );
1067             }
1068
1069             if( httpd_MsgGet( query, "Scale" ) != NULL )
1070                 httpd_MsgAdd( answer, "Scale", "1." );
1071             break;
1072         }
1073
1074         case HTTPD_MSG_PAUSE:
1075         {
1076             if (id == NULL && !vod)
1077             {
1078                 answer->i_status = 405;
1079                 httpd_MsgAdd( answer, "Allow",
1080                               "%s, TEARDOWN, PLAY, GET_PARAMETER",
1081                               ( id != NULL ) ? "SETUP" : "DESCRIBE" );
1082                 break;
1083             }
1084
1085             rtsp_session_t *ses;
1086             answer->i_status = 200;
1087             psz_session = httpd_MsgGet( query, "Session" );
1088             vlc_mutex_lock( &rtsp->lock );
1089             ses = RtspClientGet( rtsp, psz_session );
1090             if (ses != NULL)
1091             {
1092                 if (id == NULL)
1093                 {
1094                     assert(vod);
1095                     int64_t npt;
1096                     vod_pause(rtsp->vod_media, psz_session, &npt);
1097                     double f_npt = (double) npt / CLOCK_FREQ;
1098                     httpd_MsgAdd( answer, "Range", "npt=%f-", f_npt );
1099                 }
1100                 else /* "Mute" the selected track */
1101                 {
1102                     bool found = false;
1103                     for (int i = 0; i < ses->trackc; i++)
1104                     {
1105                         rtsp_strack_t *tr = ses->trackv + i;;
1106                         if (tr->id == id)
1107                         {
1108                             if (tr->setup_fd == -1)
1109                                 break;
1110
1111                             found = true;
1112                             if (tr->rtp_fd != -1)
1113                             {
1114                                 rtp_del_sink(tr->sout_id, tr->rtp_fd);
1115                                 tr->rtp_fd = -1;
1116                             }
1117                             break;
1118                         }
1119                     }
1120                     if (!found)
1121                         answer->i_status = 455;
1122                 }
1123                 RtspClientAlive(ses);
1124             }
1125             vlc_mutex_unlock( &rtsp->lock );
1126             break;
1127         }
1128
1129         case HTTPD_MSG_GETPARAMETER:
1130             if( query->i_body > 0 )
1131             {
1132                 answer->i_status = 451;
1133                 break;
1134             }
1135
1136             psz_session = httpd_MsgGet( query, "Session" );
1137             answer->i_status = 200;
1138             vlc_mutex_lock( &rtsp->lock );
1139             rtsp_session_t *ses = RtspClientGet( rtsp, psz_session );
1140             if (ses != NULL)
1141                 RtspClientAlive(ses);
1142             vlc_mutex_unlock( &rtsp->lock );
1143             break;
1144
1145         case HTTPD_MSG_TEARDOWN:
1146         {
1147             rtsp_session_t *ses;
1148
1149             answer->i_status = 200;
1150
1151             psz_session = httpd_MsgGet( query, "Session" );
1152
1153             vlc_mutex_lock( &rtsp->lock );
1154             ses = RtspClientGet( rtsp, psz_session );
1155             if( ses != NULL )
1156             {
1157                 if( id == NULL ) /* Delete the entire session */
1158                 {
1159                     RtspClientDel( rtsp, ses );
1160                     if (vod)
1161                         vod_stop(rtsp->vod_media, psz_session);
1162                     RtspUpdateTimer(rtsp);
1163                 }
1164                 else /* Delete one track from the session */
1165                 {
1166                     for( int i = 0; i < ses->trackc; i++ )
1167                     {
1168                         if( ses->trackv[i].id == id )
1169                         {
1170                             RtspTrackClose( &ses->trackv[i] );
1171                             /* Keep VoD tracks whose instance is still
1172                              * running */
1173                             if (!(vod && ses->trackv[i].sout_id != NULL))
1174                                 REMOVE_ELEM( ses->trackv, ses->trackc, i );
1175                         }
1176                     }
1177                     RtspClientAlive(ses);
1178                 }
1179             }
1180             vlc_mutex_unlock( &rtsp->lock );
1181             break;
1182         }
1183
1184         default:
1185             return VLC_EGENERIC;
1186     }
1187
1188     if( psz_session )
1189     {
1190         if (rtsp->timeout > 0)
1191             httpd_MsgAdd( answer, "Session", "%s;timeout=%d", psz_session,
1192                                                               rtsp->timeout );
1193         else
1194             httpd_MsgAdd( answer, "Session", "%s", psz_session );
1195     }
1196
1197     httpd_MsgAdd( answer, "Content-Length", "%d", answer->i_body );
1198     httpd_MsgAdd( answer, "Cache-Control", "no-cache" );
1199
1200     psz = httpd_MsgGet( query, "Cseq" );
1201     if( psz != NULL )
1202         httpd_MsgAdd( answer, "Cseq", "%s", psz );
1203     psz = httpd_MsgGet( query, "Timestamp" );
1204     if( psz != NULL )
1205         httpd_MsgAdd( answer, "Timestamp", "%s", psz );
1206
1207     return VLC_SUCCESS;
1208 }
1209
1210
1211 /** Aggregate RTSP callback */
1212 static int RtspCallback( httpd_callback_sys_t *p_args,
1213                          httpd_client_t *cl,
1214                          httpd_message_t *answer,
1215                          const httpd_message_t *query )
1216 {
1217     return RtspHandler( (rtsp_stream_t *)p_args, NULL, cl, answer, query );
1218 }
1219
1220
1221 /** Non-aggregate RTSP callback */
1222 static int RtspCallbackId( httpd_callback_sys_t *p_args,
1223                            httpd_client_t *cl,
1224                            httpd_message_t *answer,
1225                            const httpd_message_t *query )
1226 {
1227     rtsp_stream_id_t *id = (rtsp_stream_id_t *)p_args;
1228     return RtspHandler( id->stream, id, cl, answer, query );
1229 }