Coverage Report

Created: 2026-07-30 07:03

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/curl/lib/rtsp.c
Line
Count
Source
1
/***************************************************************************
2
 *                                  _   _ ____  _
3
 *  Project                     ___| | | |  _ \| |
4
 *                             / __| | | | |_) | |
5
 *                            | (__| |_| |  _ <| |___
6
 *                             \___|\___/|_| \_\_____|
7
 *
8
 * Copyright (C) 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
 * SPDX-License-Identifier: curl
22
 *
23
 ***************************************************************************/
24
#include "curl_setup.h"
25
#include "urldata.h"
26
#include "rtsp.h"
27
28
#ifndef CURL_DISABLE_RTSP
29
30
#include "transfer.h"
31
#include "sendf.h"
32
#include "curl_trc.h"
33
#include "multiif.h"
34
#include "http.h"
35
#include "url.h"
36
#include "progress.h"
37
#include "strcase.h"
38
#include "select.h"
39
#include "connect.h"
40
#include "cfilters.h"
41
#include "curlx/strdup.h"
42
#include "bufref.h"
43
#include "curlx/strparse.h"
44
45
/* meta key for storing protocol meta at easy handle */
46
0
#define CURL_META_RTSP_EASY   "meta:proto:rtsp:easy"
47
/* meta key for storing protocol meta at connection */
48
0
#define CURL_META_RTSP_CONN   "meta:proto:rtsp:conn"
49
50
typedef enum {
51
  RTP_PARSE_SKIP,
52
  RTP_PARSE_CHANNEL,
53
  RTP_PARSE_LEN,
54
  RTP_PARSE_DATA
55
} rtp_parse_st;
56
57
/* RTSP Connection data
58
 * Currently, only used for tracking incomplete RTP data reads */
59
struct rtsp_conn {
60
  struct dynbuf buf;
61
  int rtp_channel;
62
  size_t rtp_len;
63
  rtp_parse_st state;
64
  BIT(in_header);
65
};
66
67
/* RTSP transfer data */
68
struct RTSP {
69
  uint32_t CSeq_sent; /* CSeq of this request */
70
  uint32_t CSeq_recv; /* CSeq received */
71
};
72
73
0
#define RTP_PKT_LENGTH(p) ((((unsigned int)((unsigned char)((p)[2]))) << 8) | \
74
0
                            ((unsigned int)((unsigned char)((p)[3]))))
75
76
/* this returns the socket to wait for in the DO and DOING state for the multi
77
   interface and then we are always _sending_ a request and thus we wait for
78
   the single socket to become writable only */
79
static CURLcode rtsp_do_pollset(struct Curl_easy *data,
80
                                struct easy_pollset *ps)
81
0
{
82
  /* write mode */
83
0
  return Curl_pollset_add_out(data, ps, data->conn->sock[FIRSTSOCKET]);
84
0
}
85
86
0
#define MAX_RTP_BUFFERSIZE 1000000 /* arbitrary */
87
88
static void rtsp_easy_dtor(void *key, size_t klen, void *entry)
89
0
{
90
0
  struct RTSP *rtsp = entry;
91
0
  (void)key;
92
0
  (void)klen;
93
0
  curlx_free(rtsp);
94
0
}
95
96
static void rtsp_conn_dtor(void *key, size_t klen, void *entry)
97
0
{
98
0
  struct rtsp_conn *rtspc = entry;
99
0
  (void)key;
100
0
  (void)klen;
101
0
  curlx_dyn_free(&rtspc->buf);
102
0
  curlx_free(rtspc);
103
0
}
104
105
static CURLcode rtsp_setup_connection(struct Curl_easy *data,
106
                                      struct connectdata *conn)
107
0
{
108
0
  struct rtsp_conn *rtspc;
109
0
  struct RTSP *rtsp;
110
111
0
  rtspc = curlx_calloc(1, sizeof(*rtspc));
112
0
  if(!rtspc)
113
0
    return CURLE_OUT_OF_MEMORY;
114
0
  curlx_dyn_init(&rtspc->buf, MAX_RTP_BUFFERSIZE);
115
0
  if(Curl_conn_meta_set(conn, CURL_META_RTSP_CONN, rtspc, rtsp_conn_dtor))
116
0
    return CURLE_OUT_OF_MEMORY;
117
118
0
  rtsp = curlx_calloc(1, sizeof(struct RTSP));
119
0
  if(!rtsp ||
120
0
     Curl_meta_set(data, CURL_META_RTSP_EASY, rtsp, rtsp_easy_dtor))
121
0
    return CURLE_OUT_OF_MEMORY;
122
123
0
  return CURLE_OK;
124
0
}
125
126
/*
127
 * Function to check on various aspects of a connection.
128
 */
129
static bool rtsp_conn_is_dead(struct Curl_easy *data,
130
                              struct connectdata *conn)
131
0
{
132
0
  bool input_pending;
133
  /* Contrary to default handling, this protocol allows pending
134
   * input on an unused connection. */
135
0
  return !Curl_conn_is_alive(data, conn, &input_pending);
136
0
}
137
138
static CURLcode rtsp_connect(struct Curl_easy *data, bool *done)
139
0
{
140
0
  struct rtsp_conn *rtspc =
141
0
    Curl_conn_meta_get(data->conn, CURL_META_RTSP_CONN);
142
143
0
  if(!rtspc)
144
0
    return CURLE_FAILED_INIT;
145
146
  /* Initialize the CSeq if not already done */
147
0
  if(data->state.rtsp_next_client_CSeq == 0)
148
0
    data->state.rtsp_next_client_CSeq = 1;
149
0
  if(data->state.rtsp_next_server_CSeq == 0)
150
0
    data->state.rtsp_next_server_CSeq = 1;
151
152
0
  rtspc->rtp_channel = -1;
153
0
  *done = TRUE;
154
0
  return CURLE_OK;
155
0
}
156
157
static CURLcode rtsp_done(struct Curl_easy *data,
158
                          CURLcode status, bool premature)
