1 /***************************************************************************
3 * Project ___| | | | _ \| |
5 * | (__| |_| | _ <| |___
6 * \___|\___/|_| \_\_____|
8 * Copyright (C) 1998 - 2012, 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,
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, /* domore_getsock */
117 ZERO_NULL, /* perform_getsock */
118 rtsp_disconnect, /* disconnect */
119 rtsp_rtp_readwrite, /* readwrite */
120 PORT_RTSP, /* defport */
121 CURLPROTO_RTSP, /* protocol */
122 PROTOPT_NONE /* flags */
126 * The server may send us RTP data at any point, and RTSPREQ_RECEIVE does not
127 * want to block the application forever while receiving a stream. Therefore,
128 * we cannot assume that an RTSP socket is dead just because it is readable.
130 * Instead, if it is readable, run Curl_getconnectinfo() to peek at the socket
131 * and distinguish between closed and data.
133 bool Curl_rtsp_connisdead(struct connectdata *check)
138 sval = Curl_socket_ready(check->sock[FIRSTSOCKET], CURL_SOCKET_BAD, 0);
143 else if(sval & CURL_CSELECT_ERR) {
144 /* socket is in an error state */
147 else if((sval & CURL_CSELECT_IN) && check->data) {
148 /* readable with no error. could be closed or could be alive but we can
149 only check if we have a proper SessionHandle for the connection */
150 curl_socket_t connectinfo = Curl_getconnectinfo(check->data, &check);
151 if(connectinfo != CURL_SOCKET_BAD)
158 static CURLcode rtsp_connect(struct connectdata *conn, bool *done)
161 struct SessionHandle *data = conn->data;
163 httpStatus = Curl_http_connect(conn, done);
165 /* Initialize the CSeq if not already done */
166 if(data->state.rtsp_next_client_CSeq == 0)
167 data->state.rtsp_next_client_CSeq = 1;
168 if(data->state.rtsp_next_server_CSeq == 0)
169 data->state.rtsp_next_server_CSeq = 1;
171 conn->proto.rtspc.rtp_channel = -1;
176 static CURLcode rtsp_disconnect(struct connectdata *conn, bool dead)
179 Curl_safefree(conn->proto.rtspc.rtp_buf);
184 static CURLcode rtsp_done(struct connectdata *conn,
185 CURLcode status, bool premature)
187 struct SessionHandle *data = conn->data;
188 struct RTSP *rtsp = data->state.proto.rtsp;
193 /* Bypass HTTP empty-reply checks on receive */
194 if(data->set.rtspreq == RTSPREQ_RECEIVE)
197 httpStatus = Curl_http_done(conn, status, premature);
200 /* Check the sequence numbers */
201 CSeq_sent = rtsp->CSeq_sent;
202 CSeq_recv = rtsp->CSeq_recv;
203 if((data->set.rtspreq != RTSPREQ_RECEIVE) && (CSeq_sent != CSeq_recv)) {
205 "The CSeq of this request %ld did not match the response %ld",
206 CSeq_sent, CSeq_recv);
207 return CURLE_RTSP_CSEQ_ERROR;
209 else if(data->set.rtspreq == RTSPREQ_RECEIVE &&
210 (conn->proto.rtspc.rtp_channel == -1)) {
211 infof(data, "Got an RTP Receive with a CSeq of %ld\n", CSeq_recv);
212 /* TODO CPC: Server -> Client logic here */
219 static CURLcode rtsp_do(struct connectdata *conn, bool *done)
221 struct SessionHandle *data = conn->data;
222 CURLcode result=CURLE_OK;
223 Curl_RtspReq rtspreq = data->set.rtspreq;
226 Curl_send_buffer *req_buffer;
227 curl_off_t postsize = 0; /* for ANNOUNCE and SET_PARAMETER */
228 curl_off_t putsize = 0; /* for ANNOUNCE and SET_PARAMETER */
230 const char *p_request = NULL;
231 const char *p_session_id = NULL;
232 const char *p_accept = NULL;
233 const char *p_accept_encoding = NULL;
234 const char *p_range = NULL;
235 const char *p_referrer = NULL;
236 const char *p_stream_uri = NULL;
237 const char *p_transport = NULL;
238 const char *p_uagent = NULL;
242 Curl_reset_reqproto(conn);
244 if(!data->state.proto.rtsp) {
245 /* Only allocate this struct if we don't already have it! */
247 rtsp = calloc(1, sizeof(struct RTSP));
249 return CURLE_OUT_OF_MEMORY;
250 data->state.proto.rtsp = rtsp;
253 rtsp = data->state.proto.rtsp;
256 http = &(rtsp->http_wrapper);
257 /* Assert that no one has changed the RTSP struct in an evil way */
258 DEBUGASSERT((void *)http == (void *)rtsp);
260 rtsp->CSeq_sent = data->state.rtsp_next_client_CSeq;
263 /* Setup the 'p_request' pointer to the proper p_request string
264 * Since all RTSP requests are included here, there is no need to
265 * support custom requests like HTTP.
267 DEBUGASSERT((rtspreq > RTSPREQ_NONE && rtspreq < RTSPREQ_LAST));
268 data->set.opt_no_body = TRUE; /* most requests don't contain a body */
271 failf(data, "Got invalid RTSP request: RTSPREQ_NONE");
272 return CURLE_BAD_FUNCTION_ARGUMENT;
273 case RTSPREQ_OPTIONS:
274 p_request = "OPTIONS";
276 case RTSPREQ_DESCRIBE:
277 p_request = "DESCRIBE";
278 data->set.opt_no_body = FALSE;
280 case RTSPREQ_ANNOUNCE:
281 p_request = "ANNOUNCE";
292 case RTSPREQ_TEARDOWN:
293 p_request = "TEARDOWN";
295 case RTSPREQ_GET_PARAMETER:
296 /* GET_PARAMETER's no_body status is determined later */
297 p_request = "GET_PARAMETER";
298 data->set.opt_no_body = FALSE;
300 case RTSPREQ_SET_PARAMETER:
301 p_request = "SET_PARAMETER";
304 p_request = "RECORD";
306 case RTSPREQ_RECEIVE:
308 /* Treat interleaved RTP as body*/
309 data->set.opt_no_body = FALSE;
312 failf(data, "Got invalid RTSP request: RTSPREQ_LAST");
313 return CURLE_BAD_FUNCTION_ARGUMENT;
316 if(rtspreq == RTSPREQ_RECEIVE) {
317 Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
318 &http->readbytecount, -1, NULL);
323 p_session_id = data->set.str[STRING_RTSP_SESSION_ID];
325 (rtspreq & ~(RTSPREQ_OPTIONS | RTSPREQ_DESCRIBE | RTSPREQ_SETUP))) {
326 failf(data, "Refusing to issue an RTSP request [%s] without a session ID.",
327 p_request ? p_request : "");
328 return CURLE_BAD_FUNCTION_ARGUMENT;
334 /* Stream URI. Default to server '*' if not specified */
335 if(data->set.str[STRING_RTSP_STREAM_URI]) {
336 p_stream_uri = data->set.str[STRING_RTSP_STREAM_URI];
342 /* Transport Header for SETUP requests */
343 p_transport = Curl_checkheaders(data, "Transport:");
344 if(rtspreq == RTSPREQ_SETUP && !p_transport) {
345 /* New Transport: setting? */
346 if(data->set.str[STRING_RTSP_TRANSPORT]) {
347 Curl_safefree(conn->allocptr.rtsp_transport);
349 conn->allocptr.rtsp_transport =
350 aprintf("Transport: %s\r\n",
351 data->set.str[STRING_RTSP_TRANSPORT]);
352 if(!conn->allocptr.rtsp_transport)
353 return CURLE_OUT_OF_MEMORY;
357 "Refusing to issue an RTSP SETUP without a Transport: header.");
358 return CURLE_BAD_FUNCTION_ARGUMENT;
361 p_transport = conn->allocptr.rtsp_transport;
364 /* Accept Headers for DESCRIBE requests */
365 if(rtspreq == RTSPREQ_DESCRIBE) {
367 p_accept = Curl_checkheaders(data, "Accept:")?
368 NULL:"Accept: application/sdp\r\n";
370 /* Accept-Encoding header */
371 if(!Curl_checkheaders(data, "Accept-Encoding:") &&
372 data->set.str[STRING_ENCODING]) {
373 Curl_safefree(conn->allocptr.accept_encoding);
374 conn->allocptr.accept_encoding =
375 aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]);
377 if(!conn->allocptr.accept_encoding)
378 return CURLE_OUT_OF_MEMORY;
380 p_accept_encoding = conn->allocptr.accept_encoding;
384 /* The User-Agent string might have been allocated in url.c already, because
385 it might have been used in the proxy connect, but if we have got a header
386 with the user-agent string specified, we erase the previously made string
388 if(Curl_checkheaders(data, "User-Agent:") && conn->allocptr.uagent) {
389 Curl_safefree(conn->allocptr.uagent);
390 conn->allocptr.uagent = NULL;
392 else if(!Curl_checkheaders(data, "User-Agent:") &&
393 data->set.str[STRING_USERAGENT]) {
394 p_uagent = conn->allocptr.uagent;
398 Curl_safefree(conn->allocptr.ref);
399 if(data->change.referer && !Curl_checkheaders(data, "Referer:"))
400 conn->allocptr.ref = aprintf("Referer: %s\r\n", data->change.referer);
402 conn->allocptr.ref = NULL;
404 p_referrer = conn->allocptr.ref;
408 * Only applies to PLAY, PAUSE, RECORD
410 * Go ahead and use the Range stuff supplied for HTTP
412 if(data->state.use_range &&
413 (rtspreq & (RTSPREQ_PLAY | RTSPREQ_PAUSE | RTSPREQ_RECORD))) {
415 /* Check to see if there is a range set in the custom headers */
416 if(!Curl_checkheaders(data, "Range:") && data->state.range) {
417 Curl_safefree(conn->allocptr.rangeline);
418 conn->allocptr.rangeline = aprintf("Range: %s\r\n", data->state.range);
419 p_range = conn->allocptr.rangeline;
424 * Sanity check the custom headers
426 if(Curl_checkheaders(data, "CSeq:")) {
427 failf(data, "CSeq cannot be set as a custom header.");
428 return CURLE_RTSP_CSEQ_ERROR;
430 if(Curl_checkheaders(data, "Session:")) {
431 failf(data, "Session ID cannot be set as a custom header.");
432 return CURLE_BAD_FUNCTION_ARGUMENT;
435 /* Initialize a dynamic send buffer */
436 req_buffer = Curl_add_buffer_init();
439 return CURLE_OUT_OF_MEMORY;
442 Curl_add_bufferf(req_buffer,
443 "%s %s RTSP/1.0\r\n" /* Request Stream-URI RTSP/1.0 */
444 "CSeq: %ld\r\n", /* CSeq */
445 (p_request ? p_request : ""), p_stream_uri,
451 * Rather than do a normal alloc line, keep the session_id unformatted
452 * to make comparison easier
455 result = Curl_add_bufferf(req_buffer, "Session: %s\r\n", p_session_id);
461 * Shared HTTP-like options
463 result = Curl_add_bufferf(req_buffer,
466 "%s" /* accept-encoding */
469 "%s" /* user-agent */
471 p_transport ? p_transport : "",
472 p_accept ? p_accept : "",
473 p_accept_encoding ? p_accept_encoding : "",
474 p_range ? p_range : "",
475 p_referrer ? p_referrer : "",
476 p_uagent ? p_uagent : "");
480 if((rtspreq == RTSPREQ_SETUP) || (rtspreq == RTSPREQ_DESCRIBE)) {
481 result = Curl_add_timecondition(data, req_buffer);
486 result = Curl_add_custom_headers(conn, req_buffer);
490 if(rtspreq == RTSPREQ_ANNOUNCE ||
491 rtspreq == RTSPREQ_SET_PARAMETER ||
492 rtspreq == RTSPREQ_GET_PARAMETER) {
494 if(data->set.upload) {
495 putsize = data->set.infilesize;
496 data->set.httpreq = HTTPREQ_PUT;
500 postsize = (data->set.postfieldsize != -1)?
501 data->set.postfieldsize:
502 (data->set.postfields? (curl_off_t)strlen(data->set.postfields):0);
503 data->set.httpreq = HTTPREQ_POST;
506 if(putsize > 0 || postsize > 0) {
507 /* As stated in the http comments, it is probably not wise to
508 * actually set a custom Content-Length in the headers */
509 if(!Curl_checkheaders(data, "Content-Length:")) {
510 result = Curl_add_bufferf(req_buffer,
511 "Content-Length: %" FORMAT_OFF_T"\r\n",
512 (data->set.upload ? putsize : postsize));
517 if(rtspreq == RTSPREQ_SET_PARAMETER ||
518 rtspreq == RTSPREQ_GET_PARAMETER) {
519 if(!Curl_checkheaders(data, "Content-Type:")) {
520 result = Curl_add_bufferf(req_buffer,
521 "Content-Type: text/parameters\r\n");
527 if(rtspreq == RTSPREQ_ANNOUNCE) {
528 if(!Curl_checkheaders(data, "Content-Type:")) {
529 result = Curl_add_bufferf(req_buffer,
530 "Content-Type: application/sdp\r\n");
536 data->state.expect100header = FALSE; /* RTSP posts are simple/small */
538 else if(rtspreq == RTSPREQ_GET_PARAMETER) {
539 /* Check for an empty GET_PARAMETER (heartbeat) request */
540 data->set.httpreq = HTTPREQ_HEAD;
541 data->set.opt_no_body = TRUE;
545 /* RTSP never allows chunked transfer */
546 data->req.forbidchunk = TRUE;
547 /* Finish the request buffer */
548 result = Curl_add_buffer(req_buffer, "\r\n", 2);
553 result = Curl_add_buffer(req_buffer, data->set.postfields,
559 /* issue the request */
560 result = Curl_add_buffer_send(req_buffer, conn,
561 &data->info.request_size, 0, FIRSTSOCKET);
563 failf(data, "Failed sending RTSP request");
567 Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE, &http->readbytecount,
568 putsize?FIRSTSOCKET:-1,
569 putsize?&http->writebytecount:NULL);
571 /* Increment the CSeq on success */
572 data->state.rtsp_next_client_CSeq++;
574 if(http->writebytecount) {
575 /* if a request-body has been sent off, we make sure this progress is
577 Curl_pgrsSetUploadCounter(data, http->writebytecount);
578 if(Curl_pgrsUpdate(conn))
579 result = CURLE_ABORTED_BY_CALLBACK;
586 static CURLcode rtsp_rtp_readwrite(struct SessionHandle *data,
587 struct connectdata *conn,
590 struct SingleRequest *k = &data->req;
591 struct rtsp_conn *rtspc = &(conn->proto.rtspc);
593 char *rtp; /* moving pointer to rtp data */
594 ssize_t rtp_dataleft; /* how much data left to parse in this round */
599 /* There was some leftover data the last time. Merge buffers */
600 char *newptr = realloc(rtspc->rtp_buf, rtspc->rtp_bufsize + *nread);
602 Curl_safefree(rtspc->rtp_buf);
603 rtspc->rtp_buf = NULL;
604 rtspc->rtp_bufsize = 0;
605 return CURLE_OUT_OF_MEMORY;
607 rtspc->rtp_buf = newptr;
608 memcpy(rtspc->rtp_buf + rtspc->rtp_bufsize, k->str, *nread);
609 rtspc->rtp_bufsize += *nread;
610 rtp = rtspc->rtp_buf;
611 rtp_dataleft = rtspc->rtp_bufsize;
614 /* Just parse the request buffer directly */
616 rtp_dataleft = *nread;
619 while((rtp_dataleft > 0) &&
621 if(rtp_dataleft > 4) {
624 /* Parse the header */
625 /* The channel identifier immediately follows and is 1 byte */
626 rtspc->rtp_channel = RTP_PKT_CHANNEL(rtp);
628 /* The length is two bytes */
629 rtp_length = RTP_PKT_LENGTH(rtp);
631 if(rtp_dataleft < rtp_length + 4) {
632 /* Need more - incomplete payload*/
637 /* We have the full RTP interleaved packet
638 * Write out the header including the leading '$' */
639 DEBUGF(infof(data, "RTP write channel %d rtp_length %d\n",
640 rtspc->rtp_channel, rtp_length));
641 result = rtp_client_write(conn, &rtp[0], rtp_length + 4);
643 failf(data, "Got an error writing an RTP packet");
645 Curl_safefree(rtspc->rtp_buf);
646 rtspc->rtp_buf = NULL;
647 rtspc->rtp_bufsize = 0;
651 /* Move forward in the buffer */
652 rtp_dataleft -= rtp_length + 4;
653 rtp += rtp_length + 4;
655 if(data->set.rtspreq == RTSPREQ_RECEIVE) {
656 /* If we are in a passive receive, give control back
657 * to the app as often as we can.
659 k->keepon &= ~KEEP_RECV;
664 /* Need more - incomplete header */
670 if(rtp_dataleft != 0 && rtp[0] == '$') {
671 DEBUGF(infof(data, "RTP Rewinding %zu %s\n", rtp_dataleft,
672 *readmore ? "(READMORE)" : ""));
674 /* Store the incomplete RTP packet for a "rewind" */
675 scratch = malloc(rtp_dataleft);
677 Curl_safefree(rtspc->rtp_buf);
678 rtspc->rtp_buf = NULL;
679 rtspc->rtp_bufsize = 0;
680 return CURLE_OUT_OF_MEMORY;
682 memcpy(scratch, rtp, rtp_dataleft);
683 Curl_safefree(rtspc->rtp_buf);
684 rtspc->rtp_buf = scratch;
685 rtspc->rtp_bufsize = rtp_dataleft;
687 /* As far as the transfer is concerned, this data is consumed */
692 /* Fix up k->str to point just after the last RTP packet */
693 k->str += *nread - rtp_dataleft;
695 /* either all of the data has been read or...
696 * rtp now points at the next byte to parse
699 DEBUGASSERT(k->str[0] == rtp[0]);
701 DEBUGASSERT(rtp_dataleft <= *nread); /* sanity check */
703 *nread = rtp_dataleft;
706 /* If we get here, we have finished with the leftover/merge buffer */
707 Curl_safefree(rtspc->rtp_buf);
708 rtspc->rtp_buf = NULL;
709 rtspc->rtp_bufsize = 0;
715 CURLcode rtp_client_write(struct connectdata *conn, char *ptr, size_t len)
717 struct SessionHandle *data = conn->data;
719 curl_write_callback writeit;
722 failf (data, "Cannot write a 0 size RTP packet.");
723 return CURLE_WRITE_ERROR;
726 writeit = data->set.fwrite_rtp?data->set.fwrite_rtp:data->set.fwrite_func;
727 wrote = writeit(ptr, 1, len, data->set.rtp_out);
729 if(CURL_WRITEFUNC_PAUSE == wrote) {
730 failf (data, "Cannot pause RTP");
731 return CURLE_WRITE_ERROR;
735 failf (data, "Failed writing RTP data");
736 return CURLE_WRITE_ERROR;
742 CURLcode Curl_rtsp_parseheader(struct connectdata *conn,
745 struct SessionHandle *data = conn->data;
748 if(checkprefix("CSeq:", header)) {
749 /* Store the received CSeq. Match is verified in rtsp_done */
750 int nc = sscanf(&header[4], ": %ld", &CSeq);
752 data->state.proto.rtsp->CSeq_recv = CSeq; /* mark the request */
753 data->state.rtsp_CSeq_recv = CSeq; /* update the handle */
756 failf(data, "Unable to read the CSeq header: [%s]", header);
757 return CURLE_RTSP_CSEQ_ERROR;
760 else if(checkprefix("Session:", header)) {
763 /* Find the first non-space letter */
765 while(*start && ISSPACE(*start))
769 failf(data, "Got a blank Session ID");
771 else if(data->set.str[STRING_RTSP_SESSION_ID]) {
772 /* If the Session ID is set, then compare */
773 if(strncmp(start, data->set.str[STRING_RTSP_SESSION_ID],
774 strlen(data->set.str[STRING_RTSP_SESSION_ID])) != 0) {
775 failf(data, "Got RTSP Session ID Line [%s], but wanted ID [%s]",
776 start, data->set.str[STRING_RTSP_SESSION_ID]);
777 return CURLE_RTSP_SESSION_ERROR;
781 /* If the Session ID is not set, and we find it in a response, then
784 /* The session ID can be an alphanumeric or a 'safe' character
786 * RFC 2326 15.1 Base Syntax:
787 * safe = "\$" | "-" | "_" | "." | "+"
791 (ISALNUM(*end) || *end == '-' || *end == '_' || *end == '.' ||
793 (*end == '\\' && *(end + 1) && *(end + 1) == '$' && (++end, 1))))
796 /* Copy the id substring into a new buffer */
797 data->set.str[STRING_RTSP_SESSION_ID] = malloc(end - start + 1);
798 if(data->set.str[STRING_RTSP_SESSION_ID] == NULL)
799 return CURLE_OUT_OF_MEMORY;
800 memcpy(data->set.str[STRING_RTSP_SESSION_ID], start, end - start);
801 (data->set.str[STRING_RTSP_SESSION_ID])[end - start] = '\0';
807 #endif /* CURL_DISABLE_RTSP */