RTSP: cleanups
[platform/upstream/curl.git] / lib / rtsp.c
1 /***************************************************************************
2  *                                  _   _ ____  _
3  *  Project                     ___| | | |  _ \| |
4  *                             / __| | | | |_) | |
5  *                            | (__| |_| |  _ <| |___
6  *                             \___|\___/|_| \_\_____|
7  *
8  * Copyright (C) 1998 - 2011, 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 "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 "curl_memory.h"
38 #include "select.h"
39 #include "connect.h"
40
41 #define _MPRINTF_REPLACE /* use our functions only */
42 #include <curl/mprintf.h>
43
44 /* The last #include file should be: */
45 #include "memdebug.h"
46
47 /*
48  * TODO (general)
49  *  -incoming server requests
50  *      -server CSeq counter
51  *  -digest authentication
52  *  -connect thru proxy
53  *  -pipelining?
54  */
55
56
57 #define RTP_PKT_CHANNEL(p)   ((int)((unsigned char)((p)[1])))
58
59 #define RTP_PKT_LENGTH(p)  ((((int)((unsigned char)((p)[2]))) << 8) | \
60                              ((int)((unsigned char)((p)[3]))))
61
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);
67
68 static int rtsp_getsock_do(struct connectdata *conn,
69                            curl_socket_t *socks,
70                            int numsocks);
71
72 /*
73  * Parse and write out any available RTP data.
74  *
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
78  */
79 static CURLcode rtsp_rtp_readwrite(struct SessionHandle *data,
80                                    struct connectdata *conn,
81                                    ssize_t *nread,
82                                    bool *readmore);
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   ZERO_NULL,                            /* 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,                            /* perform_getsock */
117   rtsp_disconnect,                      /* disconnect */
118   rtsp_rtp_readwrite,                   /* readwrite */
119   PORT_RTSP,                            /* defport */
120   CURLPROTO_RTSP,                       /* protocol */
121   PROTOPT_NONE                          /* flags */
122 };
123
124 /*
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.
128  *
129  * Instead, if it is readable, run Curl_getconnectinfo() to peek at the socket
130  * and distinguish between closed and data.
131  */
132 bool Curl_rtsp_connisdead(struct connectdata *check)
133 {
134   int sval;
135   bool ret_val = TRUE;
136
137   sval = Curl_socket_ready(check->sock[FIRSTSOCKET], CURL_SOCKET_BAD, 0);
138   if(sval == 0) {
139     /* timeout */
140     ret_val = FALSE;
141   }
142   else if(sval & CURL_CSELECT_ERR) {
143     /* socket is in an error state */
144     ret_val = TRUE;
145   }
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)
151       ret_val = FALSE;
152   }
153
154   return ret_val;
155 }
156
157 static CURLcode rtsp_connect(struct connectdata *conn, bool *done)
158 {
159   CURLcode httpStatus;
160   struct SessionHandle *data = conn->data;
161
162   httpStatus = Curl_http_connect(conn, done);
163
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;
169
170   conn->proto.rtspc.rtp_channel = -1;
171
172   return httpStatus;
173 }
174
175 static CURLcode rtsp_disconnect(struct connectdata *conn, bool dead)
176 {
177   (void) dead;
178   Curl_safefree(conn->proto.rtspc.rtp_buf);
179   return CURLE_OK;
180 }
181
182
183 static CURLcode rtsp_done(struct connectdata *conn,
184                           CURLcode status, bool premature)
185 {
186   struct SessionHandle *data = conn->data;
187   struct RTSP *rtsp = data->state.proto.rtsp;
188   CURLcode httpStatus;
189   long CSeq_sent;
190   long CSeq_recv;
191
192   /* Bypass HTTP empty-reply checks on receive */
193   if(data->set.rtspreq == RTSPREQ_RECEIVE)
194     premature = TRUE;
195
196   httpStatus = Curl_http_done(conn, status, premature);
197
198   if(rtsp) {
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)) {
203       failf(data,
204             "The CSeq of this request %ld did not match the response %ld",
205             CSeq_sent, CSeq_recv);
206       return CURLE_RTSP_CSEQ_ERROR;
207     }
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 */
212     }
213   }
214
215   return httpStatus;
216 }
217
218 static CURLcode rtsp_do(struct connectdata *conn, bool *done)
219 {
220   struct SessionHandle *data = conn->data;
221   CURLcode result=CURLE_OK;
222   Curl_RtspReq rtspreq = data->set.rtspreq;
223   struct RTSP *rtsp;
224   struct HTTP *http;
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 */
228
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;
238
239   *done = TRUE;
240
241   Curl_reset_reqproto(conn);
242
243   if(!data->state.proto.rtsp) {
244     /* Only allocate this struct if we don't already have it! */
245
246     rtsp = calloc(1, sizeof(struct RTSP));
247     if(!rtsp)
248       return CURLE_OUT_OF_MEMORY;
249     data->state.proto.rtsp = rtsp;
250   }
251   else {
252     rtsp = data->state.proto.rtsp;
253   }
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   DEBUGASSERT((rtspreq > RTSPREQ_NONE && rtspreq < RTSPREQ_LAST));
267   data->set.opt_no_body = TRUE; /* most requests don't contain a body */
268   switch(rtspreq) {
269   case RTSPREQ_NONE:
270     failf(data, "Got invalid RTSP request: RTSPREQ_NONE");
271     return CURLE_BAD_FUNCTION_ARGUMENT;
272   case RTSPREQ_OPTIONS:
273     p_request = "OPTIONS";
274     break;
275   case RTSPREQ_DESCRIBE:
276     p_request = "DESCRIBE";
277     data->set.opt_no_body = FALSE;
278     break;
279   case RTSPREQ_ANNOUNCE:
280     p_request = "ANNOUNCE";
281     break;
282   case RTSPREQ_SETUP:
283     p_request = "SETUP";
284     break;
285   case RTSPREQ_PLAY:
286     p_request = "PLAY";
287     break;
288   case RTSPREQ_PAUSE:
289     p_request = "PAUSE";
290     break;
291   case RTSPREQ_TEARDOWN:
292     p_request = "TEARDOWN";
293     break;
294   case RTSPREQ_GET_PARAMETER:
295     /* GET_PARAMETER's no_body status is determined later */
296     p_request = "GET_PARAMETER";
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 ? 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(data, "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(data, "Accept:")?
366       NULL:"Accept: application/sdp\r\n";
367
368     /* Accept-Encoding header */
369     if(!Curl_checkheaders(data, "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(data, "User-Agent:") && conn->allocptr.uagent) {
387     Curl_safefree(conn->allocptr.uagent);
388     conn->allocptr.uagent = NULL;
389   }
390   else if(!Curl_checkheaders(data, "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(data, "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(data, "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(data, "CSeq:")) {
425     failf(data, "CSeq cannot be set as a custom header.");
426     return CURLE_RTSP_CSEQ_ERROR;
427   }
428   if(Curl_checkheaders(data, "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_request : ""), p_stream_uri,
444                      rtsp->CSeq_sent);
445   if(result)
446     return result;
447
448   /*
449    * Rather than do a normal alloc line, keep the session_id unformatted
450    * to make comparison easier
451    */
452   if(p_session_id) {
453     result = Curl_add_bufferf(req_buffer, "Session: %s\r\n", p_session_id);
454     if(result)
455       return result;
456   }
457
458   /*
459    * Shared HTTP-like options
460    */
461   result = Curl_add_bufferf(req_buffer,
462                             "%s" /* transport */
463                             "%s" /* accept */
464                             "%s" /* accept-encoding */
465                             "%s" /* range */
466                             "%s" /* referrer */
467                             "%s" /* user-agent */
468                             ,
469                             p_transport ? p_transport : "",
470                             p_accept ? p_accept : "",
471                             p_accept_encoding ? p_accept_encoding : "",
472                             p_range ? p_range : "",
473                             p_referrer ? p_referrer : "",
474                             p_uagent ? p_uagent : "");
475   if(result)
476     return result;
477
478   if((rtspreq == RTSPREQ_SETUP) || (rtspreq == RTSPREQ_DESCRIBE)) {
479     result = Curl_add_timecondition(data, req_buffer);
480     if(result)
481       return result;
482   }
483
484   result = Curl_add_custom_headers(conn, req_buffer);
485   if(result)
486     return result;
487
488   if(rtspreq == RTSPREQ_ANNOUNCE ||
489      rtspreq == RTSPREQ_SET_PARAMETER ||
490      rtspreq == RTSPREQ_GET_PARAMETER) {
491
492     if(data->set.upload) {
493       putsize = data->set.infilesize;
494       data->set.httpreq = HTTPREQ_PUT;
495
496     }
497     else {
498       postsize = (data->set.postfieldsize != -1)?
499         data->set.postfieldsize:
500         (data->set.postfields? (curl_off_t)strlen(data->set.postfields):0);
501       data->set.httpreq = HTTPREQ_POST;
502     }
503
504     if(putsize > 0 || postsize > 0) {
505       /* As stated in the http comments, it is probably not wise to
506        * actually set a custom Content-Length in the headers */
507       if(!Curl_checkheaders(data, "Content-Length:")) {
508         result = Curl_add_bufferf(req_buffer,
509             "Content-Length: %" FORMAT_OFF_T"\r\n",
510             (data->set.upload ? putsize : postsize));
511         if(result)
512           return result;
513       }
514
515       if(rtspreq == RTSPREQ_SET_PARAMETER ||
516          rtspreq == RTSPREQ_GET_PARAMETER) {
517         if(!Curl_checkheaders(data, "Content-Type:")) {
518           result = Curl_add_bufferf(req_buffer,
519               "Content-Type: text/parameters\r\n");
520           if(result)
521             return result;
522         }
523       }
524
525       if(rtspreq == RTSPREQ_ANNOUNCE) {
526         if(!Curl_checkheaders(data, "Content-Type:")) {
527           result = Curl_add_bufferf(req_buffer,
528               "Content-Type: application/sdp\r\n");
529           if(result)
530             return result;
531         }
532       }
533
534       data->state.expect100header = FALSE; /* RTSP posts are simple/small */
535     }
536     else if(rtspreq == RTSPREQ_GET_PARAMETER) {
537       /* Check for an empty GET_PARAMETER (heartbeat) request */
538       data->set.httpreq = HTTPREQ_HEAD;
539       data->set.opt_no_body = TRUE;
540     }
541   }
542
543   /* RTSP never allows chunked transfer */
544   data->req.forbidchunk = TRUE;
545   /* Finish the request buffer */
546   result = Curl_add_buffer(req_buffer, "\r\n", 2);
547   if(result)
548     return result;
549
550   if(postsize > 0) {
551     result = Curl_add_buffer(req_buffer, data->set.postfields,
552                              (size_t)postsize);
553     if(result)
554       return result;
555   }
556
557   /* issue the request */
558   result = Curl_add_buffer_send(req_buffer, conn,
559                                 &data->info.request_size, 0, FIRSTSOCKET);
560   if(result) {
561     failf(data, "Failed sending RTSP request");
562     return result;
563   }
564
565   Curl_setup_transfer(conn, FIRSTSOCKET, -1, TRUE, &http->readbytecount,
566                       putsize?FIRSTSOCKET:-1,
567                       putsize?&http->writebytecount:NULL);
568
569   /* Increment the CSeq on success */
570   data->state.rtsp_next_client_CSeq++;
571
572   if(http->writebytecount) {
573     /* if a request-body has been sent off, we make sure this progress is
574        noted properly */
575     Curl_pgrsSetUploadCounter(data, http->writebytecount);
576     if(Curl_pgrsUpdate(conn))
577       result = CURLE_ABORTED_BY_CALLBACK;
578   }
579
580   return result;
581 }
582
583
584 static CURLcode rtsp_rtp_readwrite(struct SessionHandle *data,
585                                    struct connectdata *conn,
586                                    ssize_t *nread,
587                                    bool *readmore) {
588   struct SingleRequest *k = &data->req;
589   struct rtsp_conn *rtspc = &(conn->proto.rtspc);
590
591   char *rtp; /* moving pointer to rtp data */
592   ssize_t rtp_dataleft; /* how much data left to parse in this round */
593   char *scratch;
594   CURLcode result;
595
596   if(rtspc->rtp_buf) {
597     /* There was some leftover data the last time. Merge buffers */
598     char *newptr = realloc(rtspc->rtp_buf, rtspc->rtp_bufsize + *nread);
599     if(!newptr) {
600       Curl_safefree(rtspc->rtp_buf);
601       rtspc->rtp_buf = NULL;
602       rtspc->rtp_bufsize = 0;
603       return CURLE_OUT_OF_MEMORY;
604     }
605     rtspc->rtp_buf = newptr;
606     memcpy(rtspc->rtp_buf + rtspc->rtp_bufsize, k->str, *nread);
607     rtspc->rtp_bufsize += *nread;
608     rtp = rtspc->rtp_buf;
609     rtp_dataleft = rtspc->rtp_bufsize;
610   }
611   else {
612     /* Just parse the request buffer directly */
613     rtp = k->str;
614     rtp_dataleft = *nread;
615   }
616
617   while((rtp_dataleft > 0) &&
618         (rtp[0] == '$')) {
619     if(rtp_dataleft > 4) {
620       int rtp_length;
621
622       /* Parse the header */
623       /* The channel identifier immediately follows and is 1 byte */
624       rtspc->rtp_channel = RTP_PKT_CHANNEL(rtp);
625
626       /* The length is two bytes */
627       rtp_length = RTP_PKT_LENGTH(rtp);
628
629       if(rtp_dataleft < rtp_length + 4) {
630         /* Need more - incomplete payload*/
631         *readmore = TRUE;
632         break;
633       }
634       else {
635         /* We have the full RTP interleaved packet
636          * Write out the header including the leading '$' */
637         DEBUGF(infof(data, "RTP write channel %d rtp_length %d\n",
638               rtspc->rtp_channel, rtp_length));
639         result = rtp_client_write(conn, &rtp[0], rtp_length + 4);
640         if(result) {
641           failf(data, "Got an error writing an RTP packet");
642           *readmore = FALSE;
643           Curl_safefree(rtspc->rtp_buf);
644           rtspc->rtp_buf = NULL;
645           rtspc->rtp_bufsize = 0;
646           return result;
647         }
648
649         /* Move forward in the buffer */
650         rtp_dataleft -= rtp_length + 4;
651         rtp += rtp_length + 4;
652
653         if(data->set.rtspreq == RTSPREQ_RECEIVE) {
654           /* If we are in a passive receive, give control back
655            * to the app as often as we can.
656            */
657           k->keepon &= ~KEEP_RECV;
658         }
659       }
660     }
661     else {
662       /* Need more - incomplete header */
663       *readmore = TRUE;
664       break;
665     }
666   }
667
668   if(rtp_dataleft != 0 && rtp[0] == '$') {
669     DEBUGF(infof(data, "RTP Rewinding %zu %s\n", rtp_dataleft,
670           *readmore ? "(READMORE)" : ""));
671
672     /* Store the incomplete RTP packet for a "rewind" */
673     scratch = malloc(rtp_dataleft);
674     if(!scratch) {
675       Curl_safefree(rtspc->rtp_buf);
676       rtspc->rtp_buf = NULL;
677       rtspc->rtp_bufsize = 0;
678       return CURLE_OUT_OF_MEMORY;
679     }
680     memcpy(scratch, rtp, rtp_dataleft);
681     Curl_safefree(rtspc->rtp_buf);
682     rtspc->rtp_buf = scratch;
683     rtspc->rtp_bufsize = rtp_dataleft;
684
685     /* As far as the transfer is concerned, this data is consumed */
686     *nread = 0;
687     return CURLE_OK;
688   }
689   else {
690     /* Fix up k->str to point just after the last RTP packet */
691     k->str += *nread - rtp_dataleft;
692
693     /* either all of the data has been read or...
694      * rtp now points at the next byte to parse
695      */
696     if(rtp_dataleft > 0)
697       DEBUGASSERT(k->str[0] == rtp[0]);
698
699     DEBUGASSERT(rtp_dataleft <= *nread); /* sanity check */
700
701     *nread = rtp_dataleft;
702   }
703
704   /* If we get here, we have finished with the leftover/merge buffer */
705   Curl_safefree(rtspc->rtp_buf);
706   rtspc->rtp_buf = NULL;
707   rtspc->rtp_bufsize = 0;
708
709   return CURLE_OK;
710 }
711
712 static
713 CURLcode rtp_client_write(struct connectdata *conn, char *ptr, size_t len)
714 {
715   struct SessionHandle *data = conn->data;
716   size_t wrote;
717   curl_write_callback writeit;
718
719   if(len == 0) {
720     failf (data, "Cannot write a 0 size RTP packet.");
721     return CURLE_WRITE_ERROR;
722   }
723
724   writeit = data->set.fwrite_rtp?data->set.fwrite_rtp:data->set.fwrite_func;
725   wrote = writeit(ptr, 1, len, data->set.rtp_out);
726
727   if(CURL_WRITEFUNC_PAUSE == wrote) {
728     failf (data, "Cannot pause RTP");
729     return CURLE_WRITE_ERROR;
730   }
731
732   if(wrote != len) {
733     failf (data, "Failed writing RTP data");
734     return CURLE_WRITE_ERROR;
735   }
736
737   return CURLE_OK;
738 }
739
740 CURLcode Curl_rtsp_parseheader(struct connectdata *conn,
741                                char *header)
742 {
743   struct SessionHandle *data = conn->data;
744   long CSeq = 0;
745
746   if(checkprefix("CSeq:", header)) {
747     /* Store the received CSeq. Match is verified in rtsp_done */
748     int nc;
749     char *temp = strdup(header);
750     if(!temp)
751       return CURLE_OUT_OF_MEMORY;
752     Curl_strntoupper(temp, temp, sizeof(temp));
753     nc = sscanf(temp, "CSEQ: %ld", &CSeq);
754     free(temp);
755     if(nc == 1) {
756       data->state.proto.rtsp->CSeq_recv = CSeq; /* mark the request */
757       data->state.rtsp_CSeq_recv = CSeq; /* update the handle */
758     }
759     else {
760       failf(data, "Unable to read the CSeq header: [%s]", header);
761       return CURLE_RTSP_CSEQ_ERROR;
762     }
763   }
764   else if(checkprefix("Session:", header)) {
765     char *start;
766
767     /* Find the first non-space letter */
768     start = header + 9;
769     while(*start && ISSPACE(*start))
770       start++;
771
772     if(!*start) {
773       failf(data, "Got a blank Session ID");
774     }
775     else if(data->set.str[STRING_RTSP_SESSION_ID]) {
776       /* If the Session ID is set, then compare */
777       if(strncmp(start, data->set.str[STRING_RTSP_SESSION_ID],
778                  strlen(data->set.str[STRING_RTSP_SESSION_ID]))  != 0) {
779         failf(data, "Got RTSP Session ID Line [%s], but wanted ID [%s]",
780               start, data->set.str[STRING_RTSP_SESSION_ID]);
781         return CURLE_RTSP_SESSION_ERROR;
782       }
783     }
784     else {
785       /* If the Session ID is not set, and we find it in a response, then
786          set it */
787
788       /* The session ID can be an alphanumeric or a 'safe' character
789        *
790        * RFC 2326 15.1 Base Syntax:
791        * safe =  "\$" | "-" | "_" | "." | "+"
792        * */
793       char *end = start;
794       while(*end &&
795             (ISALNUM(*end) || *end == '-' || *end == '_' || *end == '.' ||
796              *end == '+' ||
797              (*end == '\\' && *(end + 1) && *(end + 1) == '$' && (++end, 1))))
798         end++;
799
800       /* Copy the id substring into a new buffer */
801       data->set.str[STRING_RTSP_SESSION_ID] = malloc(end - start + 1);
802       if(data->set.str[STRING_RTSP_SESSION_ID] == NULL)
803         return CURLE_OUT_OF_MEMORY;
804       memcpy(data->set.str[STRING_RTSP_SESSION_ID], start, end - start);
805       (data->set.str[STRING_RTSP_SESSION_ID])[end - start] = '\0';
806     }
807   }
808   return CURLE_OK;
809 }
810
811 #endif /* CURL_DISABLE_RTSP */