159
0
{
160
0
  struct rtsp_conn *rtspc =
161
0
    Curl_conn_meta_get(data->conn, CURL_META_RTSP_CONN);
162
0
  struct RTSP *rtsp = Curl_meta_get(data, CURL_META_RTSP_EASY);
163
0
  CURLcode result;
164
165
0
  if(!rtspc || !rtsp)
166
0
    return CURLE_FAILED_INIT;
167
168
  /* Bypass HTTP empty-reply checks on receive */
169
0
  if(data->set.rtspreq == RTSPREQ_RECEIVE)
170
0
    premature = TRUE;
171
172
0
  result = Curl_http_done(data, status, premature);
173
174
0
  if(!status && !result) {
175
    /* Check the sequence numbers */
176
0
    uint32_t CSeq_sent = rtsp->CSeq_sent;
177
0
    uint32_t CSeq_recv = rtsp->CSeq_recv;
178
0
    if((data->set.rtspreq != RTSPREQ_RECEIVE) && (CSeq_sent != CSeq_recv)) {
179
0
      failf(data,
180
0
            "The CSeq of this request %u did not match the response %u",
181
0
            CSeq_sent, CSeq_recv);
182
0
      return CURLE_RTSP_CSEQ_ERROR;
183
0
    }
184
0
    if(data->set.rtspreq == RTSPREQ_RECEIVE && (rtspc->rtp_channel == -1)) {
185
0
      infof(data, "Got an RTP Receive with a CSeq of %u", CSeq_recv);
186
0
    }
187
0
    if(data->set.rtspreq == RTSPREQ_RECEIVE &&
188
0
       data->req.eos_written) {
189
0
      failf(data, "Server prematurely closed the RTSP connection.");
190
0
      return CURLE_RECV_ERROR;
191
0
    }
192
0
  }
193
194
0
  return result;
195
0
}
196
197
static CURLcode rtsp_setup_body(struct Curl_easy *data,
198
                                Curl_RtspReq rtspreq,
199
                                struct dynbuf *reqp)
