]> git.sesse.net Git - ffmpeg/blob - libavformat/rtspdec.c
avformat/rtspdec: fix mem leaks in listen mode if init fails
[ffmpeg] / libavformat / rtspdec.c
1 /*
2  * RTSP demuxer
3  * Copyright (c) 2002 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 #include "libavutil/avstring.h"
23 #include "libavutil/intreadwrite.h"
24 #include "libavutil/mathematics.h"
25 #include "libavutil/random_seed.h"
26 #include "libavutil/time.h"
27 #include "avformat.h"
28
29 #include "internal.h"
30 #include "network.h"
31 #include "os_support.h"
32 #include "rtpproto.h"
33 #include "rtsp.h"
34 #include "rdt.h"
35 #include "tls.h"
36 #include "url.h"
37
38 static const struct RTSPStatusMessage {
39     enum RTSPStatusCode code;
40     const char *message;
41 } status_messages[] = {
42     { RTSP_STATUS_OK,             "OK"                               },
43     { RTSP_STATUS_METHOD,         "Method Not Allowed"               },
44     { RTSP_STATUS_BANDWIDTH,      "Not Enough Bandwidth"             },
45     { RTSP_STATUS_SESSION,        "Session Not Found"                },
46     { RTSP_STATUS_STATE,          "Method Not Valid in This State"   },
47     { RTSP_STATUS_AGGREGATE,      "Aggregate operation not allowed"  },
48     { RTSP_STATUS_ONLY_AGGREGATE, "Only aggregate operation allowed" },
49     { RTSP_STATUS_TRANSPORT,      "Unsupported transport"            },
50     { RTSP_STATUS_INTERNAL,       "Internal Server Error"            },
51     { RTSP_STATUS_SERVICE,        "Service Unavailable"              },
52     { RTSP_STATUS_VERSION,        "RTSP Version not supported"       },
53     { 0,                          "NULL"                             }
54 };
55
56 static int rtsp_read_close(AVFormatContext *s)
57 {
58     RTSPState *rt = s->priv_data;
59
60     if (!(rt->rtsp_flags & RTSP_FLAG_LISTEN))
61         ff_rtsp_send_cmd_async(s, "TEARDOWN", rt->control_uri, NULL);
62
63     ff_rtsp_close_streams(s);
64     ff_rtsp_close_connections(s);
65     ff_network_close();
66     rt->real_setup = NULL;
67     av_freep(&rt->real_setup_cache);
68     return 0;
69 }
70
71 static inline int read_line(AVFormatContext *s, char *rbuf, const int rbufsize,
72                             int *rbuflen)
73 {
74     RTSPState *rt = s->priv_data;
75     int idx       = 0;
76     int ret       = 0;
77     *rbuflen      = 0;
78
79     do {
80         ret = ffurl_read_complete(rt->rtsp_hd, rbuf + idx, 1);
81         if (ret <= 0)
82             return ret ? ret : AVERROR_EOF;
83         if (rbuf[idx] == '\r') {
84             /* Ignore */
85         } else if (rbuf[idx] == '\n') {
86             rbuf[idx] = '\0';
87             *rbuflen  = idx;
88             return 0;
89         } else
90             idx++;
91     } while (idx < rbufsize);
92     av_log(s, AV_LOG_ERROR, "Message too long\n");
93     return AVERROR(EIO);
94 }
95
96 static int rtsp_send_reply(AVFormatContext *s, enum RTSPStatusCode code,
97                            const char *extracontent, uint16_t seq)
98 {
99     RTSPState *rt = s->priv_data;
100     char message[4096];
101     int index = 0;
102     while (status_messages[index].code) {
103         if (status_messages[index].code == code) {
104             snprintf(message, sizeof(message), "RTSP/1.0 %d %s\r\n",
105                      code, status_messages[index].message);
106             break;
107         }
108         index++;
109     }
110     if (!status_messages[index].code)
111         return AVERROR(EINVAL);
112     av_strlcatf(message, sizeof(message), "CSeq: %d\r\n", seq);
113     av_strlcatf(message, sizeof(message), "Server: %s\r\n", LIBAVFORMAT_IDENT);
114     if (extracontent)
115         av_strlcat(message, extracontent, sizeof(message));
116     av_strlcat(message, "\r\n", sizeof(message));
117     av_log(s, AV_LOG_TRACE, "Sending response:\n%s", message);
118     ffurl_write(rt->rtsp_hd_out, message, strlen(message));
119
120     return 0;
121 }
122
123 static inline int check_sessionid(AVFormatContext *s,
124                                   RTSPMessageHeader *request)
125 {
126     RTSPState *rt = s->priv_data;
127     unsigned char *session_id = rt->session_id;
128     if (!session_id[0]) {
129         av_log(s, AV_LOG_WARNING, "There is no session-id at the moment\n");
130         return 0;
131     }
132     if (strcmp(session_id, request->session_id)) {
133         av_log(s, AV_LOG_ERROR, "Unexpected session-id %s\n",
134                request->session_id);
135         rtsp_send_reply(s, RTSP_STATUS_SESSION, NULL, request->seq);
136         return AVERROR_STREAM_NOT_FOUND;
137     }
138     return 0;
139 }
140
141 static inline int rtsp_read_request(AVFormatContext *s,
142                                     RTSPMessageHeader *request,
143                                     const char *method)
144 {
145     RTSPState *rt = s->priv_data;
146     char rbuf[1024];
147     int rbuflen, ret;
148     do {
149         ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
150         if (ret)
151             return ret;
152         if (rbuflen > 1) {
153             av_log(s, AV_LOG_TRACE, "Parsing[%d]: %s\n", rbuflen, rbuf);
154             ff_rtsp_parse_line(s, request, rbuf, rt, method);
155         }
156     } while (rbuflen > 0);
157     if (request->seq != rt->seq + 1) {
158         av_log(s, AV_LOG_ERROR, "Unexpected Sequence number %d\n",
159                request->seq);
160         return AVERROR(EINVAL);
161     }
162     if (rt->session_id[0] && strcmp(method, "OPTIONS")) {
163         ret = check_sessionid(s, request);
164         if (ret)
165             return ret;
166     }
167
168     return 0;
169 }
170
171 static int rtsp_read_announce(AVFormatContext *s)
172 {
173     RTSPState *rt             = s->priv_data;
174     RTSPMessageHeader request = { 0 };
175     char sdp[SDP_MAX_SIZE];
176     int  ret;
177
178     ret = rtsp_read_request(s, &request, "ANNOUNCE");
179     if (ret)
180         return ret;
181     rt->seq++;
182     if (strcmp(request.content_type, "application/sdp")) {
183         av_log(s, AV_LOG_ERROR, "Unexpected content type %s\n",
184                request.content_type);
185         rtsp_send_reply(s, RTSP_STATUS_SERVICE, NULL, request.seq);
186         return AVERROR_OPTION_NOT_FOUND;
187     }
188     if (request.content_length && request.content_length < sizeof(sdp) - 1) {
189         /* Read SDP */
190         if (ffurl_read_complete(rt->rtsp_hd, sdp, request.content_length)
191             < request.content_length) {
192             av_log(s, AV_LOG_ERROR,
193                    "Unable to get complete SDP Description in ANNOUNCE\n");
194             rtsp_send_reply(s, RTSP_STATUS_INTERNAL, NULL, request.seq);
195             return AVERROR(EIO);
196         }
197         sdp[request.content_length] = '\0';
198         av_log(s, AV_LOG_VERBOSE, "SDP: %s\n", sdp);
199         ret = ff_sdp_parse(s, sdp);
200         if (ret)
201             return ret;
202         rtsp_send_reply(s, RTSP_STATUS_OK, NULL, request.seq);
203         return 0;
204     }
205     av_log(s, AV_LOG_ERROR,
206            "Content-Length header value exceeds sdp allocated buffer (4KB)\n");
207     rtsp_send_reply(s, RTSP_STATUS_INTERNAL,
208                     "Content-Length exceeds buffer size", request.seq);
209     return AVERROR(EIO);
210 }
211
212 static int rtsp_read_options(AVFormatContext *s)
213 {
214     RTSPState *rt             = s->priv_data;
215     RTSPMessageHeader request = { 0 };
216     int ret                   = 0;
217
218     /* Parsing headers */
219     ret = rtsp_read_request(s, &request, "OPTIONS");
220     if (ret)
221         return ret;
222     rt->seq++;
223     /* Send Reply */
224     rtsp_send_reply(s, RTSP_STATUS_OK,
225                     "Public: ANNOUNCE, PAUSE, SETUP, TEARDOWN, RECORD\r\n",
226                     request.seq);
227     return 0;
228 }
229
230 static int rtsp_read_setup(AVFormatContext *s, char* host, char *controlurl)
231 {
232     RTSPState *rt             = s->priv_data;
233     RTSPMessageHeader request = { 0 };
234     int ret                   = 0;
235     char url[1024];
236     RTSPStream *rtsp_st;
237     char responseheaders[1024];
238     int localport    = -1;
239     int transportidx = 0;
240     int streamid     = 0;
241
242     ret = rtsp_read_request(s, &request, "SETUP");
243     if (ret)
244         return ret;
245     rt->seq++;
246     if (!request.nb_transports) {
247         av_log(s, AV_LOG_ERROR, "No transport defined in SETUP\n");
248         return AVERROR_INVALIDDATA;
249     }
250     for (transportidx = 0; transportidx < request.nb_transports;
251          transportidx++) {
252         if (!request.transports[transportidx].mode_record ||
253             (request.transports[transportidx].lower_transport !=
254              RTSP_LOWER_TRANSPORT_UDP &&
255              request.transports[transportidx].lower_transport !=
256              RTSP_LOWER_TRANSPORT_TCP)) {
257             av_log(s, AV_LOG_ERROR, "mode=record/receive not set or transport"
258                    " protocol not supported (yet)\n");
259             return AVERROR_INVALIDDATA;
260         }
261     }
262     if (request.nb_transports > 1)
263         av_log(s, AV_LOG_WARNING, "More than one transport not supported, "
264                "using first of all\n");
265     for (streamid = 0; streamid < rt->nb_rtsp_streams; streamid++) {
266         if (!strcmp(rt->rtsp_streams[streamid]->control_url,
267                     controlurl))
268             break;
269     }
270     if (streamid == rt->nb_rtsp_streams) {
271         av_log(s, AV_LOG_ERROR, "Unable to find requested track\n");
272         return AVERROR_STREAM_NOT_FOUND;
273     }
274     rtsp_st   = rt->rtsp_streams[streamid];
275     localport = rt->rtp_port_min;
276
277     if (request.transports[0].lower_transport == RTSP_LOWER_TRANSPORT_TCP) {
278         rt->lower_transport = RTSP_LOWER_TRANSPORT_TCP;
279         if ((ret = ff_rtsp_open_transport_ctx(s, rtsp_st))) {
280             rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq);
281             return ret;
282         }
283         rtsp_st->interleaved_min = request.transports[0].interleaved_min;
284         rtsp_st->interleaved_max = request.transports[0].interleaved_max;
285         snprintf(responseheaders, sizeof(responseheaders), "Transport: "
286                  "RTP/AVP/TCP;unicast;mode=receive;interleaved=%d-%d"
287                  "\r\n", request.transports[0].interleaved_min,
288                  request.transports[0].interleaved_max);
289     } else {
290         do {
291             AVDictionary *opts = NULL;
292             av_dict_set_int(&opts, "buffer_size", rt->buffer_size, 0);
293             ff_url_join(url, sizeof(url), "rtp", NULL, host, localport, NULL);
294             av_log(s, AV_LOG_TRACE, "Opening: %s\n", url);
295             ret = ffurl_open_whitelist(&rtsp_st->rtp_handle, url, AVIO_FLAG_READ_WRITE,
296                                        &s->interrupt_callback, &opts,
297                                        s->protocol_whitelist, s->protocol_blacklist, NULL);
298             av_dict_free(&opts);
299             if (ret)
300                 localport += 2;
301         } while (ret || localport > rt->rtp_port_max);
302         if (localport > rt->rtp_port_max) {
303             rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq);
304             return ret;
305         }
306
307         av_log(s, AV_LOG_TRACE, "Listening on: %d\n",
308                 ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle));
309         if ((ret = ff_rtsp_open_transport_ctx(s, rtsp_st))) {
310             rtsp_send_reply(s, RTSP_STATUS_TRANSPORT, NULL, request.seq);
311             return ret;
312         }
313
314         localport = ff_rtp_get_local_rtp_port(rtsp_st->rtp_handle);
315         snprintf(responseheaders, sizeof(responseheaders), "Transport: "
316                  "RTP/AVP/UDP;unicast;mode=receive;source=%s;"
317                  "client_port=%d-%d;server_port=%d-%d\r\n",
318                  host, request.transports[0].client_port_min,
319                  request.transports[0].client_port_max, localport,
320                  localport + 1);
321     }
322
323     /* Establish sessionid if not previously set */
324     /* Put this in a function? */
325     /* RFC 2326: session id must be at least 8 digits */
326     while (strlen(rt->session_id) < 8)
327         av_strlcatf(rt->session_id, 512, "%u", av_get_random_seed());
328
329     av_strlcatf(responseheaders, sizeof(responseheaders), "Session: %s\r\n",
330                 rt->session_id);
331     /* Send Reply */
332     rtsp_send_reply(s, RTSP_STATUS_OK, responseheaders, request.seq);
333
334     rt->state = RTSP_STATE_PAUSED;
335     return 0;
336 }
337
338 static int rtsp_read_record(AVFormatContext *s)
339 {
340     RTSPState *rt             = s->priv_data;
341     RTSPMessageHeader request = { 0 };
342     int ret                   = 0;
343     char responseheaders[1024];
344
345     ret = rtsp_read_request(s, &request, "RECORD");
346     if (ret)
347         return ret;
348     ret = check_sessionid(s, &request);
349     if (ret)
350         return ret;
351     rt->seq++;
352     snprintf(responseheaders, sizeof(responseheaders), "Session: %s\r\n",
353              rt->session_id);
354     rtsp_send_reply(s, RTSP_STATUS_OK, responseheaders, request.seq);
355
356     rt->state = RTSP_STATE_STREAMING;
357     return 0;
358 }
359
360 static inline int parse_command_line(AVFormatContext *s, const char *line,
361                                      int linelen, char *uri, int urisize,
362                                      char *method, int methodsize,
363                                      enum RTSPMethod *methodcode)
364 {
365     RTSPState *rt = s->priv_data;
366     const char *linept, *searchlinept;
367     linept = strchr(line, ' ');
368
369     if (!linept) {
370         av_log(s, AV_LOG_ERROR, "Error parsing method string\n");
371         return AVERROR_INVALIDDATA;
372     }
373
374     if (linept - line > methodsize - 1) {
375         av_log(s, AV_LOG_ERROR, "Method string too long\n");
376         return AVERROR(EIO);
377     }
378     memcpy(method, line, linept - line);
379     method[linept - line] = '\0';
380     linept++;
381     if (!strcmp(method, "ANNOUNCE"))
382         *methodcode = ANNOUNCE;
383     else if (!strcmp(method, "OPTIONS"))
384         *methodcode = OPTIONS;
385     else if (!strcmp(method, "RECORD"))
386         *methodcode = RECORD;
387     else if (!strcmp(method, "SETUP"))
388         *methodcode = SETUP;
389     else if (!strcmp(method, "PAUSE"))
390         *methodcode = PAUSE;
391     else if (!strcmp(method, "TEARDOWN"))
392         *methodcode = TEARDOWN;
393     else
394         *methodcode = UNKNOWN;
395     /* Check method with the state  */
396     if (rt->state == RTSP_STATE_IDLE) {
397         if ((*methodcode != ANNOUNCE) && (*methodcode != OPTIONS)) {
398             av_log(s, AV_LOG_ERROR, "Unexpected command in Idle State %s\n",
399                    line);
400             return AVERROR_PROTOCOL_NOT_FOUND;
401         }
402     } else if (rt->state == RTSP_STATE_PAUSED) {
403         if ((*methodcode != OPTIONS) && (*methodcode != RECORD)
404             && (*methodcode != SETUP)) {
405             av_log(s, AV_LOG_ERROR, "Unexpected command in Paused State %s\n",
406                    line);
407             return AVERROR_PROTOCOL_NOT_FOUND;
408         }
409     } else if (rt->state == RTSP_STATE_STREAMING) {
410         if ((*methodcode != PAUSE) && (*methodcode != OPTIONS)
411             && (*methodcode != TEARDOWN)) {
412             av_log(s, AV_LOG_ERROR, "Unexpected command in Streaming State"
413                    " %s\n", line);
414             return AVERROR_PROTOCOL_NOT_FOUND;
415         }
416     } else {
417         av_log(s, AV_LOG_ERROR, "Unexpected State [%d]\n", rt->state);
418         return AVERROR_BUG;
419     }
420
421     searchlinept = strchr(linept, ' ');
422     if (!searchlinept) {
423         av_log(s, AV_LOG_ERROR, "Error parsing message URI\n");
424         return AVERROR_INVALIDDATA;
425     }
426     if (searchlinept - linept > urisize - 1) {
427         av_log(s, AV_LOG_ERROR, "uri string length exceeded buffer size\n");
428         return AVERROR(EIO);
429     }
430     memcpy(uri, linept, searchlinept - linept);
431     uri[searchlinept - linept] = '\0';
432     if (strcmp(rt->control_uri, uri)) {
433         char host[128], path[512], auth[128];
434         int port;
435         char ctl_host[128], ctl_path[512], ctl_auth[128];
436         int ctl_port;
437         av_url_split(NULL, 0, auth, sizeof(auth), host, sizeof(host), &port,
438                      path, sizeof(path), uri);
439         av_url_split(NULL, 0, ctl_auth, sizeof(ctl_auth), ctl_host,
440                      sizeof(ctl_host), &ctl_port, ctl_path, sizeof(ctl_path),
441                      rt->control_uri);
442         if (strcmp(host, ctl_host))
443             av_log(s, AV_LOG_INFO, "Host %s differs from expected %s\n",
444                    host, ctl_host);
445         if (strcmp(path, ctl_path) && *methodcode != SETUP)
446             av_log(s, AV_LOG_WARNING, "WARNING: Path %s differs from expected"
447                    " %s\n", path, ctl_path);
448         if (*methodcode == ANNOUNCE) {
449             av_log(s, AV_LOG_INFO,
450                    "Updating control URI to %s\n", uri);
451             av_strlcpy(rt->control_uri, uri, sizeof(rt->control_uri));
452         }
453     }
454
455     linept = searchlinept + 1;
456     if (!av_strstart(linept, "RTSP/1.0", NULL)) {
457         av_log(s, AV_LOG_ERROR, "Error parsing protocol or version\n");
458         return AVERROR_PROTOCOL_NOT_FOUND;
459     }
460     return 0;
461 }
462
463 int ff_rtsp_parse_streaming_commands(AVFormatContext *s)
464 {
465     RTSPState *rt = s->priv_data;
466     unsigned char rbuf[4096];
467     unsigned char method[10];
468     char uri[500];
469     int ret;
470     int rbuflen               = 0;
471     RTSPMessageHeader request = { 0 };
472     enum RTSPMethod methodcode;
473
474     ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
475     if (ret < 0)
476         return ret;
477     ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,
478                              sizeof(method), &methodcode);
479     if (ret) {
480         av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");
481         return ret;
482     }
483
484     ret = rtsp_read_request(s, &request, method);
485     if (ret)
486         return ret;
487     rt->seq++;
488     if (methodcode == PAUSE) {
489         rt->state = RTSP_STATE_PAUSED;
490         ret       = rtsp_send_reply(s, RTSP_STATUS_OK, NULL , request.seq);
491         // TODO: Missing date header in response
492     } else if (methodcode == OPTIONS) {
493         ret = rtsp_send_reply(s, RTSP_STATUS_OK,
494                               "Public: ANNOUNCE, PAUSE, SETUP, TEARDOWN, "
495                               "RECORD\r\n", request.seq);
496     } else if (methodcode == TEARDOWN) {
497         rt->state = RTSP_STATE_IDLE;
498         ret       = rtsp_send_reply(s, RTSP_STATUS_OK, NULL , request.seq);
499     }
500     return ret;
501 }
502
503 static int rtsp_read_play(AVFormatContext *s)
504 {
505     RTSPState *rt = s->priv_data;
506     RTSPMessageHeader reply1, *reply = &reply1;
507     int i;
508     char cmd[1024];
509
510     av_log(s, AV_LOG_DEBUG, "hello state=%d\n", rt->state);
511     rt->nb_byes = 0;
512
513     if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP) {
514         for (i = 0; i < rt->nb_rtsp_streams; i++) {
515             RTSPStream *rtsp_st = rt->rtsp_streams[i];
516             /* Try to initialize the connection state in a
517              * potential NAT router by sending dummy packets.
518              * RTP/RTCP dummy packets are used for RDT, too.
519              */
520             if (rtsp_st->rtp_handle &&
521                 !(rt->server_type == RTSP_SERVER_WMS && i > 1))
522                 ff_rtp_send_punch_packets(rtsp_st->rtp_handle);
523         }
524     }
525     if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
526         if (rt->transport == RTSP_TRANSPORT_RTP) {
527             for (i = 0; i < rt->nb_rtsp_streams; i++) {
528                 RTSPStream *rtsp_st = rt->rtsp_streams[i];
529                 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
530                 if (!rtpctx)
531                     continue;
532                 ff_rtp_reset_packet_queue(rtpctx);
533                 rtpctx->last_rtcp_ntp_time  = AV_NOPTS_VALUE;
534                 rtpctx->first_rtcp_ntp_time = AV_NOPTS_VALUE;
535                 rtpctx->base_timestamp      = 0;
536                 rtpctx->timestamp           = 0;
537                 rtpctx->unwrapped_timestamp = 0;
538                 rtpctx->rtcp_ts_offset      = 0;
539             }
540         }
541         if (rt->state == RTSP_STATE_PAUSED) {
542             cmd[0] = 0;
543         } else {
544             snprintf(cmd, sizeof(cmd),
545                      "Range: npt=%"PRId64".%03"PRId64"-\r\n",
546                      rt->seek_timestamp / AV_TIME_BASE,
547                      rt->seek_timestamp / (AV_TIME_BASE / 1000) % 1000);
548         }
549         ff_rtsp_send_cmd(s, "PLAY", rt->control_uri, cmd, reply, NULL);
550         if (reply->status_code != RTSP_STATUS_OK) {
551             return ff_rtsp_averror(reply->status_code, -1);
552         }
553         if (rt->transport == RTSP_TRANSPORT_RTP &&
554             reply->range_start != AV_NOPTS_VALUE) {
555             for (i = 0; i < rt->nb_rtsp_streams; i++) {
556                 RTSPStream *rtsp_st = rt->rtsp_streams[i];
557                 RTPDemuxContext *rtpctx = rtsp_st->transport_priv;
558                 AVStream *st = NULL;
559                 if (!rtpctx || rtsp_st->stream_index < 0)
560                     continue;
561
562                 st = s->streams[rtsp_st->stream_index];
563                 rtpctx->range_start_offset =
564                     av_rescale_q(reply->range_start, AV_TIME_BASE_Q,
565                                  st->time_base);
566             }
567         }
568     }
569     rt->state = RTSP_STATE_STREAMING;
570     return 0;
571 }
572
573 /* pause the stream */
574 static int rtsp_read_pause(AVFormatContext *s)
575 {
576     RTSPState *rt = s->priv_data;
577     RTSPMessageHeader reply1, *reply = &reply1;
578
579     if (rt->state != RTSP_STATE_STREAMING)
580         return 0;
581     else if (!(rt->server_type == RTSP_SERVER_REAL && rt->need_subscription)) {
582         ff_rtsp_send_cmd(s, "PAUSE", rt->control_uri, NULL, reply, NULL);
583         if (reply->status_code != RTSP_STATUS_OK) {
584             return ff_rtsp_averror(reply->status_code, -1);
585         }
586     }
587     rt->state = RTSP_STATE_PAUSED;
588     return 0;
589 }
590
591 int ff_rtsp_setup_input_streams(AVFormatContext *s, RTSPMessageHeader *reply)
592 {
593     RTSPState *rt = s->priv_data;
594     char cmd[1024];
595     unsigned char *content = NULL;
596     int ret;
597
598     /* describe the stream */
599     snprintf(cmd, sizeof(cmd),
600              "Accept: application/sdp\r\n");
601     if (rt->server_type == RTSP_SERVER_REAL) {
602         /**
603          * The Require: attribute is needed for proper streaming from
604          * Realmedia servers.
605          */
606         av_strlcat(cmd,
607                    "Require: com.real.retain-entity-for-setup\r\n",
608                    sizeof(cmd));
609     }
610     ff_rtsp_send_cmd(s, "DESCRIBE", rt->control_uri, cmd, reply, &content);
611     if (reply->status_code != RTSP_STATUS_OK) {
612         av_freep(&content);
613         return ff_rtsp_averror(reply->status_code, AVERROR_INVALIDDATA);
614     }
615     if (!content)
616         return AVERROR_INVALIDDATA;
617
618     av_log(s, AV_LOG_VERBOSE, "SDP:\n%s\n", content);
619     /* now we got the SDP description, we parse it */
620     ret = ff_sdp_parse(s, (const char *)content);
621     av_freep(&content);
622     if (ret < 0)
623         return ret;
624
625     return 0;
626 }
627
628 static int rtsp_listen(AVFormatContext *s)
629 {
630     RTSPState *rt = s->priv_data;
631     char proto[128], host[128], path[512], auth[128];
632     char uri[500];
633     int port;
634     int default_port = RTSP_DEFAULT_PORT;
635     char tcpname[500];
636     const char *lower_proto = "tcp";
637     unsigned char rbuf[4096];
638     unsigned char method[10];
639     int rbuflen = 0;
640     int ret;
641     enum RTSPMethod methodcode;
642
643     if (!ff_network_init())
644         return AVERROR(EIO);
645
646     /* extract hostname and port */
647     av_url_split(proto, sizeof(proto), auth, sizeof(auth), host, sizeof(host),
648                  &port, path, sizeof(path), s->url);
649
650     /* ff_url_join. No authorization by now (NULL) */
651     ff_url_join(rt->control_uri, sizeof(rt->control_uri), proto, NULL, host,
652                 port, "%s", path);
653
654     if (!strcmp(proto, "rtsps")) {
655         lower_proto  = "tls";
656         default_port = RTSPS_DEFAULT_PORT;
657     }
658
659     if (port < 0)
660         port = default_port;
661
662     /* Create TCP connection */
663     ff_url_join(tcpname, sizeof(tcpname), lower_proto, NULL, host, port,
664                 "?listen&listen_timeout=%d", rt->initial_timeout * 1000);
665
666     if (ret = ffurl_open_whitelist(&rt->rtsp_hd, tcpname, AVIO_FLAG_READ_WRITE,
667                                    &s->interrupt_callback, NULL,
668                                    s->protocol_whitelist, s->protocol_blacklist, NULL)) {
669         av_log(s, AV_LOG_ERROR, "Unable to open RTSP for listening\n");
670         goto fail;
671     }
672     rt->state       = RTSP_STATE_IDLE;
673     rt->rtsp_hd_out = rt->rtsp_hd;
674     for (;;) { /* Wait for incoming RTSP messages */
675         ret = read_line(s, rbuf, sizeof(rbuf), &rbuflen);
676         if (ret < 0)
677             goto fail;
678         ret = parse_command_line(s, rbuf, rbuflen, uri, sizeof(uri), method,
679                                  sizeof(method), &methodcode);
680         if (ret) {
681             av_log(s, AV_LOG_ERROR, "RTSP: Unexpected Command\n");
682             goto fail;
683         }
684
685         if (methodcode == ANNOUNCE) {
686             ret       = rtsp_read_announce(s);
687             rt->state = RTSP_STATE_PAUSED;
688         } else if (methodcode == OPTIONS) {
689             ret = rtsp_read_options(s);
690         } else if (methodcode == RECORD) {
691             ret = rtsp_read_record(s);
692             if (!ret)
693                 return 0; // We are ready for streaming
694         } else if (methodcode == SETUP)
695             ret = rtsp_read_setup(s, host, uri);
696         if (ret) {
697             ret = AVERROR_INVALIDDATA;
698             goto fail;
699         }
700     }
701 fail:
702     ff_rtsp_close_streams(s);
703     ff_rtsp_close_connections(s);
704     ff_network_close();
705     return ret;
706 }
707
708 static int rtsp_probe(const AVProbeData *p)
709 {
710     if (
711 #if CONFIG_TLS_PROTOCOL
712         av_strstart(p->filename, "rtsps:", NULL) ||
713 #endif
714         av_strstart(p->filename, "rtsp:", NULL))
715         return AVPROBE_SCORE_MAX;
716     return 0;
717 }
718
719 static int rtsp_read_header(AVFormatContext *s)
720 {
721     RTSPState *rt = s->priv_data;
722     int ret;
723
724     if (rt->initial_timeout > 0)
725         rt->rtsp_flags |= RTSP_FLAG_LISTEN;
726
727     if (rt->rtsp_flags & RTSP_FLAG_LISTEN) {
728         ret = rtsp_listen(s);
729         if (ret)
730             return ret;
731     } else {
732         ret = ff_rtsp_connect(s);
733         if (ret)
734             return ret;
735
736         rt->real_setup_cache = !s->nb_streams ? NULL :
737             av_mallocz_array(s->nb_streams, 2 * sizeof(*rt->real_setup_cache));
738         if (!rt->real_setup_cache && s->nb_streams)
739             return AVERROR(ENOMEM);
740         rt->real_setup = rt->real_setup_cache + s->nb_streams;
741
742         if (rt->initial_pause) {
743             /* do not start immediately */
744         } else {
745             if ((ret = rtsp_read_play(s)) < 0) {
746                 ff_rtsp_close_streams(s);
747                 ff_rtsp_close_connections(s);
748                 return ret;
749             }
750         }
751     }
752
753     return 0;
754 }
755
756 int ff_rtsp_tcp_read_packet(AVFormatContext *s, RTSPStream **prtsp_st,
757                             uint8_t *buf, int buf_size)
758 {
759     RTSPState *rt = s->priv_data;
760     int id, len, i, ret;
761     RTSPStream *rtsp_st;
762
763     av_log(s, AV_LOG_TRACE, "tcp_read_packet:\n");
764 redo:
765     for (;;) {
766         RTSPMessageHeader reply;
767
768         ret = ff_rtsp_read_reply(s, &reply, NULL, 1, NULL);
769         if (ret < 0)
770             return ret;
771         if (ret == 1) /* received '$' */
772             break;
773         /* XXX: parse message */
774         if (rt->state != RTSP_STATE_STREAMING)
775             return 0;
776     }
777     ret = ffurl_read_complete(rt->rtsp_hd, buf, 3);
778     if (ret != 3)
779         return AVERROR(EIO);
780     id  = buf[0];
781     len = AV_RB16(buf + 1);
782     av_log(s, AV_LOG_TRACE, "id=%d len=%d\n", id, len);
783     if (len > buf_size || len < 8)
784         goto redo;
785     /* get the data */
786     ret = ffurl_read_complete(rt->rtsp_hd, buf, len);
787     if (ret != len)
788         return AVERROR(EIO);
789     if (rt->transport == RTSP_TRANSPORT_RDT &&
790         (ret = ff_rdt_parse_header(buf, len, &id, NULL, NULL, NULL, NULL)) < 0)
791         return ret;
792
793     /* find the matching stream */
794     for (i = 0; i < rt->nb_rtsp_streams; i++) {
795         rtsp_st = rt->rtsp_streams[i];
796         if (id >= rtsp_st->interleaved_min &&
797             id <= rtsp_st->interleaved_max)
798             goto found;
799     }
800     goto redo;
801 found:
802     *prtsp_st = rtsp_st;
803     return len;
804 }
805
806 static int resetup_tcp(AVFormatContext *s)
807 {
808     RTSPState *rt = s->priv_data;
809     char host[1024];
810     int port;
811
812     av_url_split(NULL, 0, NULL, 0, host, sizeof(host), &port, NULL, 0,
813                  s->url);
814     ff_rtsp_undo_setup(s, 0);
815     return ff_rtsp_make_setup_request(s, host, port, RTSP_LOWER_TRANSPORT_TCP,
816                                       rt->real_challenge);
817 }
818
819 static int rtsp_read_packet(AVFormatContext *s, AVPacket *pkt)
820 {
821     RTSPState *rt = s->priv_data;
822     int ret;
823     RTSPMessageHeader reply1, *reply = &reply1;
824     char cmd[1024];
825
826 retry:
827     if (rt->server_type == RTSP_SERVER_REAL) {
828         int i;
829
830         for (i = 0; i < s->nb_streams; i++)
831             rt->real_setup[i] = s->streams[i]->discard;
832
833         if (!rt->need_subscription) {
834             if (memcmp (rt->real_setup, rt->real_setup_cache,
835                         sizeof(enum AVDiscard) * s->nb_streams)) {
836                 snprintf(cmd, sizeof(cmd),
837                          "Unsubscribe: %s\r\n",
838                          rt->last_subscription);
839                 ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
840                                  cmd, reply, NULL);
841                 if (reply->status_code != RTSP_STATUS_OK)
842                     return ff_rtsp_averror(reply->status_code, AVERROR_INVALIDDATA);
843                 rt->need_subscription = 1;
844             }
845         }
846
847         if (rt->need_subscription) {
848             int r, rule_nr, first = 1;
849
850             memcpy(rt->real_setup_cache, rt->real_setup,
851                    sizeof(enum AVDiscard) * s->nb_streams);
852             rt->last_subscription[0] = 0;
853
854             snprintf(cmd, sizeof(cmd),
855                      "Subscribe: ");
856             for (i = 0; i < rt->nb_rtsp_streams; i++) {
857                 rule_nr = 0;
858                 for (r = 0; r < s->nb_streams; r++) {
859                     if (s->streams[r]->id == i) {
860                         if (s->streams[r]->discard != AVDISCARD_ALL) {
861                             if (!first)
862                                 av_strlcat(rt->last_subscription, ",",
863                                            sizeof(rt->last_subscription));
864                             ff_rdt_subscribe_rule(
865                                 rt->last_subscription,
866                                 sizeof(rt->last_subscription), i, rule_nr);
867                             first = 0;
868                         }
869                         rule_nr++;
870                     }
871                 }
872             }
873             av_strlcatf(cmd, sizeof(cmd), "%s\r\n", rt->last_subscription);
874             ff_rtsp_send_cmd(s, "SET_PARAMETER", rt->control_uri,
875                              cmd, reply, NULL);
876             if (reply->status_code != RTSP_STATUS_OK)
877                 return ff_rtsp_averror(reply->status_code, AVERROR_INVALIDDATA);
878             rt->need_subscription = 0;
879
880             if (rt->state == RTSP_STATE_STREAMING)
881                 rtsp_read_play (s);
882         }
883     }
884
885     ret = ff_rtsp_fetch_packet(s, pkt);
886     if (ret < 0) {
887         if (ret == AVERROR(ETIMEDOUT) && !rt->packets) {
888             if (rt->lower_transport == RTSP_LOWER_TRANSPORT_UDP &&
889                 rt->lower_transport_mask & (1 << RTSP_LOWER_TRANSPORT_TCP)) {
890                 RTSPMessageHeader reply1, *reply = &reply1;
891                 av_log(s, AV_LOG_WARNING, "UDP timeout, retrying with TCP\n");
892                 if (rtsp_read_pause(s) != 0)
893                     return -1;
894                 // TEARDOWN is required on Real-RTSP, but might make
895                 // other servers close the connection.
896                 if (rt->server_type == RTSP_SERVER_REAL)
897                     ff_rtsp_send_cmd(s, "TEARDOWN", rt->control_uri, NULL,
898                                      reply, NULL);
899                 rt->session_id[0] = '\0';
900                 if (resetup_tcp(s) == 0) {
901                     rt->state = RTSP_STATE_IDLE;
902                     rt->need_subscription = 1;
903                     if (rtsp_read_play(s) != 0)
904                         return -1;
905                     goto retry;
906                 }
907             }
908         }
909         return ret;
910     }
911     rt->packets++;
912
913     if (!(rt->rtsp_flags & RTSP_FLAG_LISTEN)) {
914         /* send dummy request to keep TCP connection alive */
915         if ((av_gettime_relative() - rt->last_cmd_time) / 1000000 >= rt->timeout / 2 ||
916             rt->auth_state.stale) {
917             if (rt->server_type == RTSP_SERVER_WMS ||
918                 (rt->server_type != RTSP_SERVER_REAL &&
919                  rt->get_parameter_supported)) {
920                 ff_rtsp_send_cmd_async(s, "GET_PARAMETER", rt->control_uri, NULL);
921             } else {
922                 ff_rtsp_send_cmd_async(s, "OPTIONS", rt->control_uri, NULL);
923             }
924             /* The stale flag should be reset when creating the auth response in
925              * ff_rtsp_send_cmd_async, but reset it here just in case we never
926              * called the auth code (if we didn't have any credentials set). */
927             rt->auth_state.stale = 0;
928         }
929     }
930
931     return 0;
932 }
933
934 static int rtsp_read_seek(AVFormatContext *s, int stream_index,
935                           int64_t timestamp, int flags)
936 {
937     RTSPState *rt = s->priv_data;
938     int ret;
939
940     rt->seek_timestamp = av_rescale_q(timestamp,
941                                       s->streams[stream_index]->time_base,
942                                       AV_TIME_BASE_Q);
943     switch(rt->state) {
944     default:
945     case RTSP_STATE_IDLE:
946         break;
947     case RTSP_STATE_STREAMING:
948         if ((ret = rtsp_read_pause(s)) != 0)
949             return ret;
950         rt->state = RTSP_STATE_SEEKING;
951         if ((ret = rtsp_read_play(s)) != 0)
952             return ret;
953         break;
954     case RTSP_STATE_PAUSED:
955         rt->state = RTSP_STATE_IDLE;
956         break;
957     }
958     return 0;
959 }
960
961 static const AVClass rtsp_demuxer_class = {
962     .class_name     = "RTSP demuxer",
963     .item_name      = av_default_item_name,
964     .option         = ff_rtsp_options,
965     .version        = LIBAVUTIL_VERSION_INT,
966 };
967
968 AVInputFormat ff_rtsp_demuxer = {
969     .name           = "rtsp",
970     .long_name      = NULL_IF_CONFIG_SMALL("RTSP input"),
971     .priv_data_size = sizeof(RTSPState),
972     .read_probe     = rtsp_probe,
973     .read_header    = rtsp_read_header,
974     .read_packet    = rtsp_read_packet,
975     .read_close     = rtsp_read_close,
976     .read_seek      = rtsp_read_seek,
977     .flags          = AVFMT_NOFILE,
978     .read_play      = rtsp_read_play,
979     .read_pause     = rtsp_read_pause,
980     .priv_class     = &rtsp_demuxer_class,
981 };