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