200
0
{
201
0
  CURLcode result;
202
0
  if(rtspreq == RTSPREQ_ANNOUNCE ||
203
0
     rtspreq == RTSPREQ_SET_PARAMETER ||
204
0
     rtspreq == RTSPREQ_GET_PARAMETER) {
205
0
    curl_off_t req_clen; /* request content length */
206
207
0
    if(data->state.upload) {
208
0
      req_clen = data->state.infilesize;
209
0
      data->state.httpreq = HTTPREQ_PUT;
210
0
      result = Curl_creader_set_fread(data, req_clen);
211
0
      if(result)
212
0
        return result;
213
0
    }
214
0
    else {
215
0
      if(data->set.postfields) {
216
0
        size_t plen = (data->set.postfieldsize >= 0) ?
217
0
          (size_t)data->set.postfieldsize : strlen(data->set.postfields);
218
0
        req_clen = (curl_off_t)plen;
219
0
        result = Curl_creader_set_buf(data, data->set.postfields, plen);
220
0
      }
221
0
      else if(data->state.infilesize >= 0) {
222
0
        req_clen = data->state.infilesize;
223
0
        result = Curl_creader_set_fread(data, req_clen);
224
0
      }
225
0
      else {
226
0
        req_clen = 0;
227
0
        result = Curl_creader_set_null(data);
228
0
      }
229
0
      if(result)
230
0
        return result;
231
0
    }
232
233
0
    if(req_clen > 0) {
234
      /* As stated in the http comments, it is probably not wise to
235
       * actually set a custom Content-Length in the headers */
236
0
      if(!Curl_checkheaders(data, STRCONST("Content-Length"))) {
237
0
        result = curlx_dyn_addf(reqp, "Content-Length: %" FMT_OFF_T "\r\n",
238
0
                                req_clen);
239
0
        if(result)
240
0
          return result;
241
0
      }
242
243
0
      if(rtspreq == RTSPREQ_SET_PARAMETER ||
244
0
         rtspreq == RTSPREQ_GET_PARAMETER) {
245
0
        if(!Curl_checkheaders(data, STRCONST("Content-Type"))) {
246
0
          result = curlx_dyn_addn(reqp, STRCONST("Content-Type: "
247
0
                                                 "text/parameters\r\n"));
248
0
          if(result)
249
0
            return result;
250
0
        }
251
0
      }
252
253
0
      if(rtspreq == RTSPREQ_ANNOUNCE) {
254
0
        if(!Curl_checkheaders(data, STRCONST("Content-Type"))) {
255
0
          result = curlx_dyn_addn(reqp, STRCONST("Content-Type: "
256
0
                                                 "application/sdp\r\n"));
257
0
          if(result)
258
0
            return result;
259
0
        }
260
0
      }
261
0
    }
262
0
    else if(rtspreq == RTSPREQ_GET_PARAMETER) {
263
      /* Check for an empty GET_PARAMETER (heartbeat) request */
264
0
      data->state.httpreq = HTTPREQ_HEAD;
265
0
      data->req.no_body = TRUE;
266
0
    }
267
0
  }
268
0
  else
269
0
    result = Curl_creader_set_null(data);
270
0
  return result;
271
0
}
272
273
static CURLcode rtsp_do(struct Curl_easy *data, bool *done)
274
0
{
275
0
  struct connectdata *conn = data->conn;
276
0
  CURLcode result = CURLE_OK;
277
0
  const Curl_RtspReq rtspreq = data->set.rtspreq;
278
0
  struct RTSP *rtsp = Curl_meta_get(data, CURL_META_RTSP_EASY);
279
0
  struct dynbuf req_buffer;
280
0
  const unsigned char httpversion = 11; /* RTSP is close to HTTP/1.1, sort
281
                                           of... */
282
0
  const char *p_request = NULL;
283
0
  const char *p_session_id = NULL;
284
0
  const char *p_accept = NULL;
285
0
  const char *p_accept_encoding = NULL;
286
0
  const char *p_range = NULL;
287
0
  const char *p_referrer = NULL;
288
0
  const char *p_stream_uri = NULL;
289
0
  const char *p_transport = NULL;
290
0
  const char *p_uagent = NULL;
291
0
  const char *p_hd_proxy_auth = NULL;
292
0
  const char *p_hd_auth = NULL;
293
294
0
  *done = TRUE;
295
0
  if(!rtsp)
296
0
    return CURLE_FAILED_INIT;
297
298
  /* Initialize a dynamic send buffer */
299
0
  curlx_dyn_init(&req_buffer, DYN_RTSP_REQ_HEADER);
300
301
0
  rtsp->CSeq_sent = data->state.rtsp_next_client_CSeq;
302
0
  rtsp->CSeq_recv = 0;
303
304
  /* Setup the 'p_request' pointer to the proper p_request string
305
   * Since all RTSP requests are included here, there is no need to
306
   * support custom requests like HTTP.
307
   **/
308
0
  data->req.no_body = TRUE; /* most requests do not contain a body */
309
0
  switch(rtspreq) {
310
0
  default:
311
0
    failf(data, "Got invalid RTSP request");
312
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
313
0
  case RTSPREQ_OPTIONS:
314
0
    p_request = "OPTIONS";
315
0
    break;
316
0
  case RTSPREQ_DESCRIBE:
317
0
    p_request = "DESCRIBE";
318
0
    data->req.no_body = FALSE;
319
0
    break;
320
0
  case RTSPREQ_ANNOUNCE:
321
0
    p_request = "ANNOUNCE";
322
0
    break;
323
0
  case RTSPREQ_SETUP:
324
0
    p_request = "SETUP";
325
0
    break;
326
0
  case RTSPREQ_PLAY:
327
0
    p_request = "PLAY";
328
0
    break;
329
0
  case RTSPREQ_PAUSE:
330
0
    p_request = "PAUSE";
331
0
    break;
332
0
  case RTSPREQ_TEARDOWN:
333
0
    p_request = "TEARDOWN";
334
0
    break;
335
0
  case RTSPREQ_GET_PARAMETER:
336
    /* GET_PARAMETER's no_body status is determined later */
337
0
    p_request = "GET_PARAMETER";
338
0
    data->req.no_body = FALSE;
339
0
    break;
340
0
  case RTSPREQ_SET_PARAMETER:
341
0
    p_request = "SET_PARAMETER";
342
0
    break;
343
0
  case RTSPREQ_RECORD:
344
0
    p_request = "RECORD";
345
0
    break;
346
0
  case RTSPREQ_RECEIVE:
347
0
    p_request = "";
348
    /* Treat interleaved RTP as body */
349
0
    data->req.no_body = FALSE;
350
0
    break;
351
0
  case RTSPREQ_LAST:
352
0
    failf(data, "Got invalid RTSP request: RTSPREQ_LAST");
353
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
354
0
  }
355
356
0
  if(rtspreq == RTSPREQ_RECEIVE) {
357
0
    Curl_xfer_setup_recv(data, FIRSTSOCKET, -1);
358
0
    goto out;
359
0
  }
360
361
0
  p_session_id = data->set.str[STRING_RTSP_SESSION_ID];
362
0
  if(!p_session_id &&
363
0
     (rtspreq & ~(Curl_RtspReq)(RTSPREQ_OPTIONS |
364
0
                                RTSPREQ_DESCRIBE |
365
0
                                RTSPREQ_SETUP))) {
366
0
    failf(data, "Refusing to issue an RTSP request [%s] without a session ID.",
367
0
          p_request);
368
0
    result = CURLE_BAD_FUNCTION_ARGUMENT;
369
0
    goto out;
370
0
  }
371
372
  /* Stream URI. Default to server '*' if not specified */
373
0
  if(data->set.str[STRING_RTSP_STREAM_URI]) {
374
0
    p_stream_uri = data->set.str[STRING_RTSP_STREAM_URI];
375
0
  }
376
0
  else {
377
0
    p_stream_uri = "*";
378
0
  }
379
380
  /* Transport Header for SETUP requests */
381
0
  p_transport = Curl_checkheaders(data, STRCONST("Transport"));
382
0
  if(rtspreq == RTSPREQ_SETUP && !p_transport) {
383
    /* New Transport: setting? */
384
0
    if(data->set.str[STRING_RTSP_TRANSPORT]) {
385
0
      curlx_free(data->state.aptr.rtsp_transport);
386
0
      data->state.aptr.rtsp_transport =
387
0
        curl_maprintf("Transport: %s\r\n",
388
0
                      data->set.str[STRING_RTSP_TRANSPORT]);
389
0
      if(!data->state.aptr.rtsp_transport)
390
0
        return CURLE_OUT_OF_MEMORY;
391
0
    }
392
0
    else {
393
0
      failf(data,
394
0
            "Refusing to issue an RTSP SETUP without a Transport: header.");
395
0
      result = CURLE_BAD_FUNCTION_ARGUMENT;
396
0
      goto out;
397
0
    }
398
399
0
    p_transport = data->state.aptr.rtsp_transport;
400
0
  }
401
402
  /* Accept Headers for DESCRIBE requests */
403
0
  if(rtspreq == RTSPREQ_DESCRIBE) {
404
    /* Accept Header */
405
0
    p_accept = Curl_checkheaders(data, STRCONST("Accept")) ?
406
0
      NULL : "Accept: application/sdp\r\n";
407
408
    /* Accept-Encoding header */
409
0
    if(!Curl_checkheaders(data, STRCONST("Accept-Encoding")) &&
410
0
       data->set.str[STRING_ENCODING]) {
411
0
      curlx_free(data->state.aptr.accept_encoding);
412
0
      data->state.aptr.accept_encoding =
413
0
        curl_maprintf("Accept-Encoding: %s\r\n",
414
0
                      data->set.str[STRING_ENCODING]);
415
416
0
      if(!data->state.aptr.accept_encoding) {
417
0
        result = CURLE_OUT_OF_MEMORY;
418
0
        goto out;
419
0
      }
420
0
      p_accept_encoding = data->state.aptr.accept_encoding;
421
0
    }
422
0
  }
423
424
  /* The User-Agent string might have been allocated already, because
425
     it might have been used in the proxy connect, but if we have got a header
426
     with the user-agent string specified, we erase the previously made string
427
     here. */
428
0
  if(Curl_checkheaders(data, STRCONST("User-Agent")) &&
429
0
     data->state.aptr.uagent) {
430
0
    curlx_safefree(data->state.aptr.uagent);
431
0
  }
432
0
  else if(!Curl_checkheaders(data, STRCONST("User-Agent")) &&
433
0
          data->set.str[STRING_USERAGENT]) {
434
0
    p_uagent = data->state.aptr.uagent;
435
0
  }
436
437
  /* setup the authentication headers */
438
0
  result = Curl_http_output_auth(data, conn, p_request, HTTPREQ_GET,
439
0
                                 p_stream_uri, NULL, FALSE);
440
0
  if(result)
441
0
    goto out;
442
443
0
#ifndef CURL_DISABLE_PROXY
444
0
  p_hd_proxy_auth = data->req.hd_proxy_auth;
445
0
#endif
446
0
  p_hd_auth = data->req.hd_auth;
447
448
  /* Referrer */
449
0
  curlx_safefree(data->state.aptr.ref);
450
0
  if(Curl_bufref_ptr(&data->state.referer) &&
451
0
     !Curl_checkheaders(data, STRCONST("Referer")))
452
0
    data->state.aptr.ref =
453
0
      curl_maprintf("Referer: %s\r\n", Curl_bufref_ptr(&data->state.referer));
454
455
0
  p_referrer = data->state.aptr.ref;
456
457
  /*
458
   * Range Header
459
   * Only applies to PLAY, PAUSE, RECORD
460
   *
461
   * Go ahead and use the Range stuff supplied for HTTP
462
   */
463
0
  if(data->state.use_range &&
464
0
     (rtspreq & (RTSPREQ_PLAY | RTSPREQ_PAUSE | RTSPREQ_RECORD))) {
465
466
    /* Check to see if there is a range set in the custom headers */
467
0
    if(!Curl_checkheaders(data, STRCONST("Range")) && data->state.range) {
468
0
      curlx_free(data->state.aptr.rangeline);
469
0
      data->state.aptr.rangeline = curl_maprintf("Range: %s\r\n",
470
0
                                                 data->state.range);
471
0
      p_range = data->state.aptr.rangeline;
472
0
    }
473
0
  }
474
475
  /*
476
   * Sanity check the custom headers
477
   */
478
0
  if(Curl_checkheaders(data, STRCONST("CSeq"))) {
479
0
    failf(data, "CSeq cannot be set as a custom header.");
480
0
    result = CURLE_RTSP_CSEQ_ERROR;
481
0
    goto out;
482
0
  }
483
0
  if(Curl_checkheaders(data, STRCONST("Session"))) {
484
0
    failf(data, "Session ID cannot be set as a custom header.");
485
0
    result = CURLE_BAD_FUNCTION_ARGUMENT;
486
0
    goto out;
487
0
  }
488
489
0
  result =
490
0
    curlx_dyn_addf(&req_buffer,
491
0
                   "%s %s RTSP/1.0\r\n" /* Request Stream-URI RTSP/1.0 */
492
0
                   "CSeq: %u\r\n", /* CSeq */
493
0
                   p_request, p_stream_uri, rtsp->CSeq_sent);
494
0
  if(result)
495
0
    goto out;
496
497
  /*
498
   * Rather than do a normal alloc line, keep the session_id unformatted
499
   * to make comparison easier
500
   */
501
0
  if(p_session_id) {
502
0
    result = curlx_dyn_addf(&req_buffer, "Session: %s\r\n", p_session_id);
503
0
    if(result)
504
0
      goto out;
505
0
  }
506
507
  /*
508
   * Shared HTTP-like options
509
   */
510
0
  result = curlx_dyn_addf(&req_buffer,
511
0
                          "%s" /* transport */
512
0
                          "%s" /* accept */
513
0
                          "%s" /* accept-encoding */
514
0
                          "%s" /* range */
515
0
                          "%s" /* referrer */
516
0
                          "%s" /* user-agent */
517
0
                          "%s" /* hd_proxy_auth */
518
0
                          "%s" /* hd_auth */
519
0
                          ,
520
0
                          p_transport ? p_transport : "",
521
0
                          p_accept ? p_accept : "",
522
0
                          p_accept_encoding ? p_accept_encoding : "",
523
0
                          p_range ? p_range : "",
524
0
                          p_referrer ? p_referrer : "",
525
0
                          p_uagent ? p_uagent : "",
526
0
                          p_hd_proxy_auth ? p_hd_proxy_auth : "",
527
0
                          p_hd_auth ? p_hd_auth : "");
528
529
0
  if(result)
530
0
    goto out;
531
532
0
  if((rtspreq == RTSPREQ_SETUP) || (rtspreq == RTSPREQ_DESCRIBE)) {
533
0
    result = Curl_add_timecondition(data, &req_buffer);
534
0
    if(result)
535
0
      goto out;
536
0
  }
537
538
0
  result = Curl_add_custom_headers(data, FALSE, httpversion, &req_buffer);
539
0
  if(result)
540
0
    goto out;
541
542
0
  result = rtsp_setup_body(data, rtspreq, &req_buffer);
543
0
  if(result)
544
0
    goto out;
545
546
  /* Finish the request buffer */
547
0
  result = curlx_dyn_addn(&req_buffer, STRCONST("\r\n"));
548
0
  if(result)
549
0
    goto out;
550
551
0
  Curl_xfer_setup_sendrecv(data, FIRSTSOCKET, -1);
552
553
  /* issue the request */
554
0
  result = Curl_req_send(data, &req_buffer, httpversion);
555
0
  if(result) {
556
0
    failf(data, "Failed sending RTSP request");
557
0
    goto out;
558
0
  }
559
560
  /* Increment the CSeq on success */
561
0
  data->state.rtsp_next_client_CSeq++;
562
563
0
  if(data->req.writebytecount) {
564
    /* if a request-body has been sent off, we make sure this progress is
565
       noted properly */
566
0
    Curl_pgrsSetUploadCounter(data, data->req.writebytecount);
567
0
    result = Curl_pgrsUpdate(data);
568
0
  }
569
0
out:
570
0
  curlx_dyn_free(&req_buffer);
571
0
  return result;
572
0
}
573
574
/**
575
 * write any BODY bytes missing to the client, ignore the rest.
576
 */
