1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2011, 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 ***************************************************************************/
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,
85 /* this returns the socket to wait for in the DO and DOING state for the multi
86 interface and then we're always _sending_ a request and thus we wait for
87 the single socket to become writable only */
88 static int rtsp_getsock_do(struct connectdata *conn,
93 (void)numsocks; /* unused, we trust it to be at least 1 */
94 socks[0] = conn->sock[FIRSTSOCKET];
95 return GETSOCK_WRITESOCK(0);
99 CURLcode rtp_client_write(struct connectdata *conn, char *ptr, size_t len);
103 * RTSP handler interface.
105 const struct Curl_handler Curl_handler_rtsp = {
107 ZERO_NULL, /* setup_connection */
109 rtsp_done, /* done */
110 ZERO_NULL, /* do_more */
111 rtsp_connect, /* connect_it */
112 ZERO_NULL, /* connecting */
113 ZERO_NULL, /* doing */
114 ZERO_NULL, /* proto_getsock */
115 rtsp_getsock_do, /* doing_getsock */
116 ZERO_NULL, /* perform_getsock */
117 rtsp_disconnect, /* disconnect */
118 rtsp_rtp_readwrite, /* readwrite */
119 PORT_RTSP, /* defport */
120 CURLPROTO_RTSP, /* protocol */
121 PROTOPT_NONE /* flags */
125 * The server may send us RTP data at any point, and RTSPREQ_RECEIVE does not
126 * want to block the application forever while receiving a stream. Therefore,
127 * we cannot assume that an RTSP socket is dead just because it is readable.
129 * Instead, if it is readable, run Curl_getconnectinfo() to peek at the socket
130 * and distinguish between closed and data.
132 bool Curl_rtsp_connisdead(struct connectdata *check)
137 sval = Curl_socket_ready(check->sock[FIRSTSOCKET], CURL_SOCKET_BAD, 0);
142 else if(sval & CURL_CSELECT_ERR) {
143 /* socket is in an error state */
146 else if((sval & CURL_CSELECT_IN) && check->data) {
147 /* readable with no error. could be closed or could be alive but we can
148 only check if we have a proper SessionHandle for the connection */
149 curl_socket_t connectinfo = Curl_getconnectinfo(check->data, &check);
150 if(connectinfo != CURL_SOCKET_BAD)
157 static CURLcode rtsp_connect(struct connectdata *conn, bool *done)
160 struct SessionHandle *data = conn->data;
162 httpStatus = Curl_http_connect(conn, done);
164 /* Initialize the CSeq if not already done */
165 if(data->state.rtsp_next_client_CSeq == 0)
166 data->state.rtsp_next_client_CSeq = 1;
167 if(data->state.rtsp_next_server_CSeq == 0)
168 data->state.rtsp_next_server_CSeq = 1;
170 conn->proto.rtspc.rtp_channel = -1;
175 static CURLcode rtsp_disconnect(struct connectdata *conn, bool dead)
178 Curl_safefree(conn->proto.rtspc.rtp_buf);
183 static CURLcode rtsp_done(struct connectdata *conn,
184 CURLcode status, bool premature)
186 struct SessionHandle *data = conn->data;
187 struct RTSP *rtsp = data->state.proto.rtsp;
192 /* Bypass HTTP empty-reply checks on receive */
193 if(data->set.rtspreq == RTSPREQ_RECEIVE)
196 httpStatus = Curl_http_done(conn, status, premature);
199 /* Check the sequence numbers */
200 CSeq_sent = rtsp->CSeq_sent;
201 CSeq_recv = rtsp->CSeq_recv;
202 if((data->set.rtspreq != RTSPREQ_RECEIVE) && (CSeq_sent != CSeq_recv)) {
204 "The CSeq of this request %ld did not match the response %ld",
205 CSeq_sent, CSeq_recv);
206 return CURLE_RTSP_CSEQ_ERROR;
208 else if(data->set.rtspreq == RTSPREQ_RECEIVE &&
209 (conn->proto.rtspc.rtp_channel == -1)) {
210 infof(data, "Got an RTP Receive with a CSeq of %ld\n", CSeq_recv);
211 /* TODO CPC: Server -> Client logic here */
218 static CURLcode rtsp_do(struct connectdata *conn, bool *done)
220 struct SessionHandle *data = conn->data;
221 CURLcode result=CURLE_OK;
222 Curl_RtspReq rtspreq = data->set.rtspreq;
225 Curl_send_buffer *req_buffer;
226 curl_off_t postsize = 0; /* for ANNOUNCE and SET_PARAMETER */
227 curl_off_t putsize = 0; /* for ANNOUNCE and SET_PARAMETER */
229 const char *p_request = NULL;
230 const char *p_session_id = NULL;
231 const char *p_accept = NULL;
232 const char *p_accept_encoding = NULL;
233 const char *p_range = NULL;
234 const char *p_referrer = NULL;
235 const char *p_stream_uri = NULL;
236 const char *p_transport = NULL;
237 const char *p_uagent = NULL;
241 Curl_reset_reqproto(conn);
243 if(!data->state.proto.rtsp) {
244 /* Only allocate this struct if we don't already have it! */
246 rtsp = calloc(1, sizeof(struct RTSP));
248 return CURLE_OUT_OF_MEMORY;
249 data->state.proto.rtsp = rtsp;
252 rtsp = data->state.proto.rtsp;
255 http = &(rtsp->http_wrapper);
256 /* Assert that no one has changed the RTSP struct in an evil way */
257 DEBUGASSERT((void *)http == (void *)rtsp);
259 rtsp->CSeq_sent = data->state.rtsp_next_client_CSeq;
262 /* Setup the 'p_request' pointer to the proper p_request string
263 * Since all RTSP requests are included here, there is no need to
264 * support custom requests like HTTP.
266 DEBUGASSERT((rtspreq > RTSPREQ_NONE && rtspreq < RTSPREQ_LAST));
267 data->set.opt_no_body = TRUE; /* most requests don't contain a body */
270 failf(data, "Got invalid RTSP request: RTSPREQ_NONE");
271 return CURLE_BAD_FUNCTION_ARGUMENT;
272 case RTSPREQ_OPTIONS:
273 p_request = "OPTIONS";
275 case RTSPREQ_DESCRIBE:
276 p_request = "DESCRIBE";
277 data->set.opt_no_body = FALSE;
279 case RTSPREQ_ANNOUNCE:
280 p_request = "ANNOUNCE";
291 case RTSPREQ_TEARDOWN:
292 p_request = "TEARDOWN";
294 case RTSPREQ_GET_PARAMETER:
295 /* GET_PARAMETER's no_body status is determined later */
296 p_request = "GET_PARAMETER";
297 data->set.opt_no_body = FALSE;
299 case RTSPREQ_SET_PARAMETER:
300 p_request = "SET_PARAMETER";
303 p_request = "RECORD";
305 case RTSPREQ_RECEIVE:
307 /* Treat interleaved RTP as body*/
308 data->set.opt_no_body = FALSE;
311 failf(data, "Got invalid RTSP request: RTSPREQ_LAST");
312 return CURLE_BAD_FUNCTION_ARGUMENT;
315 if(rtspreq == RTSPREQ_RECEIVE) {
316 Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
317 &http->readbytecount, -1, NULL);
322 p_session_id = data->set.str[STRING_RTSP_SESSION_ID];
324 (rtspreq & ~(RTSPREQ_OPTIONS | RTSPREQ_DESCRIBE | RTSPREQ_SETUP))) {
325 failf(data, "Refusing to issue an RTSP request [%s] without a session ID.",
326 p_request ? p_request : "");
327 return CURLE_BAD_FUNCTION_ARGUMENT;
333 /* Stream URI. Default to server '*' if not specified */
334 if(data->set.str[STRING_RTSP_STREAM_URI]) {
335 p_stream_uri = data->set.str[STRING_RTSP_STREAM_URI];
341 /* Transport Header for SETUP requests */
342 p_transport = Curl_checkheaders(data, "Transport:");
343 if(rtspreq == RTSPREQ_SETUP && !p_transport) {
344 /* New Transport: setting? */
345 if(data->set.str[STRING_RTSP_TRANSPORT]) {
346 Curl_safefree(conn->allocptr.rtsp_transport);
348 conn->allocptr.rtsp_transport =
349 aprintf("Transport: %s\r\n",
350 data->set.str[STRING_RTSP_TRANSPORT]);
351 if(!conn->allocptr.rtsp_transport)
352 return CURLE_OUT_OF_MEMORY;
356 "Refusing to issue an RTSP SETUP without a Transport: header.");
357 return CURLE_BAD_FUNCTION_ARGUMENT;
360 p_transport = conn->allocptr.rtsp_transport;
363 /* Accept Headers for DESCRIBE requests */
364 if(rtspreq == RTSPREQ_DESCRIBE) {
366 p_accept = Curl_checkheaders(data, "Accept:")?
367 NULL:"Accept: application/sdp\r\n";
369 /* Accept-Encoding header */
370 if(!Curl_checkheaders(data, "Accept-Encoding:") &&
371 data->set.str[STRING_ENCODING]) {
372 Curl_safefree(conn->allocptr.accept_encoding);
373 conn->allocptr.accept_encoding =
374 aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]);
376 if(!conn->allocptr.accept_encoding)
377 return CURLE_OUT_OF_MEMORY;
379 p_accept_encoding = conn->allocptr.accept_encoding;
383 /* The User-Agent string might have been allocated in url.c already, because
384 it might have been used in the proxy connect, but if we have got a header
385 with the user-agent string specified, we erase the previously made string
387 if(Curl_checkheaders(data, "User-Agent:") && conn->allocptr.uagent) {
388 Curl_safefree(conn->allocptr.uagent);
389 conn->allocptr.uagent = NULL;
391 else if(!Curl_checkheaders(data, "User-Agent:") &&
392 data->set.str[STRING_USERAGENT]) {
393 p_uagent = conn->allocptr.uagent;
397 Curl_safefree(conn->allocptr.ref);
398 if(data->change.referer && !Curl_checkheaders(data, "Referer:"))
399 conn->allocptr.ref = aprintf("Referer: %s\r\n", data->change.referer);
401 conn->allocptr.ref = NULL;
403 p_referrer = conn->allocptr.ref;
407 * Only applies to PLAY, PAUSE, RECORD
409 * Go ahead and use the Range stuff supplied for HTTP
411 if(data->state.use_range &&
412 (rtspreq & (RTSPREQ_PLAY | RTSPREQ_PAUSE | RTSPREQ_RECORD))) {
414 /* Check to see if there is a range set in the custom headers */
415 if(!Curl_checkheaders(data, "Range:") && data->state.range) {
416 Curl_safefree(conn->allocptr.rangeline);
417 conn->allocptr.rangeline = aprintf("Range: %s\r\n", data->state.range);
418 p_range = conn->allocptr.rangeline;
423 * Sanity check the custom headers
425 if(Curl_checkheaders(data, "CSeq:")) {
426 failf(data, "CSeq cannot be set as a custom header.");
427 return CURLE_RTSP_CSEQ_ERROR;
429 if(Curl_checkheaders(data, "Session:")) {
430 failf(data, "Session ID cannot be set as a custom header.");
431 return CURLE_BAD_FUNCTION_ARGUMENT;
434 /* Initialize a dynamic send buffer */
435 req_buffer = Curl_add_buffer_init();
438 return CURLE_OUT_OF_MEMORY;
441 Curl_add_bufferf(req_buffer,
442 "%s %s RTSP/1.0\r\n" /* Request Stream-URI RTSP/1.0 */
443 "CSeq: %ld\r\n", /* CSeq */
444 (p_request ? p_request : ""), p_stream_uri,
450 * Rather than do a normal alloc line, keep the session_id unformatted
451 * to make comparison easier
454 result = Curl_add_bufferf(req_buffer, "Session: %s\r\n", p_session_id);
460 * Shared HTTP-like options
462 result = Curl_add_bufferf(req_buffer,
465 "%s" /* accept-encoding */
468 "%s" /* user-agent */
470 p_transport ? p_transport : "",
471 p_accept ? p_accept : "",
472 p_accept_encoding ? p_accept_encoding : "",
473 p_range ? p_range : "",
474 p_referrer ? p_referrer : "",
475 p_uagent ? p_uagent : "");
479 if((rtspreq == RTSPREQ_SETUP) || (rtspreq == RTSPREQ_DESCRIBE)) {
480 result = Curl_add_timecondition(data, req_buffer);
485 result = Curl_add_custom_headers(conn, req_buffer);
489 if(rtspreq == RTSPREQ_ANNOUNCE ||
490 rtspreq == RTSPREQ_SET_PARAMETER ||
491 rtspreq == RTSPREQ_GET_PARAMETER) {
493 if(data->set.upload) {
494 putsize = data->set.infilesize;
495 data->set.httpreq = HTTPREQ_PUT;
499 postsize = (data->set.postfieldsize != -1)?
500 data->set.postfieldsize:
501 (data->set.postfields? (curl_off_t)strlen(data->set.postfields):0);
502 data->set.httpreq = HTTPREQ_POST;
505 if(putsize > 0 || postsize > 0) {
506 /* As stated in the http comments, it is probably not wise to
507 * actually set a custom Content-Length in the headers */
508 if(!Curl_checkheaders(data, "Content-Length:")) {
509 result = Curl_add_bufferf(req_buffer,
510 "Content-Length: %" FORMAT_OFF_T"\r\n",
511 (data->set.upload ? putsize : postsize));
516 if(rtspreq == RTSPREQ_SET_PARAMETER ||
517 rtspreq == RTSPREQ_GET_PARAMETER) {
518 if(!Curl_checkheaders(data, "Content-Type:")) {
519 result = Curl_add_bufferf(req_buffer,
520 "Content-Type: text/parameters\r\n");
526 if(rtspreq == RTSPREQ_ANNOUNCE) {
527 if(!Curl_checkheaders(data, "Content-Type:")) {
528 result = Curl_add_bufferf(req_buffer,
529 "Content-Type: application/sdp\r\n");
535 data->state.expect100header = FALSE; /* RTSP posts are simple/small */
537 else if(rtspreq == RTSPREQ_GET_PARAMETER) {
538 /* Check for an empty GET_PARAMETER (heartbeat) request */
539 data->set.httpreq = HTTPREQ_HEAD;
540 data->set.opt_no_body = TRUE;
544 /* RTSP never allows chunked transfer */
545 data->req.forbidchunk = TRUE;
546 /* Finish the request buffer */
547 result = Curl_add_buffer(req_buffer, "\r\n", 2);
552 result = Curl_add_buffer(req_buffer, data->set.postfields,
558 /* issue the request */
559 result = Curl_add_buffer_send(req_buffer, conn,
560 &data->info.request_size, 0, FIRSTSOCKET);
562 failf(data, "Failed sending RTSP request");
566 Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE, &http->readbytecount,
567 putsize?FIRSTSOCKET:-1,
568 putsize?&http->writebytecount:NULL);
570 /* Increment the CSeq on success */
571 data->state.rtsp_next_client_CSeq++;
573 if(http->writebytecount) {
574 /* if a request-body has been sent off, we make sure this progress is
576 Curl_pgrsSetUploadCounter(data, http->writebytecount);
577 if(Curl_pgrsUpdate(conn))
578 result = CURLE_ABORTED_BY_CALLBACK;
585 static CURLcode rtsp_rtp_readwrite(struct SessionHandle *data,
586 struct connectdata *conn,
589 struct SingleRequest *k = &data->req;
590 struct rtsp_conn *rtspc = &(conn->proto.rtspc);
592 char *rtp; /* moving pointer to rtp data */
593 ssize_t rtp_dataleft; /* how much data left to parse in this round */
598 /* There was some leftover data the last time. Merge buffers */
599 char *newptr = realloc(rtspc->rtp_buf, rtspc->rtp_bufsize + *nread);
601 Curl_safefree(rtspc->rtp_buf);
602 rtspc->rtp_buf = NULL;
603 rtspc->rtp_bufsize = 0;
604 return CURLE_OUT_OF_MEMORY;
606 rtspc->rtp_buf = newptr;
607 memcpy(rtspc->rtp_buf + rtspc->rtp_bufsize, k->str, *nread);
608 rtspc->rtp_bufsize += *nread;
609 rtp = rtspc->rtp_buf;
610 rtp_dataleft = rtspc->rtp_bufsize;
613 /* Just parse the request buffer directly */
615 rtp_dataleft = *nread;
618 while((rtp_dataleft > 0) &&
620 if(rtp_dataleft > 4) {
623 /* Parse the header */
624 /* The channel identifier immediately follows and is 1 byte */
625 rtspc->rtp_channel = RTP_PKT_CHANNEL(rtp);
627 /* The length is two bytes */
628 rtp_length = RTP_PKT_LENGTH(rtp);
630 if(rtp_dataleft < rtp_length + 4) {
631 /* Need more - incomplete payload*/
636 /* We have the full RTP interleaved packet
637 * Write out the header including the leading '$' */
638 DEBUGF(infof(data, "RTP write channel %d rtp_length %d\n",
639 rtspc->rtp_channel, rtp_length));
640 result = rtp_client_write(conn, &rtp[0], rtp_length + 4);
642 failf(data, "Got an error writing an RTP packet");
644 Curl_safefree(rtspc->rtp_buf);
645 rtspc->rtp_buf = NULL;
646 rtspc->rtp_bufsize = 0;
650 /* Move forward in the buffer */
651 rtp_dataleft -= rtp_length + 4;
652 rtp += rtp_length + 4;
654 if(data->set.rtspreq == RTSPREQ_RECEIVE) {
655 /* If we are in a passive receive, give control back
656 * to the app as often as we can.
658 k->keepon &= ~KEEP_RECV;
663 /* Need more - incomplete header */
669 if(rtp_dataleft != 0 && rtp[0] == '$') {
670 DEBUGF(infof(data, "RTP Rewinding %zu %s\n", rtp_dataleft,
671 *readmore ? "(READMORE)" : ""));
673 /* Store the incomplete RTP packet for a "rewind" */
674 scratch = malloc(rtp_dataleft);
676 Curl_safefree(rtspc->rtp_buf);
677 rtspc->rtp_buf = NULL;
678 rtspc->rtp_bufsize = 0;
679 return CURLE_OUT_OF_MEMORY;
681 memcpy(scratch, rtp, rtp_dataleft);
682 Curl_safefree(rtspc->rtp_buf);
683 rtspc->rtp_buf = scratch;
684 rtspc->rtp_bufsize = rtp_dataleft;
686 /* As far as the transfer is concerned, this data is consumed */
691 /* Fix up k->str to point just after the last RTP packet */
692 k->str += *nread - rtp_dataleft;
694 /* either all of the data has been read or...
695 * rtp now points at the next byte to parse
698 DEBUGASSERT(k->str[0] == rtp[0]);
700 DEBUGASSERT(rtp_dataleft <= *nread); /* sanity check */
702 *nread = rtp_dataleft;
705 /* If we get here, we have finished with the leftover/merge buffer */
706 Curl_safefree(rtspc->rtp_buf);
707 rtspc->rtp_buf = NULL;
708 rtspc->rtp_bufsize = 0;
714 CURLcode rtp_client_write(struct connectdata *conn, char *ptr, size_t len)
716 struct SessionHandle *data = conn->data;
718 curl_write_callback writeit;
721 failf (data, "Cannot write a 0 size RTP packet.");
722 return CURLE_WRITE_ERROR;
725 writeit = data->set.fwrite_rtp?data->set.fwrite_rtp:data->set.fwrite_func;
726 wrote = writeit(ptr, 1, len, data->set.rtp_out);
728 if(CURL_WRITEFUNC_PAUSE == wrote) {
729 failf (data, "Cannot pause RTP");
730 return CURLE_WRITE_ERROR;
734 failf (data, "Failed writing RTP data");
735 return CURLE_WRITE_ERROR;
741 CURLcode Curl_rtsp_parseheader(struct connectdata *conn,
744 struct SessionHandle *data = conn->data;
747 if(checkprefix("CSeq:", header)) {
748 /* Store the received CSeq. Match is verified in rtsp_done */
750 char *temp = strdup(header);
752 return CURLE_OUT_OF_MEMORY;
753 Curl_strntoupper(temp, temp, sizeof(temp));
754 nc = sscanf(temp, "CSEQ: %ld", &CSeq);
757 data->state.proto.rtsp->CSeq_recv = CSeq; /* mark the request */
758 data->state.rtsp_CSeq_recv = CSeq; /* update the handle */
761 failf(data, "Unable to read the CSeq header: [%s]", header);
762 return CURLE_RTSP_CSEQ_ERROR;
765 else if(checkprefix("Session:", header)) {
768 /* Find the first non-space letter */
770 while(*start && ISSPACE(*start))
774 failf(data, "Got a blank Session ID");
776 else if(data->set.str[STRING_RTSP_SESSION_ID]) {
777 /* If the Session ID is set, then compare */
778 if(strncmp(start, data->set.str[STRING_RTSP_SESSION_ID],
779 strlen(data->set.str[STRING_RTSP_SESSION_ID])) != 0) {
780 failf(data, "Got RTSP Session ID Line [%s], but wanted ID [%s]",
781 start, data->set.str[STRING_RTSP_SESSION_ID]);
782 return CURLE_RTSP_SESSION_ERROR;
786 /* If the Session ID is not set, and we find it in a response, then
789 /* The session ID can be an alphanumeric or a 'safe' character
791 * RFC 2326 15.1 Base Syntax:
792 * safe = "\$" | "-" | "_" | "." | "+"
796 (ISALNUM(*end) || *end == '-' || *end == '_' || *end == '.' ||
798 (*end == '\\' && *(end + 1) && *(end + 1) == '$' && (++end, 1))))
801 /* Copy the id substring into a new buffer */
802 data->set.str[STRING_RTSP_SESSION_ID] = malloc(end - start + 1);
803 if(data->set.str[STRING_RTSP_SESSION_ID] == NULL)
804 return CURLE_OUT_OF_MEMORY;
805 memcpy(data->set.str[STRING_RTSP_SESSION_ID], start, end - start);
806 (data->set.str[STRING_RTSP_SESSION_ID])[end - start] = '\0';
812 #endif /* CURL_DISABLE_RTSP */