c30afd39d3d48050149d201c5e7fcd891f546fc8
[platform/upstream/curl.git] / lib / rtsp.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2015, Daniel Stenberg, <daniel@haxx.se>, et al.
9  *
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.
13  *
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.
17  *
18  * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
19  * KIND, either express or implied.
20  *
21  ***************************************************************************/
22
23 #include "curl_setup.h"
24
25 #ifndef CURL_DISABLE_RTSP
26
27 #include "urldata.h"
28 #include <curl/curl.h>
29 #include "transfer.h"
30 #include "sendf.h"
31 #include "multiif.h"
32 #include "http.h"
33 #include "url.h"
34 #include "progress.h"
35 #include "rtsp.h"
36 #include "rawstr.h"
37 #include "select.h"
38 #include "connect.h"
39 #include "curl_printf.h"
40
41 /* The last #include files should be: */
42 #include "curl_memory.h"
43 #include "memdebug.h"
44
45 /*
46  * TODO (general)
47  *  -incoming server requests
48  *      -server CSeq counter
49  *  -digest authentication
50  *  -connect thru proxy
51  *  -pipelining?
52  */
53
54
55 #define RTP_PKT_CHANNEL(p)   ((int)((unsigned char)((p)[1])))
56
57 #define RTP_PKT_LENGTH(p)  ((((int)((unsigned char)((p)[2]))) << 8) | \
58                              ((int)((unsigned char)((p)[3]))))
59
60 /* protocol-specific functions set up to be called by the main engine */
61 static CURLcode rtsp_do(struct connectdata *conn, bool *done);
62 static CURLcode rtsp_done(struct connectdata *conn, CURLcode, bool premature);
63 static CURLcode rtsp_connect(struct connectdata *conn, bool *done);
64 static CURLcode rtsp_disconnect(struct connectdata *conn, bool dead);
65
66 static int rtsp_getsock_do(struct connectdata *conn,
67                            curl_socket_t *socks,
68                            int numsocks);
69
70 /*
71  * Parse and write out any available RTP data.
72  *
73  * nread: amount of data left after k->str. will be modified if RTP
74  *        data is parsed and k->str is moved up
75  * readmore: whether or not the RTP parser needs more data right away
76  */
77 static CURLcode rtsp_rtp_readwrite(struct SessionHandle *data,
78                                    struct connectdata *conn,
79                                    ssize_t *nread,
80                                    bool *readmore);
81
82 static CURLcode rtsp_setup_connection(struct connectdata *conn);
83
84
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,
89                            curl_socket_t *socks,
90                            int numsocks)
91 {
92   /* write mode */
93   (void)numsocks; /* unused, we trust it to be at least 1 */
94   socks[0] = conn->sock[FIRSTSOCKET];
95   return GETSOCK_WRITESOCK(0);
96 }
97
98 static
99 CURLcode rtp_client_write(struct connectdata *conn, char *ptr, size_t len);
100
101
102 /*
103  * RTSP handler interface.
104  */
105 const struct Curl_handler Curl_handler_rtsp = {
106   "RTSP",                               /* scheme */
107   rtsp_setup_connection,                /* setup_connection */
108   rtsp_do,                              /* do_it */
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 */
123 };
124
125
126 static CURLcode rtsp_setup_connection(struct connectdata *conn)
127 {
128   struct RTSP *rtsp;
129
130   conn->data->req.protop = rtsp = calloc(1, sizeof(struct RTSP));
131   if(!rtsp)
132     return CURLE_OUT_OF_MEMORY;
133
134   return CURLE_OK;
135 }
136
137
138 /*
139  * The server may send us RTP data at any point, and RTSPREQ_RECEIVE does not
140  * want to block the application forever while receiving a stream. Therefore,
141  * we cannot assume that an RTSP socket is dead just because it is readable.
142  *
143  * Instead, if it is readable, run Curl_getconnectinfo() to peek at the socket
144  * and distinguish between closed and data.
145  */
146 bool Curl_rtsp_connisdead(struct connectdata *check)
147 {
148   int sval;
149   bool ret_val = TRUE;
150
151   sval = Curl_socket_ready(check->sock[FIRSTSOCKET], CURL_SOCKET_BAD, 0);
152   if(sval == 0) {
153     /* timeout */
154     ret_val = FALSE;
155   }
156   else if(sval & CURL_CSELECT_ERR) {
157     /* socket is in an error state */
158     ret_val = TRUE;
159   }
160   else if((sval & CURL_CSELECT_IN) && check->data) {
161     /* readable with no error. could be closed or could be alive but we can
162        only check if we have a proper SessionHandle for the connection */
163     curl_socket_t connectinfo = Curl_getconnectinfo(check->data, &check);
164     if(connectinfo != CURL_SOCKET_BAD)
165       ret_val = FALSE;
166   }
167
168   return ret_val;
169 }
170
171 static CURLcode rtsp_connect(struct connectdata *conn, bool *done)
172 {
173   CURLcode httpStatus;
174   struct SessionHandle *data = conn->data;
175
176   httpStatus = Curl_http_connect(conn, done);
177
178   /* Initialize the CSeq if not already done */
179   if(data->state.rtsp_next_client_CSeq == 0)
180     data->state.rtsp_next_client_CSeq = 1;
181   if(data->state.rtsp_next_server_CSeq == 0)
182     data->state.rtsp_next_server_CSeq = 1;
183
184   conn->proto.rtspc.rtp_channel = -1;
185
186   return httpStatus;
187 }
188
189 static CURLcode rtsp_disconnect(struct connectdata *conn, bool dead)
190 {
191   (void) dead;
192   Curl_safefree(conn->proto.rtspc.rtp_buf);
193   return CURLE_OK;
194 }
195
196
197 static CURLcode rtsp_done(struct connectdata *conn,
198                           CURLcode status, bool premature)
199 {
200   struct SessionHandle *data = conn->data;
201   struct RTSP *rtsp = data->req.protop;
202   CURLcode httpStatus;
203   long CSeq_sent;
204   long CSeq_recv;
205
206   /* Bypass HTTP empty-reply checks on receive */
207   if(data->set.rtspreq == RTSPREQ_RECEIVE)
208     premature = TRUE;
209
210   httpStatus = Curl_http_done(conn, status, premature);
211
212   if(rtsp) {
213     /* Check the sequence numbers */
214     CSeq_sent = rtsp->CSeq_sent;
215     CSeq_recv = rtsp->CSeq_recv;
216     if((data->set.rtspreq != RTSPREQ_RECEIVE) && (CSeq_sent != CSeq_recv)) {
217       failf(data,
218             "The CSeq of this request %ld did not match the response %ld",
219             CSeq_sent, CSeq_recv);
220       return CURLE_RTSP_CSEQ_ERROR;
221     }
222     else if(data->set.rtspreq == RTSPREQ_RECEIVE &&
223             (conn->proto.rtspc.rtp_channel == -1)) {
224       infof(data, "Got an RTP Receive with a CSeq of %ld\n", CSeq_recv);
225       /* TODO CPC: Server -> Client logic here */
226     }
227   }
228
229   return httpStatus;
230 }
231
232 static CURLcode rtsp_do(struct connectdata *conn, bool *done)
233 {
234   struct SessionHandle *data = conn->data;
235   CURLcode result=CURLE_OK;
236   Curl_RtspReq rtspreq = data->set.rtspreq;
237   struct RTSP *rtsp = data->req.protop;
238   struct HTTP *http;
239   Curl_send_buffer *req_buffer;
240   curl_off_t postsize = 0; /* for ANNOUNCE and SET_PARAMETER */
241   curl_off_t putsize = 0; /* for ANNOUNCE and SET_PARAMETER */
242
243   const char *p_request = NULL;
244   const char *p_session_id = NULL;
245   const char *p_accept = NULL;
246   const char *p_accept_encoding = NULL;
247   const char *p_range = NULL;
248   const char *p_referrer = NULL;
249   const char *p_stream_uri = NULL;
250   const char *p_transport = NULL;
251   const char *p_uagent = NULL;
252
253   *done = TRUE;
254
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);
258
259   rtsp->CSeq_sent = data->state.rtsp_next_client_CSeq;
260   rtsp->CSeq_recv = 0;
261
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.
265    **/
266   data->set.opt_no_body = TRUE; /* most requests don't contain a body */
267   switch(rtspreq) {
268   default:
269     failf(data, "Got invalid RTSP request");
270     return CURLE_BAD_FUNCTION_ARGUMENT;
271   case RTSPREQ_OPTIONS:
272     p_request = "OPTIONS";
273     break;
274   case RTSPREQ_DESCRIBE:
275     p_request = "DESCRIBE";
276     data->set.opt_no_body = FALSE;
277     break;
278   case RTSPREQ_ANNOUNCE:
279     p_request = "ANNOUNCE";
280     break;
281   case RTSPREQ_SETUP:
282     p_request = "SETUP";
283     break;
284   case RTSPREQ_PLAY:
285     p_request = "PLAY";
286     break;
287   case RTSPREQ_PAUSE:
288     p_request = "PAUSE";
289     break;
290   case RTSPREQ_TEARDOWN:
291     p_request = "TEARDOWN";
292     break;
293   case RTSPREQ_GET_PARAMETER:
294     /* GET_PARAMETER's no_body status is determined later */
295     p_request = "GET_PARAMETER";
296     data->set.opt_no_body = FALSE;
297     break;
298   case RTSPREQ_SET_PARAMETER:
299     p_request = "SET_PARAMETER";
300     break;
301   case RTSPREQ_RECORD:
302     p_request = "RECORD";
303     break;
304   case RTSPREQ_RECEIVE:
305     p_request = "";
306     /* Treat interleaved RTP as body*/
307     data->set.opt_no_body = FALSE;
308     break;
309   case RTSPREQ_LAST:
310     failf(data, "Got invalid RTSP request: RTSPREQ_LAST");
311     return CURLE_BAD_FUNCTION_ARGUMENT;
312   }
313
314   if(rtspreq == RTSPREQ_RECEIVE) {
315     Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE,
316                         &http->readbytecount, -1, NULL);
317
318     return result;
319   }
320
321   p_session_id = data->set.str[STRING_RTSP_SESSION_ID];
322   if(!p_session_id &&
323      (rtspreq & ~(RTSPREQ_OPTIONS | RTSPREQ_DESCRIBE | RTSPREQ_SETUP))) {
324     failf(data, "Refusing to issue an RTSP request [%s] without a session ID.",
325           p_request);
326     return CURLE_BAD_FUNCTION_ARGUMENT;
327   }
328
329   /* TODO: auth? */
330   /* TODO: proxy? */
331
332   /* Stream URI. Default to server '*' if not specified */
333   if(data->set.str[STRING_RTSP_STREAM_URI]) {
334     p_stream_uri = data->set.str[STRING_RTSP_STREAM_URI];
335   }
336   else {
337     p_stream_uri = "*";
338   }
339
340   /* Transport Header for SETUP requests */
341   p_transport = Curl_checkheaders(conn, "Transport:");
342   if(rtspreq == RTSPREQ_SETUP && !p_transport) {
343     /* New Transport: setting? */
344     if(data->set.str[STRING_RTSP_TRANSPORT]) {
345       Curl_safefree(conn->allocptr.rtsp_transport);
346
347       conn->allocptr.rtsp_transport =
348         aprintf("Transport: %s\r\n",
349                 data->set.str[STRING_RTSP_TRANSPORT]);
350       if(!conn->allocptr.rtsp_transport)
351         return CURLE_OUT_OF_MEMORY;
352     }
353     else {
354       failf(data,
355             "Refusing to issue an RTSP SETUP without a Transport: header.");
356       return CURLE_BAD_FUNCTION_ARGUMENT;
357     }
358
359     p_transport = conn->allocptr.rtsp_transport;
360   }
361
362   /* Accept Headers for DESCRIBE requests */
363   if(rtspreq == RTSPREQ_DESCRIBE) {
364     /* Accept Header */
365     p_accept = Curl_checkheaders(conn, "Accept:")?
366       NULL:"Accept: application/sdp\r\n";
367
368     /* Accept-Encoding header */
369     if(!Curl_checkheaders(conn, "Accept-Encoding:") &&
370        data->set.str[STRING_ENCODING]) {
371       Curl_safefree(conn->allocptr.accept_encoding);
372       conn->allocptr.accept_encoding =
373         aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]);
374
375       if(!conn->allocptr.accept_encoding)
376         return CURLE_OUT_OF_MEMORY;
377
378       p_accept_encoding = conn->allocptr.accept_encoding;
379     }
380   }
381
382   /* The User-Agent string might have been allocated in url.c already, because
383      it might have been used in the proxy connect, but if we have got a header
384      with the user-agent string specified, we erase the previously made string
385      here. */
386   if(Curl_checkheaders(conn, "User-Agent:") && conn->allocptr.uagent) {
387     Curl_safefree(conn->allocptr.uagent);
388     conn->allocptr.uagent = NULL;
389   }
390   else if(!Curl_checkheaders(conn, "User-Agent:") &&
391           data->set.str[STRING_USERAGENT]) {
392     p_uagent = conn->allocptr.uagent;
393   }
394
395   /* Referrer */
396   Curl_safefree(conn->allocptr.ref);
397   if(data->change.referer && !Curl_checkheaders(conn, "Referer:"))
398     conn->allocptr.ref = aprintf("Referer: %s\r\n", data->change.referer);
399   else
400     conn->allocptr.ref = NULL;
401
402   p_referrer = conn->allocptr.ref;
403
404   /*
405    * Range Header
406    * Only applies to PLAY, PAUSE, RECORD
407    *
408    * Go ahead and use the Range stuff supplied for HTTP
409    */
410   if(data->state.use_range &&
411      (rtspreq  & (RTSPREQ_PLAY | RTSPREQ_PAUSE | RTSPREQ_RECORD))) {
412
413     /* Check to see if there is a range set in the custom headers */
414     if(!Curl_checkheaders(conn, "Range:") && data->state.range) {
415       Curl_safefree(conn->allocptr.rangeline);
416       conn->allocptr.rangeline = aprintf("Range: %s\r\n", data->state.range);
417       p_range = conn->allocptr.rangeline;
418     }
419   }
420
421   /*
422    * Sanity check the custom headers
423    */
424   if(Curl_checkheaders(conn, "CSeq:")) {
425     failf(data, "CSeq cannot be set as a custom header.");
426     return CURLE_RTSP_CSEQ_ERROR;
427   }
428   if(Curl_checkheaders(conn, "Session:")) {
429     failf(data, "Session ID cannot be set as a custom header.");
430     return CURLE_BAD_FUNCTION_ARGUMENT;
431   }
432
433   /* Initialize a dynamic send buffer */
434   req_buffer = Curl_add_buffer_init();
435
436   if(!req_buffer)
437     return CURLE_OUT_OF_MEMORY;
438
439   result =
440     Curl_add_bufferf(req_buffer,
441                      "%s %s RTSP/1.0\r\n" /* Request Stream-URI RTSP/1.0 */
442                      "CSeq: %ld\r\n", /* CSeq */
443                      p_request, p_stream_uri, rtsp->CSeq_sent);
444   if(result)
445     return result;
446
447   /*
448    * Rather than do a normal alloc line, keep the session_id unformatted
449    * to make comparison easier
450    */
451   if(p_session_id) {
452     result = Curl_add_bufferf(req_buffer, "Session: %s\r\n", p_session_id);
453     if(result)
454       return result;
455   }
456
457   /*
458    * Shared HTTP-like options
459    */
460   result = Curl_add_bufferf(req_buffer,
461                             "%s" /* transport */
462                             "%s" /* accept */
463                             "%s" /* accept-encoding */
464                             "%s" /* range */
465                             "%s" /* referrer */
466                             "%s" /* user-agent */
467                             ,
468                             p_transport ? p_transport : "",
469                             p_accept ? p_accept : "",
470                             p_accept_encoding ? p_accept_encoding : "",
471                             p_range ? p_range : "",
472                             p_referrer ? p_referrer : "",
473                             p_uagent ? p_uagent : "");
474   if(result)
475     return result;
476
477   if((rtspreq == RTSPREQ_SETUP) || (rtspreq == RTSPREQ_DESCRIBE)) {
478     result = Curl_add_timecondition(data, req_buffer);
479     if(result)
480       return result;
481   }
482
483   result = Curl_add_custom_headers(conn, FALSE, req_buffer);
484   if(result)
485     return result;
486
487   if(rtspreq == RTSPREQ_ANNOUNCE ||
488      rtspreq == RTSPREQ_SET_PARAMETER ||
489      rtspreq == RTSPREQ_GET_PARAMETER) {
490
491     if(data->set.upload) {
492       putsize = data->state.infilesize;
493       data->set.httpreq = HTTPREQ_PUT;
494
495     }
496     else {
497       postsize = (data->state.infilesize != -1)?
498         data->state.infilesize:
499         (data->set.postfields? (curl_off_t)strlen(data->set.postfields):0);
500       data->set.httpreq = HTTPREQ_POST;
501     }
502
503     if(putsize > 0 || postsize > 0) {
504       /* As stated in the http comments, it is probably not wise to
505        * actually set a custom Content-Length in the headers */
506       if(!Curl_checkheaders(conn, "Content-Length:")) {
507         result = Curl_add_bufferf(req_buffer,
508             "Content-Length: %" CURL_FORMAT_CURL_OFF_T"\r\n",
509             (data->set.upload ? putsize : postsize));
510         if(result)
511           return result;
512       }
513
514       if(rtspreq == RTSPREQ_SET_PARAMETER ||
515          rtspreq == RTSPREQ_GET_PARAMETER) {
516         if(!Curl_checkheaders(conn, "Content-Type:")) {
517           result = Curl_add_bufferf(req_buffer,
518               "Content-Type: text/parameters\r\n");
519           if(result)
520             return result;
521         }
522       }
523
524       if(rtspreq == RTSPREQ_ANNOUNCE) {
525         if(!Curl_checkheaders(conn, "Content-Type:")) {
526           result = Curl_add_bufferf(req_buffer,
527               "Content-Type: application/sdp\r\n");
528           if(result)
529             return result;
530         }
531       }
532
533       data->state.expect100header = FALSE; /* RTSP posts are simple/small */
534     }
535     else if(rtspreq == RTSPREQ_GET_PARAMETER) {
536       /* Check for an empty GET_PARAMETER (heartbeat) request */
537       data->set.httpreq = HTTPREQ_HEAD;
538       data->set.opt_no_body = TRUE;
539     }
540   }
541
542   /* RTSP never allows chunked transfer */
543   data->req.forbidchunk = TRUE;
544   /* Finish the request buffer */
545   result = Curl_add_buffer(req_buffer, "\r\n", 2);
546   if(result)
547     return result;
548
549   if(postsize > 0) {
550     result = Curl_add_buffer(req_buffer, data->set.postfields,
551                              (size_t)postsize);
552     if(result)
553       return result;
554   }
555
556   /* issue the request */
557   result = Curl_add_buffer_send(req_buffer, conn,
558                                 &data->info.request_size, 0, FIRSTSOCKET);
559   if(result) {
560     failf(data, "Failed sending RTSP request");
561     return result;
562   }
563
564   Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE, &http->readbytecount,
565                       putsize?FIRSTSOCKET:-1,
566                       putsize?&http->writebytecount:NULL);
567
568   /* Increment the CSeq on success */
569   data->state.rtsp_next_client_CSeq++;
570
571   if(http->writebytecount) {
572     /* if a request-body has been sent off, we make sure this progress is
573        noted properly */
574     Curl_pgrsSetUploadCounter(data, http->writebytecount);
575     if(Curl_pgrsUpdate(conn))
576       result = CURLE_ABORTED_BY_CALLBACK;
577   }
578
579   return result;
580 }
581
582
583 static CURLcode rtsp_rtp_readwrite(struct SessionHandle *data,
584                                    struct connectdata *conn,
585                                    ssize_t *nread,
586                                    bool *readmore) {
587   struct SingleRequest *k = &data->req;
588   struct rtsp_conn *rtspc = &(conn->proto.rtspc);
589
590   char *rtp; /* moving pointer to rtp data */
591   ssize_t rtp_dataleft; /* how much data left to parse in this round */
592   char *scratch;
593   CURLcode result;
594
595   if(rtspc->rtp_buf) {
596     /* There was some leftover data the last time. Merge buffers */
597     char *newptr = realloc(rtspc->rtp_buf, rtspc->rtp_bufsize + *nread);
598     if(!newptr) {
599       Curl_safefree(rtspc->rtp_buf);
600       rtspc->rtp_buf = NULL;
601       rtspc->rtp_bufsize = 0;
602       return CURLE_OUT_OF_MEMORY;
603     }
604     rtspc->rtp_buf = newptr;
605     memcpy(rtspc->rtp_buf + rtspc->rtp_bufsize, k->str, *nread);
606     rtspc->rtp_bufsize += *nread;
607     rtp = rtspc->rtp_buf;
608     rtp_dataleft = rtspc->rtp_bufsize;
609   }
610   else {
611     /* Just parse the request buffer directly */
612     rtp = k->str;
613     rtp_dataleft = *nread;
614   }
615
616   while((rtp_dataleft > 0) &&
617         (rtp[0] == '$')) {
618     if(rtp_dataleft > 4) {
619       int rtp_length;
620
621       /* Parse the header */
622       /* The channel identifier immediately follows and is 1 byte */
623       rtspc->rtp_channel = RTP_PKT_CHANNEL(rtp);
624
625       /* The length is two bytes */
626       rtp_length = RTP_PKT_LENGTH(rtp);
627
628       if(rtp_dataleft < rtp_length + 4) {
629         /* Need more - incomplete payload*/
630         *readmore = TRUE;
631         break;
632       }
633       else {
634         /* We have the full RTP interleaved packet
635          * Write out the header including the leading '$' */
636         DEBUGF(infof(data, "RTP write channel %d rtp_length %d\n",
637               rtspc->rtp_channel, rtp_length));
638         result = rtp_client_write(conn, &rtp[0], rtp_length + 4);
639         if(result) {
640           failf(data, "Got an error writing an RTP packet");
641           *readmore = FALSE;
642           Curl_safefree(rtspc->rtp_buf);
643           rtspc->rtp_buf = NULL;
644           rtspc->rtp_bufsize = 0;
645           return result;
646         }
647
648         /* Move forward in the buffer */
649         rtp_dataleft -= rtp_length + 4;
650         rtp += rtp_length + 4;
651
652         if(data->set.rtspreq == RTSPREQ_RECEIVE) {
653           /* If we are in a passive receive, give control back
654            * to the app as often as we can.
655            */
656           k->keepon &= ~KEEP_RECV;
657         }
658       }
659     }
660     else {
661       /* Need more - incomplete header */
662       *readmore = TRUE;
663       break;
664     }
665   }
666
667   if(rtp_dataleft != 0 && rtp[0] == '$') {
668     DEBUGF(infof(data, "RTP Rewinding %zd %s\n", rtp_dataleft,
669           *readmore ? "(READMORE)" : ""));
670
671     /* Store the incomplete RTP packet for a "rewind" */
672     scratch = malloc(rtp_dataleft);
673     if(!scratch) {
674       Curl_safefree(rtspc->rtp_buf);
675       rtspc->rtp_buf = NULL;
676       rtspc->rtp_bufsize = 0;
677       return CURLE_OUT_OF_MEMORY;
678     }
679     memcpy(scratch, rtp, rtp_dataleft);
680     Curl_safefree(rtspc->rtp_buf);
681     rtspc->rtp_buf = scratch;
682     rtspc->rtp_bufsize = rtp_dataleft;
683
684     /* As far as the transfer is concerned, this data is consumed */
685     *nread = 0;
686     return CURLE_OK;
687   }
688   else {
689     /* Fix up k->str to point just after the last RTP packet */
690     k->str += *nread - rtp_dataleft;
691
692     /* either all of the data has been read or...
693      * rtp now points at the next byte to parse
694      */
695     if(rtp_dataleft > 0)
696       DEBUGASSERT(k->str[0] == rtp[0]);
697
698     DEBUGASSERT(rtp_dataleft <= *nread); /* sanity check */
699
700     *nread = rtp_dataleft;
701   }
702
703   /* If we get here, we have finished with the leftover/merge buffer */
704   Curl_safefree(rtspc->rtp_buf);
705   rtspc->rtp_buf = NULL;
706   rtspc->rtp_bufsize = 0;
707
708   return CURLE_OK;
709 }
710
711 static
712 CURLcode rtp_client_write(struct connectdata *conn, char *ptr, size_t len)
713 {
714   struct SessionHandle *data = conn->data;
715   size_t wrote;
716   curl_write_callback writeit;
717
718   if(len == 0) {
719     failf (data, "Cannot write a 0 size RTP packet.");
720     return CURLE_WRITE_ERROR;
721   }
722
723   writeit = data->set.fwrite_rtp?data->set.fwrite_rtp:data->set.fwrite_func;
724   wrote = writeit(ptr, 1, len, data->set.rtp_out);
725
726   if(CURL_WRITEFUNC_PAUSE == wrote) {
727     failf (data, "Cannot pause RTP");
728     return CURLE_WRITE_ERROR;
729   }
730
731   if(wrote != len) {
732     failf (data, "Failed writing RTP data");
733     return CURLE_WRITE_ERROR;
734   }
735
736   return CURLE_OK;
737 }
738
739 CURLcode Curl_rtsp_parseheader(struct connectdata *conn,
740                                char *header)
741 {
742   struct SessionHandle *data = conn->data;
743   long CSeq = 0;
744
745   if(checkprefix("CSeq:", header)) {
746     /* Store the received CSeq. Match is verified in rtsp_done */
747     int nc = sscanf(&header[4], ": %ld", &CSeq);
748     if(nc == 1) {
749       struct RTSP *rtsp = data->req.protop;
750       rtsp->CSeq_recv = CSeq; /* mark the request */
751       data->state.rtsp_CSeq_recv = CSeq; /* update the handle */
752     }
753     else {
754       failf(data, "Unable to read the CSeq header: [%s]", header);
755       return CURLE_RTSP_CSEQ_ERROR;
756     }
757   }
758   else if(checkprefix("Session:", header)) {
759     char *start;
760
761     /* Find the first non-space letter */
762     start = header + 8;
763     while(*start && ISSPACE(*start))
764       start++;
765
766     if(!*start) {
767       failf(data, "Got a blank Session ID");
768     }
769     else if(data->set.str[STRING_RTSP_SESSION_ID]) {
770       /* If the Session ID is set, then compare */
771       if(strncmp(start, data->set.str[STRING_RTSP_SESSION_ID],
772                  strlen(data->set.str[STRING_RTSP_SESSION_ID]))  != 0) {
773         failf(data, "Got RTSP Session ID Line [%s], but wanted ID [%s]",
774               start, data->set.str[STRING_RTSP_SESSION_ID]);
775         return CURLE_RTSP_SESSION_ERROR;
776       }
777     }
778     else {
779       /* If the Session ID is not set, and we find it in a response, then
780          set it */
781
782       /* The session ID can be an alphanumeric or a 'safe' character
783        *
784        * RFC 2326 15.1 Base Syntax:
785        * safe =  "\$" | "-" | "_" | "." | "+"
786        * */
787       char *end = start;
788       while(*end &&
789             (ISALNUM(*end) || *end == '-' || *end == '_' || *end == '.' ||
790              *end == '+' ||
791              (*end == '\\' && *(end + 1) && *(end + 1) == '$' && (++end, 1))))
792         end++;
793
794       /* Copy the id substring into a new buffer */
795       data->set.str[STRING_RTSP_SESSION_ID] = malloc(end - start + 1);
796       if(data->set.str[STRING_RTSP_SESSION_ID] == NULL)
797         return CURLE_OUT_OF_MEMORY;
798       memcpy(data->set.str[STRING_RTSP_SESSION_ID], start, end - start);
799       (data->set.str[STRING_RTSP_SESSION_ID])[end - start] = '\0';
800     }
801   }
802   return CURLE_OK;
803 }
804
805 #endif /* CURL_DISABLE_RTSP */