577
static CURLcode rtp_write_body_junk(struct Curl_easy *data,
578
                                    struct rtsp_conn *rtspc,
579
                                    const char *buf,
580
                                    size_t blen)
581
0
{
582
0
  curl_off_t body_remain;
583
0
  bool in_body;
584
585
0
  in_body = (data->req.headerline && !rtspc->in_header) &&
586
0
            (data->req.size >= 0) &&
587
0
            (data->req.bytecount < data->req.size);
588
0
  body_remain = in_body ? (data->req.size - data->req.bytecount) : 0;
589
0
  DEBUGASSERT(body_remain >= 0);
590
0
  if(body_remain) {
591
0
    if((curl_off_t)blen > body_remain)
592
0
      blen = (size_t)body_remain;
593
0
    return Curl_client_write(data, CLIENTWRITE_BODY, buf, blen);
594
0
  }
595
0
  return CURLE_OK;
596
0
}
597
598
static CURLcode rtp_client_write(struct Curl_easy *data, const char *ptr,
599
                                 size_t len)
600
0
{
601
0
  struct Curl_mapi_guard guard;
602
0
  size_t wrote;
603
0
  curl_write_callback writeit;
604
0
  void *user_ptr;
605
606
0
  if(len == 0) {
607
0
    failf(data, "Cannot write a 0 size RTP packet.");
608
0
    return CURLE_WRITE_ERROR;
609
0
  }
610
611
  /* If the user has configured CURLOPT_INTERLEAVEFUNCTION then use that
612
     function and any configured CURLOPT_INTERLEAVEDATA to write out the RTP
613
     data. Otherwise, use the CURLOPT_WRITEFUNCTION with the CURLOPT_WRITEDATA
614
     pointer to write out the RTP data. */
615
0
  if(data->set.fwrite_rtp) {
616
0
    writeit = data->set.fwrite_rtp;
617
0
    user_ptr = data->set.rtp_out;
618
0
  }
619
0
  else {
620
0
    writeit = data->set.fwrite_func;
621
0
    user_ptr = data->set.out;
622
0
  }
623
624
0
  CURL_CBAPI_START(&guard, data, easy_fwrite_rtp);
625
0
  wrote = writeit((char *)CURL_UNCONST(ptr), 1, len, user_ptr);
626
0
  CURL_CBAPI_END(&guard);
627
628
0
  if(wrote == CURL_WRITEFUNC_PAUSE) {
629
0
    failf(data, "Cannot pause RTP");
630
0
    return CURLE_WRITE_ERROR;
631
0
  }
632
633
0
  if(wrote != len) {
634
0
    failf(data, "Failed writing RTP data");
635
0
    return CURLE_WRITE_ERROR;
636
0
  }
637
638
0
  return CURLE_OK;
639
0
}
640
641
static CURLcode rtsp_filter_rtp(struct Curl_easy *data,
642
                                struct rtsp_conn *rtspc,
643
                                const char *buf,
644
                                size_t blen,
645
                                size_t *pconsumed)
