1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2014, Daniel Stenberg, <daniel@haxx.se>, et al.
10 * This software is licensed as described in the file COPYING, which
11 * you should have received as part of this distribution. The terms
12 * are also available at http://curl.haxx.se/docs/copyright.html.
14 * You may opt to use, copy, modify, merge, publish, distribute and/or sell
15 * copies of the Software, and permit persons to whom the Software is
16 * furnished to do so, under the terms of the COPYING file.
18 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19 * KIND, either express or implied.
21 ***************************************************************************/
23 #include "curl_setup.h"
25 #ifndef CURL_DISABLE_RTSP
28 #include <curl/curl.h>
37 #include "curl_memory.h"
41 #define _MPRINTF_REPLACE /* use our functions only */
42 #include <curl/mprintf.h>
44 /* The last #include file should be: */
49 * -incoming server requests
50 * -server CSeq counter
51 * -digest authentication
57 #define RTP_PKT_CHANNEL(p) ((int)((unsigned char)((p)[1])))
59 #define RTP_PKT_LENGTH(p) ((((int)((unsigned char)((p)[2]))) << 8) | \
60 ((int)((unsigned char)((p)[3]))))
62 /* protocol-specific functions set up to be called by the main engine */
63 static CURLcode rtsp_do(struct connectdata *conn, bool *done);
64 static CURLcode rtsp_done(struct connectdata *conn, CURLcode, bool premature);
65 static CURLcode rtsp_connect(struct connectdata *conn, bool *done);
66 static CURLcode rtsp_disconnect(struct connectdata *conn, bool dead);
68 static int rtsp_getsock_do(struct connectdata *conn,
73 * Parse and write out any available RTP data.
75 * nread: amount of data left after k->str. will be modified if RTP
76 * data is parsed and k->str is moved up
77 * readmore: whether or not the RTP parser needs more data right away
79 static CURLcode rtsp_rtp_readwrite(struct SessionHandle *data,
80 struct connectdata *conn,
84 static CURLcode rtsp_setup_connection(struct connectdata *conn);
87 /* this returns the socket to wait for in the DO and DOING state for the multi
88 interface and then we're always _sending_ a request and thus we wait for
89 the single socket to become writable only */
90 static int rtsp_getsock_do(struct connectdata *conn,
95 (void)numsocks; /* unused, we trust it to be at least 1 */
96 socks[0] = conn->sock[FIRSTSOCKET];
97 return GETSOCK_WRITESOCK(0);
101 CURLcode rtp_client_write(struct connectdata *conn, char *ptr, size_t len);
105 * RTSP handler interface.
107 const struct Curl_handler Curl_handler_rtsp = {
109 rtsp_setup_connection, /* setup_connection */
111 rtsp_done, /* done */
112 ZERO_NULL, /* do_more */
113 rtsp_connect, /* connect_it */
114 ZERO_NULL, /* connecting */
115 ZERO_NULL, /* doing */
116 ZERO_NULL, /* proto_getsock */
117 rtsp_getsock_do, /* doing_getsock */
118 ZERO_NULL, /* domore_getsock */
119 ZERO_NULL, /* perform_getsock */
120 rtsp_disconnect, /* disconnect */
121 rtsp_rtp_readwrite, /* readwrite */
122 PORT_RTSP, /* defport */
123 CURLPROTO_RTSP, /* protocol */
124 PROTOPT_NONE /* flags */
128 static CURLcode rtsp_setup_connection(struct connectdata *conn)
132 conn->data->req.protop = rtsp = calloc(1, sizeof(struct RTSP));
134 return CURLE_OUT_OF_MEMORY;
141 * The server may send us RTP data at any point, and RTSPREQ_RECEIVE does not
142 * want to block the application forever while receiving a stream. Therefore,
143 * we cannot assume that an RTSP socket is dead just because it is readable.
145 * Instead, if it is readable, run Curl_getconnectinfo() to peek at the socket
146 * and distinguish between closed and data.
148 bool Curl_rtsp_connisdead(struct connectdata *check)
153 sval = Curl_socket_ready(check->sock[FIRSTSOCKET], CURL_SOCKET_BAD, 0);
158 else if(sval & CURL_CSELECT_ERR) {
159 /* socket is in an error state */
162 else if((sval & CURL_CSELECT_IN) && check->data) {
163 /* readable with no error. could be closed or could be alive but we can
164 only check if we have a proper SessionHandle for the connection */
165 curl_socket_t connectinfo = Curl_getconnectinfo(check->data, &check);
166 if(connectinfo != CURL_SOCKET_BAD)
173 static CURLcode rtsp_connect(struct connectdata *conn, bool *done)
176 struct SessionHandle *data = conn->data;
178 httpStatus = Curl_http_connect(conn, done);
180 /* Initialize the CSeq if not already done */
181 if(data->state.rtsp_next_client_CSeq == 0)
182 data->state.rtsp_next_client_CSeq = 1;
183 if(data->state.rtsp_next_server_CSeq == 0)
184 data->state.rtsp_next_server_CSeq = 1;
186 conn->proto.rtspc.rtp_channel = -1;
191 static CURLcode rtsp_disconnect(struct connectdata *conn, bool dead)
194 Curl_safefree(conn->proto.rtspc.rtp_buf);
199 static CURLcode rtsp_done(struct connectdata *conn,
200 CURLcode status, bool premature)
202 struct SessionHandle *data = conn->data;
203 struct RTSP *rtsp = data->req.protop;
208 /* Bypass HTTP empty-reply checks on receive */
209 if(data->set.rtspreq == RTSPREQ_RECEIVE)
212 httpStatus = Curl_http_done(conn, status, premature);
215 /* Check the sequence numbers */
216 CSeq_sent = rtsp->CSeq_sent;
217 CSeq_recv = rtsp->CSeq_recv;
218 if((data->set.rtspreq != RTSPREQ_RECEIVE) && (CSeq_sent != CSeq_recv)) {
220 "The CSeq of this request %ld did not match the response %ld",
221 CSeq_sent, CSeq_recv);
222 return CURLE_RTSP_CSEQ_ERROR;
224 else if(data->set.rtspreq == RTSPREQ_RECEIVE &&
225 (conn->proto.rtspc.rtp_channel == -1)) {
226 infof(data, "Got an RTP Receive with a CSeq of %ld\n", CSeq_recv);
227 /* TODO CPC: Server -> Client logic here */
234 static CURLcode rtsp_do(struct connectdata *conn, bool *done)
236 struct SessionHandle *data = conn->data;
237 CURLcode result=CURLE_OK;
238 Curl_RtspReq rtspreq = data->set.rtspreq;
239 struct RTSP *rtsp = data->req.protop;
241 Curl_send_buffer *req_buffer;
242 curl_off_t postsize = 0; /* for ANNOUNCE and SET_PARAMETER */
243 curl_off_t putsize = 0; /* for ANNOUNCE and SET_PARAMETER */
245 const char *p_request = NULL;
246 const char *p_session_id = NULL;
247 const char *p_accept = NULL;
248 const char *p_accept_encoding = NULL;
249 const char *p_range = NULL;
250 const char *p_referrer = NULL;
251 const char *p_stream_uri = NULL;
252 const char *p_transport = NULL;
253 const char *p_uagent = NULL;
257 http = &(rtsp->http_wrapper);
258 /* Assert that no one has changed the RTSP struct in an evil way */
259 DEBUGASSERT((void *)http == (void *)rtsp);
261 rtsp->CSeq_sent = data->state.rtsp_next_client_CSeq;
264 /* Setup the 'p_request' pointer to the proper p_request string
265 * Since all RTSP requests are included here, there is no need to
266 * support custom requests like HTTP.
268 DEBUGASSERT((rtspreq > RTSPREQ_NONE && rtspreq < RTSPREQ_LAST));
269 data->set.opt_no_body = TRUE; /* most requests don't contain a body */
272 failf(data, "Got invalid RTSP request: RTSPREQ_NONE");
273 return CURLE_BAD_FUNCTION_ARGUMENT;
274 case RTSPREQ_OPTIONS:
275 p_request = "OPTIONS";
277 case RTSPREQ_DESCRIBE:
278 p_request = "DESCRIBE";
279 data->set.opt_no_body = FALSE;
281 case RTSPREQ_ANNOUNCE:
282 p_request = "ANNOUNCE";
293 case RTSPREQ_TEARDOWN:
294 p_request = "TEARDOWN";
296 case RTSPREQ_GET_PARAMETER:
297 /* GET_PARAMETER's no_body status is determined later */
298 p_request = "GET_PARAMETER";
299 data->set.opt_no_body = FALSE;
301 case RTSPREQ_SET_PARAMETER:
302 p_request = "SET_PARAMETER";
305 p_request = "RECORD";
307 case RTSPREQ_RECEIVE:
309 /* Treat interleaved RTP as body*/
310 data->set.opt_no_body = FALSE;
313 failf(data, "Got invalid RTSP request: RTSPREQ_LAST");
314 return CURLE_BAD_FUNCTION_ARGUMENT;
317 if(rtspreq == RTSPREQ_RECEIVE) {
318 Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
319 &http->readbytecount, -1, NULL);
324 p_session_id = data->set.str[STRING_RTSP_SESSION_ID];
326 (rtspreq & ~(RTSPREQ_OPTIONS | RTSPREQ_DESCRIBE | RTSPREQ_SETUP))) {
327 failf(data, "Refusing to issue an RTSP request [%s] without a session ID.",
328 p_request ? p_request : "");
329 return CURLE_BAD_FUNCTION_ARGUMENT;
335 /* Stream URI. Default to server '*' if not specified */
336 if(data->set.str[STRING_RTSP_STREAM_URI]) {
337 p_stream_uri = data->set.str[STRING_RTSP_STREAM_URI];
343 /* Transport Header for SETUP requests */
344 p_transport = Curl_checkheaders(conn, "Transport:");
345 if(rtspreq == RTSPREQ_SETUP && !p_transport) {
346 /* New Transport: setting? */
347 if(data->set.str[STRING_RTSP_TRANSPORT]) {
348 Curl_safefree(conn->allocptr.rtsp_transport);
350 conn->allocptr.rtsp_transport =
351 aprintf("Transport: %s\r\n",
352 data->set.str[STRING_RTSP_TRANSPORT]);
353 if(!conn->allocptr.rtsp_transport)
354 return CURLE_OUT_OF_MEMORY;
358 "Refusing to issue an RTSP SETUP without a Transport: header.");
359 return CURLE_BAD_FUNCTION_ARGUMENT;
362 p_transport = conn->allocptr.rtsp_transport;
365 /* Accept Headers for DESCRIBE requests */
366 if(rtspreq == RTSPREQ_DESCRIBE) {
368 p_accept = Curl_checkheaders(conn, "Accept:")?
369 NULL:"Accept: application/sdp\r\n";
371 /* Accept-Encoding header */
372 if(!Curl_checkheaders(conn, "Accept-Encoding:") &&
373 data->set.str[STRING_ENCODING]) {
374 Curl_safefree(conn->allocptr.accept_encoding);
375 conn->allocptr.accept_encoding =
376 aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]);
378 if(!conn->allocptr.accept_encoding)
379 return CURLE_OUT_OF_MEMORY;
381 p_accept_encoding = conn->allocptr.accept_encoding;
385 /* The User-Agent string might have been allocated in url.c already, because
386 it might have been used in the proxy connect, but if we have got a header
387 with the user-agent string specified, we erase the previously made string
389 if(Curl_checkheaders(conn, "User-Agent:") && conn->allocptr.uagent) {
390 Curl_safefree(conn->allocptr.uagent);
391 conn->allocptr.uagent = NULL;
393 else if(!Curl_checkheaders(conn, "User-Agent:") &&
394 data->set.str[STRING_USERAGENT]) {
395 p_uagent = conn->allocptr.uagent;
399 Curl_safefree(conn->allocptr.ref);
400 if(data->change.referer && !Curl_checkheaders(conn, "Referer:"))
401 conn->allocptr.ref = aprintf("Referer: %s\r\n", data->change.referer);
403 conn->allocptr.ref = NULL;
405 p_referrer = conn->allocptr.ref;
409 * Only applies to PLAY, PAUSE, RECORD
411 * Go ahead and use the Range stuff supplied for HTTP
413 if(data->state.use_range &&
414 (rtspreq & (RTSPREQ_PLAY | RTSPREQ_PAUSE | RTSPREQ_RECORD))) {
416 /* Check to see if there is a range set in the custom headers */
417 if(!Curl_checkheaders(conn, "Range:") && data->state.range) {
418 Curl_safefree(conn->allocptr.rangeline);
419 conn->allocptr.rangeline = aprintf("Range: %s\r\n", data->state.range);
420 p_range = conn->allocptr.rangeline;
425 * Sanity check the custom headers
427 if(Curl_checkheaders(conn, "CSeq:")) {
428 failf(data, "CSeq cannot be set as a custom header.");
429 return CURLE_RTSP_CSEQ_ERROR;
431 if(Curl_checkheaders(conn, "Session:")) {
432 failf(data, "Session ID cannot be set as a custom header.");
433 return CURLE_BAD_FUNCTION_ARGUMENT;
436 /* Initialize a dynamic send buffer */
437 req_buffer = Curl_add_buffer_init();
440 return CURLE_OUT_OF_MEMORY;
443 Curl_add_bufferf(req_buffer,
444 "%s %s RTSP/1.0\r\n" /* Request Stream-URI RTSP/1.0 */
445 "CSeq: %ld\r\n", /* CSeq */
446 (p_request ? p_request : ""), p_stream_uri,
452 * Rather than do a normal alloc line, keep the session_id unformatted
453 * to make comparison easier
456 result = Curl_add_bufferf(req_buffer, "Session: %s\r\n", p_session_id);
462 * Shared HTTP-like options
464 result = Curl_add_bufferf(req_buffer,
467 "%s" /* accept-encoding */
470 "%s" /* user-agent */
472 p_transport ? p_transport : "",
473 p_accept ? p_accept : "",
474 p_accept_encoding ? p_accept_encoding : "",
475 p_range ? p_range : "",
476 p_referrer ? p_referrer : "",
477 p_uagent ? p_uagent : "");
481 if((rtspreq == RTSPREQ_SETUP) || (rtspreq == RTSPREQ_DESCRIBE)) {
482 result = Curl_add_timecondition(data, req_buffer);
487 result = Curl_add_custom_headers(conn, FALSE, req_buffer);
491 if(rtspreq == RTSPREQ_ANNOUNCE ||
492 rtspreq == RTSPREQ_SET_PARAMETER ||
493 rtspreq == RTSPREQ_GET_PARAMETER) {
495 if(data->set.upload) {
496 putsize = data->state.infilesize;
497 data->set.httpreq = HTTPREQ_PUT;
501 postsize = (data->set.postfieldsize != -1)?
502 data->set.postfieldsize:
503 (data->set.postfields? (curl_off_t)strlen(data->set.postfields):0);
504 data->set.httpreq = HTTPREQ_POST;
507 if(putsize > 0 || postsize > 0) {
508 /* As stated in the http comments, it is probably not wise to
509 * actually set a custom Content-Length in the headers */
510 if(!Curl_checkheaders(conn, "Content-Length:")) {
511 result = Curl_add_bufferf(req_buffer,
512 "Content-Length: %" CURL_FORMAT_CURL_OFF_T"\r\n",
513 (data->set.upload ? putsize : postsize));
518 if(rtspreq == RTSPREQ_SET_PARAMETER ||
519 rtspreq == RTSPREQ_GET_PARAMETER) {
520 if(!Curl_checkheaders(conn, "Content-Type:")) {
521 result = Curl_add_bufferf(req_buffer,
522 "Content-Type: text/parameters\r\n");
528 if(rtspreq == RTSPREQ_ANNOUNCE) {
529 if(!Curl_checkheaders(conn, "Content-Type:")) {
530 result = Curl_add_bufferf(req_buffer,
531 "Content-Type: application/sdp\r\n");
537 data->state.expect100header = FALSE; /* RTSP posts are simple/small */
539 else if(rtspreq == RTSPREQ_GET_PARAMETER) {
540 /* Check for an empty GET_PARAMETER (heartbeat) request */
541 data->set.httpreq = HTTPREQ_HEAD;
542 data->set.opt_no_body = TRUE;
546 /* RTSP never allows chunked transfer */
547 data->req.forbidchunk = TRUE;
548 /* Finish the request buffer */
549 result = Curl_add_buffer(req_buffer, "\r\n", 2);
554 result = Curl_add_buffer(req_buffer, data->set.postfields,
560 /* issue the request */
561 result = Curl_add_buffer_send(req_buffer, conn,
562 &data->info.request_size, 0, FIRSTSOCKET);
564 failf(data, "Failed sending RTSP request");
568 Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE, &http->readbytecount,
569 putsize?FIRSTSOCKET:-1,
570 putsize?&http->writebytecount:NULL);
572 /* Increment the CSeq on success */
573 data->state.rtsp_next_client_CSeq++;
575 if(http->writebytecount) {
576 /* if a request-body has been sent off, we make sure this progress is
578 Curl_pgrsSetUploadCounter(data, http->writebytecount);
579 if(Curl_pgrsUpdate(conn))
580 result = CURLE_ABORTED_BY_CALLBACK;
587 static CURLcode rtsp_rtp_readwrite(struct SessionHandle *data,
588 struct connectdata *conn,
591 struct SingleRequest *k = &data->req;
592 struct rtsp_conn *rtspc = &(conn->proto.rtspc);
594 char *rtp; /* moving pointer to rtp data */
595 ssize_t rtp_dataleft; /* how much data left to parse in this round */
600 /* There was some leftover data the last time. Merge buffers */
601 char *newptr = realloc(rtspc->rtp_buf, rtspc->rtp_bufsize + *nread);
603 Curl_safefree(rtspc->rtp_buf);
604 rtspc->rtp_buf = NULL;
605 rtspc->rtp_bufsize = 0;
606 return CURLE_OUT_OF_MEMORY;
608 rtspc->rtp_buf = newptr;
609 memcpy(rtspc->rtp_buf + rtspc->rtp_bufsize, k->str, *nread);
610 rtspc->rtp_bufsize += *nread;
611 rtp = rtspc->rtp_buf;
612 rtp_dataleft = rtspc->rtp_bufsize;
615 /* Just parse the request buffer directly */
617 rtp_dataleft = *nread;
620 while((rtp_dataleft > 0) &&
622 if(rtp_dataleft > 4) {
625 /* Parse the header */
626 /* The channel identifier immediately follows and is 1 byte */
627 rtspc->rtp_channel = RTP_PKT_CHANNEL(rtp);
629 /* The length is two bytes */
630 rtp_length = RTP_PKT_LENGTH(rtp);
632 if(rtp_dataleft < rtp_length + 4) {
633 /* Need more - incomplete payload*/
638 /* We have the full RTP interleaved packet
639 * Write out the header including the leading '$' */
640 DEBUGF(infof(data, "RTP write channel %d rtp_length %d\n",
641 rtspc->rtp_channel, rtp_length));
642 result = rtp_client_write(conn, &rtp[0], rtp_length + 4);
644 failf(data, "Got an error writing an RTP packet");
646 Curl_safefree(rtspc->rtp_buf);
647 rtspc->rtp_buf = NULL;
648 rtspc->rtp_bufsize = 0;
652 /* Move forward in the buffer */
653 rtp_dataleft -= rtp_length + 4;
654 rtp += rtp_length + 4;
656 if(data->set.rtspreq == RTSPREQ_RECEIVE) {
657 /* If we are in a passive receive, give control back
658 * to the app as often as we can.
660 k->keepon &= ~KEEP_RECV;
665 /* Need more - incomplete header */
671 if(rtp_dataleft != 0 && rtp[0] == '$') {
672 DEBUGF(infof(data, "RTP Rewinding %zd %s\n", rtp_dataleft,
673 *readmore ? "(READMORE)" : ""));
675 /* Store the incomplete RTP packet for a "rewind" */
676 scratch = malloc(rtp_dataleft);
678 Curl_safefree(rtspc->rtp_buf);
679 rtspc->rtp_buf = NULL;
680 rtspc->rtp_bufsize = 0;
681 return CURLE_OUT_OF_MEMORY;
683 memcpy(scratch, rtp, rtp_dataleft);
684 Curl_safefree(rtspc->rtp_buf);
685 rtspc->rtp_buf = scratch;
686 rtspc->rtp_bufsize = rtp_dataleft;
688 /* As far as the transfer is concerned, this data is consumed */
693 /* Fix up k->str to point just after the last RTP packet */
694 k->str += *nread - rtp_dataleft;
696 /* either all of the data has been read or...
697 * rtp now points at the next byte to parse
700 DEBUGASSERT(k->str[0] == rtp[0]);
702 DEBUGASSERT(rtp_dataleft <= *nread); /* sanity check */
704 *nread = rtp_dataleft;
707 /* If we get here, we have finished with the leftover/merge buffer */
708 Curl_safefree(rtspc->rtp_buf);
709 rtspc->rtp_buf = NULL;
710 rtspc->rtp_bufsize = 0;
716 CURLcode rtp_client_write(struct connectdata *conn, char *ptr, size_t len)
718 struct SessionHandle *data = conn->data;
720 curl_write_callback writeit;
723 failf (data, "Cannot write a 0 size RTP packet.");
724 return CURLE_WRITE_ERROR;
727 writeit = data->set.fwrite_rtp?data->set.fwrite_rtp:data->set.fwrite_func;
728 wrote = writeit(ptr, 1, len, data->set.rtp_out);
730 if(CURL_WRITEFUNC_PAUSE == wrote) {
731 failf (data, "Cannot pause RTP");
732 return CURLE_WRITE_ERROR;
736 failf (data, "Failed writing RTP data");
737 return CURLE_WRITE_ERROR;
743 CURLcode Curl_rtsp_parseheader(struct connectdata *conn,
746 struct SessionHandle *data = conn->data;
749 if(checkprefix("CSeq:", header)) {
750 /* Store the received CSeq. Match is verified in rtsp_done */
751 int nc = sscanf(&header[4], ": %ld", &CSeq);
753 struct RTSP *rtsp = data->req.protop;
754 rtsp->CSeq_recv = CSeq; /* mark the request */
755 data->state.rtsp_CSeq_recv = CSeq; /* update the handle */
758 failf(data, "Unable to read the CSeq header: [%s]", header);
759 return CURLE_RTSP_CSEQ_ERROR;
762 else if(checkprefix("Session:", header)) {
765 /* Find the first non-space letter */
767 while(*start && ISSPACE(*start))
771 failf(data, "Got a blank Session ID");
773 else if(data->set.str[STRING_RTSP_SESSION_ID]) {
774 /* If the Session ID is set, then compare */
775 if(strncmp(start, data->set.str[STRING_RTSP_SESSION_ID],
776 strlen(data->set.str[STRING_RTSP_SESSION_ID])) != 0) {
777 failf(data, "Got RTSP Session ID Line [%s], but wanted ID [%s]",
778 start, data->set.str[STRING_RTSP_SESSION_ID]);
779 return CURLE_RTSP_SESSION_ERROR;
783 /* If the Session ID is not set, and we find it in a response, then
786 /* The session ID can be an alphanumeric or a 'safe' character
788 * RFC 2326 15.1 Base Syntax:
789 * safe = "\$" | "-" | "_" | "." | "+"
793 (ISALNUM(*end) || *end == '-' || *end == '_' || *end == '.' ||
795 (*end == '\\' && *(end + 1) && *(end + 1) == '$' && (++end, 1))))
798 /* Copy the id substring into a new buffer */
799 data->set.str[STRING_RTSP_SESSION_ID] = malloc(end - start + 1);
800 if(data->set.str[STRING_RTSP_SESSION_ID] == NULL)
801 return CURLE_OUT_OF_MEMORY;
802 memcpy(data->set.str[STRING_RTSP_SESSION_ID], start, end - start);
803 (data->set.str[STRING_RTSP_SESSION_ID])[end - start] = '\0';
809 #endif /* CURL_DISABLE_RTSP */