646
0
{
647
0
  CURLcode result = CURLE_OK;
648
0
  size_t skip_len = 0;
649
650
0
  *pconsumed = 0;
651
0
  while(blen) {
652
0
    bool in_body = (data->req.headerline && !rtspc->in_header) &&
653
0
                   (data->req.size >= 0) &&
654
0
                   (data->req.bytecount < data->req.size);
655
0
    switch(rtspc->state) {
656
657
0
    case RTP_PARSE_SKIP: {
658
0
      DEBUGASSERT(curlx_dyn_len(&rtspc->buf) == 0);
659
0
      while(blen && buf[0] != '$') {
660
0
        if(!in_body && buf[0] == 'R' &&
661
0
           data->set.rtspreq != RTSPREQ_RECEIVE) {
662
0
          if(!strncmp(buf, "RTSP/", (blen < 5) ? blen : 5)) {
663
            /* This could be the next response, no consume and return */
664
0
            if(*pconsumed) {
665
0
              DEBUGF(infof(data, "RTP rtsp_filter_rtp[SKIP] RTSP/ prefix, "
666
0
                           "skipping %zu bytes of junk", *pconsumed));
667
0
            }
668
0
            rtspc->state = RTP_PARSE_SKIP;
669
0
            rtspc->in_header = TRUE;
670
0
            goto out;
671
0
          }
672
0
        }
673
        /* junk/BODY, consume without buffering */
674
0
        *pconsumed += 1;
675
0
        ++buf;
676
0
        --blen;
677
0
        ++skip_len;
678
0
      }
679
0
      if(blen && buf[0] == '$') {
680
        /* possible start of an RTP message, buffer */
681
0
        if(skip_len) {
682
          /* end of junk/BODY bytes, flush */
683
0
          result = rtp_write_body_junk(data, rtspc, buf - skip_len, skip_len);
684
0
          skip_len = 0;
685
0
          if(result)
686
0
            goto out;
687
0
        }
688
0
        if(curlx_dyn_addn(&rtspc->buf, buf, 1)) {
689
0
          result = CURLE_OUT_OF_MEMORY;
690
0
          goto out;
691
0
        }
692
0
        *pconsumed += 1;
693
0
        ++buf;
694
0
        --blen;
695
0
        rtspc->state = RTP_PARSE_CHANNEL;
696
0
      }
697
0
      break;
698
0
    }
699
700
0
    case RTP_PARSE_CHANNEL: {
701
0
      int idx = ((unsigned char)buf[0]) / 8;
702
0
      int off = ((unsigned char)buf[0]) % 8;
703
0
      DEBUGASSERT(curlx_dyn_len(&rtspc->buf) == 1);
704
0
      if(!(data->state.rtp_channel_mask[idx] & (1 << off))) {
705
        /* invalid channel number, junk or BODY data */
706
0
        rtspc->state = RTP_PARSE_SKIP;
707
0
        DEBUGASSERT(skip_len == 0);
708
        /* we do not consume this byte, it is BODY data */
709
0
        DEBUGF(infof(data, "RTSP: invalid RTP channel %d, skipping", idx));
710
0
        if(*pconsumed == 0) {
711
          /* We did not consume the initial '$' in our buffer, but had
712
           * it from an earlier call. We cannot un-consume it and have
713
           * to write it directly as BODY data */
714
0
          result = rtp_write_body_junk(data, rtspc,
715
0
                                       curlx_dyn_ptr(&rtspc->buf), 1);
716
0
          if(result)
717
0
            goto out;
718
0
        }
719
0
        else {
720
          /* count the '$' as skip and continue */
721
0
          skip_len = 1;
722
0
        }
723
0
        curlx_dyn_free(&rtspc->buf);
724
0
        break;
725
0
      }
726
      /* a valid channel, so we expect this to be a real RTP message */
727
0
      rtspc->rtp_channel = (unsigned char)buf[0];
728
0
      if(curlx_dyn_addn(&rtspc->buf, buf, 1)) {
729
0
        result = CURLE_OUT_OF_MEMORY;
730
0
        goto out;
731
0
      }
732
0
      *pconsumed += 1;
733
0
      ++buf;
734
0
      --blen;
735
0
      rtspc->state = RTP_PARSE_LEN;
736
0
      break;
737
0
    }
738
739
0
    case RTP_PARSE_LEN: {
740
0
      size_t rtp_len = curlx_dyn_len(&rtspc->buf);
741
0
      const char *rtp_buf;
742
0
      DEBUGASSERT(rtp_len >= 2 && rtp_len < 4);
743
0
      if(curlx_dyn_addn(&rtspc->buf, buf, 1)) {
744
0
        result = CURLE_OUT_OF_MEMORY;
745
0
        goto out;
746
0
      }
747
0
      *pconsumed += 1;
748
0
      ++buf;
749
0
      --blen;
750
0
      if(rtp_len == 2)
751
0
        break;
752
0
      rtp_buf = curlx_dyn_ptr(&rtspc->buf);
753
0
      rtspc->rtp_len = RTP_PKT_LENGTH(rtp_buf) + 4;
754
0
      if(rtspc->rtp_len == 4) {
755
        /* zero-length payload, the 4-byte header is the complete RTP
756
           message. Dispatch immediately without entering RTP_PARSE_DATA. */
757
0
        DEBUGF(infof(data, "RTP write channel %d rtp_len %zu (no payload)",
758
0
                     rtspc->rtp_channel, rtspc->rtp_len));
759
0
        result = rtp_client_write(data, rtp_buf, rtspc->rtp_len);
760
0
        curlx_dyn_free(&rtspc->buf);
761
0
        rtspc->state = RTP_PARSE_SKIP;
762
0
        if(result)
763
0
          goto out;
764
0
        break;
765
0
      }
766
0
      rtspc->state = RTP_PARSE_DATA;
767
0
      break;
768
0
    }
769
770
0
    case RTP_PARSE_DATA: {
771
0
      size_t rtp_len = curlx_dyn_len(&rtspc->buf);
772
0
      size_t needed;
773
0
      DEBUGASSERT(rtp_len < rtspc->rtp_len);
774
0
      needed = rtspc->rtp_len - rtp_len;
775
0
      if(needed <= blen) {
776
0
        if(curlx_dyn_addn(&rtspc->buf, buf, needed)) {
777
0
          result = CURLE_OUT_OF_MEMORY;
778
0
          goto out;
779
0
        }
780
0
        *pconsumed += needed;
781
0
        buf += needed;
782
0
        blen -= needed;
783
        /* complete RTP message in buffer */
784
0
        DEBUGF(infof(data, "RTP write channel %d rtp_len %zu",
785
0
                     rtspc->rtp_channel, rtspc->rtp_len));
786
0
        result = rtp_client_write(data, curlx_dyn_ptr(&rtspc->buf),
787
0
                                  rtspc->rtp_len);
788
0
        curlx_dyn_free(&rtspc->buf);
789
0
        rtspc->state = RTP_PARSE_SKIP;
790
0
        if(result)
791
0
          goto out;
792
0
      }
793
0
      else {
794
0
        if(curlx_dyn_addn(&rtspc->buf, buf, blen)) {
795
0
          result = CURLE_OUT_OF_MEMORY;
796
0
          goto out;
797
0
        }
798
0
        *pconsumed += blen;
799
0
        buf += blen;
800
0
        blen = 0;
801
0
      }
802
0
      break;
803
0
    }
804
805
0
    default:
806
0
      DEBUGASSERT(0);
807
0
      return CURLE_RECV_ERROR;
808
0
    }
809
0
  }
810
0
out:
811
0
  if(!result && skip_len)
812
0
    result = rtp_write_body_junk(data, rtspc, buf - skip_len, skip_len);
813
0
  return result;
814
0
}
815
816
/*
817
 * Parse and write out an RTSP response.
818
 * @param data     the transfer
819
 * @param conn     the connection
820
 * @param buf      data read from connection
821
 * @param blen     amount of data in buf
822
 * @param is_eos   TRUE iff this is the last write
823
 * @param readmore out, TRUE iff complete buf was consumed and more data
824
 *                 is needed
825
 */
826
static CURLcode rtsp_rtp_write_resp(struct Curl_easy *data,
827
                                    const char *buf,
828
                                    size_t blen,
829
                                    bool is_eos)
830
0
{
831
0
  struct rtsp_conn *rtspc =
832
0
    Curl_conn_meta_get(data->conn, CURL_META_RTSP_CONN);
833
0
  CURLcode result = CURLE_OK;
834
0
  size_t consumed = 0;
835
836
0
  if(!rtspc)
837
0
    return CURLE_FAILED_INIT;
838
839
0
  if(!data->req.header)
840
0
    rtspc->in_header = FALSE;
841
0
  if(!blen) {
842
0
    goto out;
843
0
  }
844
845
0
  DEBUGF(infof(data, "rtsp_rtp_write_resp(len=%zu, in_header=%d, eos=%d)",
846
0
               blen, rtspc->in_header, is_eos));
847
848
  /* If header parsing is not ongoing, extract RTP messages */
849
0
  if(!rtspc->in_header) {
850
0
    result = rtsp_filter_rtp(data, rtspc, buf, blen, &consumed);
851
0
    if(result)
852
0
      goto out;
853
0
    buf += consumed;
854
0
    blen -= consumed;
855
    /* either we consumed all or are at the start of header parsing */
856
0
    if(blen && !data->req.header)
857
0
      DEBUGF(infof(data, "RTSP: %zu bytes, possibly excess in response body",
858
0
                   blen));
859
0
  }
860
861
  /* we want to parse headers, do so */
862
0
  if(data->req.header && blen) {
863
0
    rtspc->in_header = TRUE;
864
0
    result = Curl_http_write_resp_hds(data, buf, blen, &consumed);
865
0
    if(result)
866
0
      goto out;
867
868
0
    buf += consumed;
869
0
    blen -= consumed;
870
871
0
    if(!data->req.header)
872
0
      rtspc->in_header = FALSE;
873
874
0
    if(!rtspc->in_header) {
875
      /* If header parsing is done, extract interleaved RTP messages */
876
0
      if(data->req.size <= -1) {
877
        /* Respect section 4.4 of rfc2326: If the Content-Length header is
878
           absent, a length 0 must be assumed. */
879
0
        data->req.size = 0;
880
0
        data->req.download_done = TRUE;
881
0
      }
882
0
      result = rtsp_filter_rtp(data, rtspc, buf, blen, &consumed);
883
0
      if(result)
884
0
        goto out;
885
0
      buf += consumed;
886
0
      blen -= consumed;
887
0
    }
888
0
  }
889
890
0
  if(rtspc->state != RTP_PARSE_SKIP)
891
0
    data->req.done = FALSE;
892
  /* we SHOULD have consumed all bytes, unless the response is borked.
893
   * In which case we write out the left over bytes, letting the client
894
   * writer deal with it (it will report EXCESS and fail the transfer). */
895
0
  DEBUGF(infof(data, "rtsp_rtp_write_resp(len=%zu, in_header=%d, done=%d, "
896
0
               "rtspc->state=%d, req.size=%" FMT_OFF_T ")",
897
0
               blen, rtspc->in_header, data->req.done, (int)rtspc->state,
898
0
               data->req.size));
899
0
  if(!result && (is_eos || blen)) {
900
0
    result = Curl_client_write(data, CLIENTWRITE_BODY |
901
0
                               (is_eos ? CLIENTWRITE_EOS : 0), buf, blen);
902
0
  }
903
904
0
out:
905
0
  if((data->set.rtspreq == RTSPREQ_RECEIVE) &&
906
0
     (rtspc->state == RTP_PARSE_SKIP)) {
907
    /* In special mode RECEIVE, we process one chunk of network
908
     * data, so we stop the transfer here, if we have no incomplete
909
     * RTP message pending. */
910
0
    data->req.download_done = TRUE;
911
0
  }
912
0
  return result;
913
0
}
914
915
static CURLcode rtsp_rtp_write_resp_hd(struct Curl_easy *data,
916
                                       const char *buf,
917
                                       size_t blen,
918
                                       bool is_eos)
919
0
{
920
0
  return rtsp_rtp_write_resp(data, buf, blen, is_eos);
921
0
}
922
923
static CURLcode rtsp_parse_transport(struct Curl_easy *data,
924
                                     const char *transport)
925
0
{
926
  /* If we receive multiple Transport response-headers, the interleaved
927
     channels of each response header is recorded and used together for
928
     subsequent data validity checks.*/
929
  /* e.g.: ' RTP/AVP/TCP;unicast;interleaved=5-6' */
930
0
  const char *start, *end;
931
0
  start = transport;
932
0
  while(start && *start) {
933
0
    curlx_str_passblanks(&start);
934
0
    end = strchr(start, ';');
935
0
    if(checkprefix("interleaved=", start)) {
936
0
      curl_off_t chan1, chan2, chan;
937
0
      const char *p = start + 12;
938
0
      if(!curlx_str_number(&p, &chan1, 255)) {
939
0
        unsigned char *rtp_channel_mask = data->state.rtp_channel_mask;
940
0
        chan2 = chan1;
941
0
        if(!curlx_str_single(&p, '-')) {
942
0
          if(curlx_str_number(&p, &chan2, 255)) {
943
0
            infof(data, "Unable to read the interleaved parameter from "
944
0
                  "Transport header: [%s]", transport);
945
0
            chan2 = chan1;
946
0
          }
947
0
        }
948
0
        for(chan = chan1; chan <= chan2; chan++) {
949
0
          int idx = (int)chan / 8;
950
0
          int off = (int)chan % 8;
951
0
          rtp_channel_mask[idx] |= (unsigned char)(1 << off);
952
0
        }
953
0
      }
954
0
      else {
955
0
        infof(data, "Unable to read the interleaved parameter from "
956
0
              "Transport header: [%s]", transport);
957
0
      }
958
0
      break;
959
0
    }
960
    /* skip to next parameter */
961
0
    start = (!end) ? end : (end + 1);
962
0
  }
963
0
  return CURLE_OK;
964
0
}
965
966
CURLcode Curl_rtsp_parseheader(struct Curl_easy *data, const char *header)
967
0
{
968
0
  if(checkprefix("CSeq:", header)) {
969
0
    curl_off_t CSeq = 0;
970
0
    struct RTSP *rtsp = Curl_meta_get(data, CURL_META_RTSP_EASY);
971
0
    const char *p = &header[5];
972
0
    if(!rtsp)
973
0
      return CURLE_FAILED_INIT;
974
0
    curlx_str_passblanks(&p);
975
0
    if(curlx_str_number(&p, &CSeq, UINT_MAX)) {
976
0
      failf(data, "Unable to read the CSeq header: [%s]", header);
977
0
      return CURLE_RTSP_CSEQ_ERROR;
978
0
    }
979
0
    data->state.rtsp_CSeq_recv = rtsp->CSeq_recv = (uint32_t)CSeq;
980
0
  }
981
0
  else if(checkprefix("Session:", header)) {
982
0
    const char *start, *end;
983
0
    size_t idlen;
984
985
    /* Find the first non-space letter */
986
0
    start = header + 8;
987
0
    curlx_str_passblanks(&start);
988
989
0
    if(!*start) {
990
0
      failf(data, "Got a blank Session ID");
991
0
      return CURLE_RTSP_SESSION_ERROR;
992
0
    }
993
994
    /* Find the end of Session ID
995
     *
996
     * Allow any non whitespace content, up to the field separator or end of
997
     * line. RFC 2326 is not 100% clear on the session ID and for example
998
     * gstreamer does URL-encoded session ID's not covered by the standard.
999
     */
1000
0
    end = start;
1001
0
    while((*end > ' ') && (*end != ';'))
1002
0
      end++;
1003
0
    idlen = end - start;
1004
1005
0
    if(data->set.str[STRING_RTSP_SESSION_ID]) {
1006
1007
      /* If the Session ID is set, then compare */
1008
0
      if(strlen(data->set.str[STRING_RTSP_SESSION_ID]) != idlen ||
1009
0
         strncmp(start, data->set.str[STRING_RTSP_SESSION_ID], idlen)) {
1010
0
        failf(data, "Got RTSP Session ID Line [%s], but wanted ID [%s]",
1011
0
              start, data->set.str[STRING_RTSP_SESSION_ID]);
1012
0
        return CURLE_RTSP_SESSION_ERROR;
1013
0
      }
1014
0
    }
1015
0
    else {
1016
      /* If the Session ID is not set, and we find it in a response, then set
1017
       * it.
1018
       */
1019
1020
      /* Copy the id substring into a new buffer */
1021
0
      data->set.str[STRING_RTSP_SESSION_ID] = curlx_memdup0(start, idlen);
1022
0
      if(!data->set.str[STRING_RTSP_SESSION_ID])
1023
0
        return CURLE_OUT_OF_MEMORY;
1024
0
    }
1025
0
  }
1026
0
  else if(checkprefix("Transport:", header)) {
1027
0
    CURLcode result;
1028
0
    result = rtsp_parse_transport(data, header + 10);
1029
0
    if(result)
1030
0
      return result;
1031
0
  }
1032
0
  return CURLE_OK;
1033
0
}
1034
1035
/*
1036
 * RTSP handler interface.
1037
 */
1038
const struct Curl_protocol Curl_protocol_rtsp = {
1039
  rtsp_setup_connection,                /* setup_connection */
1040
  rtsp_do,                              /* do_it */
1041
  rtsp_done,                            /* done */
1042
  ZERO_NULL,                            /* do_more */
1043
  rtsp_connect,                         /* connect_it */
1044
  ZERO_NULL,                            /* connecting */
1045
  ZERO_NULL,                            /* doing */
1046
  ZERO_NULL,                            /* proto_pollset */
1047
  rtsp_do_pollset,                      /* doing_pollset */
1048
  ZERO_NULL,                            /* domore_pollset */
1049
  Curl_http_perform_pollset,            /* perform_pollset */
1050
  ZERO_NULL,                            /* disconnect */
1051
  rtsp_rtp_write_resp,                  /* write_resp */
1052
  rtsp_rtp_write_resp_hd,               /* write_resp_hd */
1053
  rtsp_conn_is_dead,                    /* connection_is_dead */
1054
  ZERO_NULL,                            /* attach connection */
1055
  Curl_http_follow,                     /* follow */
1056
};
1057
1058
#endif /* CURL_DISABLE_RTSP */