Coverage Report

Created: 2026-08-13 07:42

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
80.0k
#define CURL_META_RTSP_EASY   "meta:proto:rtsp:easy"
47
/* meta key for storing protocol meta at connection */
48
139k
#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
29.0k
#define MAX_RTP_BUFFERSIZE 1000000 /* arbitrary */
87
88
static void rtsp_easy_dtor(void *key, size_t klen, void *entry)
89
29.0k
{
90
29.0k
  struct RTSP *rtsp = entry;
91
29.0k
  (void)key;
92
29.0k
  (void)klen;
93
29.0k
  curlx_free(rtsp);
94
29.0k
}
95
96
static void rtsp_conn_dtor(void *key, size_t klen, void *entry)
97
29.0k
{
98
29.0k
  struct rtsp_conn *rtspc = entry;
99
29.0k
  (void)key;
100
29.0k
  (void)klen;
101
29.0k
  curlx_dyn_free(&rtspc->buf);
102
29.0k
  curlx_free(rtspc);
103
29.0k
}
104
105
static CURLcode rtsp_setup_connection(struct Curl_easy *data,
106
                                      struct connectdata *conn)
107
29.0k
{
108
29.0k
  struct rtsp_conn *rtspc;
109
29.0k
  struct RTSP *rtsp;
110
111
29.0k
  rtspc = curlx_calloc(1, sizeof(*rtspc));
112
29.0k
  if(!rtspc)
113
0
    return CURLE_OUT_OF_MEMORY;
114
29.0k
  curlx_dyn_init(&rtspc->buf, MAX_RTP_BUFFERSIZE);
115
29.0k
  if(Curl_conn_meta_set(conn, CURL_META_RTSP_CONN, rtspc, rtsp_conn_dtor))
116
0
    return CURLE_OUT_OF_MEMORY;
117
118
29.0k
  rtsp = curlx_calloc(1, sizeof(struct RTSP));
119
29.0k
  if(!rtsp ||
120
29.0k
     Curl_meta_set(data, CURL_META_RTSP_EASY, rtsp, rtsp_easy_dtor))
121
0
    return CURLE_OUT_OF_MEMORY;
122
123
29.0k
  return CURLE_OK;
124
29.0k
}
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
1.37k
{
132
1.37k
  bool input_pending;
133
  /* Contrary to default handling, this protocol allows pending
134
   * input on an unused connection. */
135
1.37k
  return !Curl_conn_is_alive(data, conn, &input_pending);
136
1.37k
}
137
138
static CURLcode rtsp_connect(struct Curl_easy *data, bool *done)
139
8.73k
{
140
8.73k
  struct rtsp_conn *rtspc =
141
8.73k
    Curl_conn_meta_get(data->conn, CURL_META_RTSP_CONN);
142
143
8.73k
  if(!rtspc)
144
0
    return CURLE_FAILED_INIT;
145
146
  /* Initialize the CSeq if not already done */
147
8.73k
  if(data->state.rtsp_next_client_CSeq == 0)
148
8.37k
    data->state.rtsp_next_client_CSeq = 1;
149
8.73k
  if(data->state.rtsp_next_server_CSeq == 0)
150
8.37k
    data->state.rtsp_next_server_CSeq = 1;
151
152
8.73k
  rtspc->rtp_channel = -1;
153
8.73k
  *done = TRUE;
154
8.73k
  return CURLE_OK;
155
8.73k
}
156
157
static CURLcode rtsp_done(struct Curl_easy *data,
158
                          CURLcode status, bool premature)
159
25.2k
{
160
25.2k
  struct rtsp_conn *rtspc =
161
25.2k
    Curl_conn_meta_get(data->conn, CURL_META_RTSP_CONN);
162
25.2k
  struct RTSP *rtsp = Curl_meta_get(data, CURL_META_RTSP_EASY);
163
25.2k
  CURLcode result;
164
165
25.2k
  if(!rtspc || !rtsp)
166
0
    return CURLE_FAILED_INIT;
167
168
  /* Bypass HTTP empty-reply checks on receive */
169
25.2k
  if(data->set.rtspreq == RTSPREQ_RECEIVE)
170
16
    premature = TRUE;
171
172
25.2k
  result = Curl_http_done(data, status, premature);
173
174
25.2k
  if(!status && !result) {
175
    /* Check the sequence numbers */
176
19.5k
    uint32_t CSeq_sent = rtsp->CSeq_sent;
177
19.5k
    uint32_t CSeq_recv = rtsp->CSeq_recv;
178
19.5k
    if((data->set.rtspreq != RTSPREQ_RECEIVE) && (CSeq_sent != CSeq_recv)) {
179
19.5k
      failf(data,
180
19.5k
            "The CSeq of this request %u did not match the response %u",
181
19.5k
            CSeq_sent, CSeq_recv);
182
19.5k
      return CURLE_RTSP_CSEQ_ERROR;
183
19.5k
    }
184
21
    if(data->set.rtspreq == RTSPREQ_RECEIVE && (rtspc->rtp_channel == -1)) {
185
16
      infof(data, "Got an RTP Receive with a CSeq of %u", CSeq_recv);
186
16
    }
187
21
    if(data->set.rtspreq == RTSPREQ_RECEIVE &&
188
16
       data->req.eos_written) {
189
3
      failf(data, "Server prematurely closed the RTSP connection.");
190
3
      return CURLE_RECV_ERROR;
191
3
    }
192
21
  }
193
194
5.66k
  return result;
195
25.2k
}
196
197
static CURLcode rtsp_setup_body(struct Curl_easy *data,
198
                                unsigned char rtspreq,
199
                                struct dynbuf *reqp)
200
25.1k
{
201
25.1k
  CURLcode result;
202
25.1k
  if(rtspreq == RTSPREQ_ANNOUNCE ||
203
24.0k
     rtspreq == RTSPREQ_SET_PARAMETER ||
204
23.8k
     rtspreq == RTSPREQ_GET_PARAMETER) {
205
1.59k
    curl_off_t req_clen; /* request content length */
206
207
1.59k
    if(data->state.upload) {
208
247
      req_clen = data->state.infilesize;
209
247
      data->state.httpreq = HTTPREQ_PUT;
210
247
      result = Curl_creader_set_fread(data, req_clen);
211
247
      if(result)
212
0
        return result;
213
247
    }
214
1.34k
    else {
215
1.34k
      if(data->set.postfields) {
216
981
        size_t plen = (data->set.postfieldsize >= 0) ?
217
981
          (size_t)data->set.postfieldsize : strlen(data->set.postfields);
218
981
        req_clen = (curl_off_t)plen;
219
981
        result = Curl_creader_set_buf(data, data->set.postfields, plen);
220
981
      }
221
367
      else if(data->state.infilesize >= 0) {
222
234
        req_clen = data->state.infilesize;
223
234
        result = Curl_creader_set_fread(data, req_clen);
224
234
      }
225
133
      else {
226
133
        req_clen = 0;
227
133
        result = Curl_creader_set_null(data);
228
133
      }
229
1.34k
      if(result)
230
0
        return result;
231
1.34k
    }
232
233
1.59k
    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
1.07k
      if(!Curl_checkheaders(data, STRCONST("Content-Length"))) {
237
1.07k
        result = curlx_dyn_addf(reqp, "Content-Length: %" FMT_OFF_T "\r\n",
238
1.07k
                                req_clen);
239
1.07k
        if(result)
240
1
          return result;
241
1.07k
      }
242
243
1.07k
      if(rtspreq == RTSPREQ_SET_PARAMETER ||
244
902
         rtspreq == RTSPREQ_GET_PARAMETER) {
245
405
        if(!Curl_checkheaders(data, STRCONST("Content-Type"))) {
246
405
          result = curlx_dyn_addn(reqp, STRCONST("Content-Type: "
247
405
                                                 "text/parameters\r\n"));
248
405
          if(result)
249
1
            return result;
250
405
        }
251
405
      }
252
253
1.07k
      if(rtspreq == RTSPREQ_ANNOUNCE) {
254
667
        if(!Curl_checkheaders(data, STRCONST("Content-Type"))) {
255
667
          result = curlx_dyn_addn(reqp, STRCONST("Content-Type: "
256
667
                                                 "application/sdp\r\n"));
257
667
          if(result)
258
1
            return result;
259
667
        }
260
667
      }
261
1.07k
    }
262
522
    else if(rtspreq == RTSPREQ_GET_PARAMETER) {
263
      /* Check for an empty GET_PARAMETER (heartbeat) request */
264
95
      data->state.httpreq = HTTPREQ_HEAD;
265
95
      data->req.no_body = TRUE;
266
95
    }
267
1.59k
  }
268
23.5k
  else
269
23.5k
    result = Curl_creader_set_null(data);
270
25.1k
  return result;
271
25.1k
}
272
273
struct rtspselect {
274
  const char *method;
275
  bool no_body;
276
};
277
278
static CURLcode pick_method(struct Curl_easy *data,
279
                            const unsigned char rtspreq,
280
                            const char **p)
281
25.2k
{
282
25.2k
  static const struct rtspselect req[] = {
283
25.2k
    { "OPTIONS",       TRUE },
284
25.2k
    { "DESCRIBE",      FALSE },
285
25.2k
    { "ANNOUNCE",      TRUE },
286
25.2k
    { "SETUP",         TRUE },
287
25.2k
    { "PLAY",          TRUE },
288
25.2k
    { "PAUSE",         TRUE },
289
25.2k
    { "TEARDOWN",      TRUE },
290
25.2k
    { "GET_PARAMETER", FALSE },
291
25.2k
    { "SET_PARAMETER", TRUE },
292
25.2k
    { "RECORD",        TRUE },
293
25.2k
    { "", FALSE }, /* RECEIVE: treat interleaved RTP as body */
294
25.2k
  };
295
  /* this is verified already in setopt, this is just added precaution */
296
25.2k
  DEBUGASSERT((rtspreq > RTSPREQ_NONE) && (rtspreq < RTSPREQ_LAST));
297
25.2k
  if((rtspreq <= RTSPREQ_NONE) || (rtspreq >= RTSPREQ_LAST))
298
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
299
25.2k
  *p = req[rtspreq - 1].method;
300
25.2k
  data->req.no_body = req[rtspreq - 1].no_body;
301
25.2k
  return CURLE_OK;
302
25.2k
}
303
304
/* Allocate and store a header string. */
305
static CURLcode rtsp_header_alloc(const char *header_name,
306
                                  const char *value,
307
                                  char **target)
308
1.73k
{
309
1.73k
  if(!value)
310
0
    return CURLE_OK;
311
1.73k
  curlx_free(*target);
312
1.73k
  *target = curl_maprintf("%s: %s\r\n", header_name, value);
313
1.73k
  if(!*target)
314
0
    return CURLE_OUT_OF_MEMORY;
315
1.73k
  return CURLE_OK;
316
1.73k
}
317
318
struct rtsp_blocks {
319
  const char *request;
320
  const char *session_id;
321
  const char *accept;
322
  const char *accept_encoding;
323
  const char *range;
324
  const char *referrer;
325
  const char *stream_uri;
326
  const char *transport;
327
  const char *uagent;
328
  const char *hd_proxy_auth;
329
  const char *hd_auth;
330
};
331
332
static CURLcode rtsp_setup_request(struct Curl_easy *data,
333
                                   struct rtsp_blocks *b,
334
                                   const unsigned char rtspreq)
335
25.2k
{
336
25.2k
  CURLcode result = CURLE_OK;
337
25.2k
  struct connectdata *conn = data->conn;
338
339
25.2k
  b->session_id = data->set.str[STRING_RTSP_SESSION_ID];
340
341
  /* Stream URI. Default to server '*' if not specified */
342
25.2k
  if(data->set.str[STRING_RTSP_STREAM_URI])
343
513
    b->stream_uri = data->set.str[STRING_RTSP_STREAM_URI];
344
24.6k
  else
345
24.6k
    b->stream_uri = "*";
346
347
  /* Transport Header for SETUP requests */
348
25.2k
  b->transport = Curl_checkheaders(data, STRCONST("Transport"));
349
25.2k
  if(rtspreq == RTSPREQ_SETUP && !b->transport) {
350
    /* New Transport: setting? */
351
136
    if(data->set.str[STRING_RTSP_TRANSPORT]) {
352
131
      result = rtsp_header_alloc("Transport",
353
131
                                 data->set.str[STRING_RTSP_TRANSPORT],
354
131
                                 &data->state.aptr.rtsp_transport);
355
131
      if(result)
356
0
        return result;
357
131
    }
358
5
    else {
359
5
      failf(data,
360
5
            "Refusing to issue an RTSP SETUP without a Transport: header.");
361
5
      return CURLE_BAD_FUNCTION_ARGUMENT;
362
5
    }
363
364
131
    b->transport = data->state.aptr.rtsp_transport;
365
131
  }
366
367
  /* Accept Headers for DESCRIBE requests */
368
25.1k
  if(rtspreq == RTSPREQ_DESCRIBE) {
369
    /* Accept Header */
370
2.49k
    b->accept = Curl_checkheaders(data, STRCONST("Accept")) ?
371
2.49k
      NULL : "Accept: application/sdp\r\n";
372
373
    /* Accept-Encoding header */
374
2.49k
    if(!Curl_checkheaders(data, STRCONST("Accept-Encoding")) &&
375
2.49k
       data->set.str[STRING_ENCODING]) {
376
1.35k
      result = rtsp_header_alloc("Accept-Encoding",
377
1.35k
                                 data->set.str[STRING_ENCODING],
378
1.35k
                                 &data->state.aptr.accept_encoding);
379
1.35k
      if(result)
380
0
        return result;
381
1.35k
      b->accept_encoding = data->state.aptr.accept_encoding;
382
1.35k
    }
383
2.49k
  }
384
385
  /* The User-Agent string might have been allocated already, because
386
     it might have been used in the proxy connect, but if we have got a header
387
     with the user-agent string specified, we erase the previously made string
388
     here. */
389
25.1k
  if(Curl_checkheaders(data, STRCONST("User-Agent")) &&
390
0
     data->state.aptr.uagent) {
391
0
    curlx_safefree(data->state.aptr.uagent);
392
0
  }
393
25.1k
  else if(!Curl_checkheaders(data, STRCONST("User-Agent")) &&
394
25.1k
          data->set.str[STRING_USERAGENT]) {
395
1.83k
    b->uagent = data->state.aptr.uagent;
396
1.83k
  }
397
398
  /* setup the authentication headers */
399
25.1k
  result = Curl_http_output_auth(data, conn, b->request, HTTPREQ_GET,
400
25.1k
                                 b->stream_uri, NULL, FALSE);
401
25.1k
  if(result)
402
26
    return result;
403
404
25.1k
#ifndef CURL_DISABLE_PROXY
405
25.1k
  b->hd_proxy_auth = data->req.hd_proxy_auth;
406
25.1k
#endif
407
25.1k
  b->hd_auth = data->req.hd_auth;
408
409
  /* Referrer */
410
25.1k
  curlx_safefree(data->state.aptr.ref);
411
25.1k
  if(Curl_bufref_ptr(&data->state.referer) &&
412
6.54k
     !Curl_checkheaders(data, STRCONST("Referer")))
413
6.54k
    data->state.aptr.ref =
414
6.54k
      curl_maprintf("Referer: %s\r\n", Curl_bufref_ptr(&data->state.referer));
415
416
25.1k
  b->referrer = data->state.aptr.ref;
417
418
  /*
419
   * Range Header
420
   * Only applies to PLAY, PAUSE, RECORD
421
   *
422
   * Go ahead and use the Range stuff supplied for HTTP
423
   */
424
25.1k
  if(data->state.use_range &&
425
2.24k
     ((rtspreq == RTSPREQ_PLAY) ||
426
2.11k
      (rtspreq == RTSPREQ_PAUSE) ||
427
2.07k
      (rtspreq == RTSPREQ_RECORD))) {
428
429
    /* Check to see if there is a range set in the custom headers */
430
246
    if(!Curl_checkheaders(data, STRCONST("Range")) && data->state.range) {
431
246
      result = rtsp_header_alloc("Range",
432
246
                                 data->state.range,
433
246
                                 &data->state.aptr.rangeline);
434
246
      if(!result)
435
246
        b->range = data->state.aptr.rangeline;
436
246
    }
437
246
  }
438
25.1k
  return result;
439
25.1k
}
440
441
50.3k
#define HTTPVERSION 11 /* RTSP is close to HTTP/1.1, sort of... */
442
443
static CURLcode rtsp_do(struct Curl_easy *data, bool *done)
444
25.2k
{
445
25.2k
  CURLcode result = CURLE_OK;
446
25.2k
  const unsigned char rtspreq = data->set.rtspreq;
447
25.2k
  struct RTSP *rtsp = Curl_meta_get(data, CURL_META_RTSP_EASY);
448
25.2k
  struct dynbuf req_buffer;
449
25.2k
  struct rtsp_blocks block;
450
25.2k
  memset(&block, 0, sizeof(block));
451
452
25.2k
  *done = TRUE;
453
25.2k
  if(!rtsp)
454
0
    return CURLE_FAILED_INIT;
455
456
  /* Initialize a dynamic send buffer */
457
25.2k
  curlx_dyn_init(&req_buffer, DYN_RTSP_REQ_HEADER);
458
459
25.2k
  rtsp->CSeq_sent = data->state.rtsp_next_client_CSeq;
460
25.2k
  rtsp->CSeq_recv = 0;
461
462
  /* Setup the 'p_request' pointer to the proper method. */
463
25.2k
  result = pick_method(data, rtspreq, &block.request);
464
25.2k
  if(result)
465
0
    goto out;
466
467
25.2k
  if(rtspreq == RTSPREQ_RECEIVE) {
468
16
    Curl_xfer_setup_recv(data, FIRSTSOCKET, -1);
469
16
    goto out;
470
16
  }
471
472
25.2k
  result = rtsp_setup_request(data, &block,  rtspreq);
473
25.2k
  if(result)
474
31
    goto out;
475
  /*
476
   * Sanity check the custom headers
477
   */
478
25.1k
  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
25.1k
  if(Curl_checkheaders(data, STRCONST("Session"))) {
484
1
    failf(data, "Session ID cannot be set as a custom header.");
485
1
    result = CURLE_BAD_FUNCTION_ARGUMENT;
486
1
    goto out;
487
1
  }
488
489
25.1k
  result =
490
25.1k
    curlx_dyn_addf(&req_buffer,
491
25.1k
                   "%s %s RTSP/1.0\r\n" /* Request Stream-URI RTSP/1.0 */
492
25.1k
                   "CSeq: %u\r\n", /* CSeq */
493
25.1k
                   block.request, block.stream_uri, rtsp->CSeq_sent);
494
25.1k
  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
25.1k
  if(block.session_id) {
502
1.31k
    result = curlx_dyn_addf(&req_buffer, "Session: %s\r\n", block.session_id);
503
1.31k
    if(result)
504
0
      goto out;
505
1.31k
  }
506
507
  /*
508
   * Shared HTTP-like options
509
   */
510
25.1k
  result = curlx_dyn_addf(&req_buffer,
511
25.1k
                          "%s" /* transport */
512
25.1k
                          "%s" /* accept */
513
25.1k
                          "%s" /* accept-encoding */
514
25.1k
                          "%s" /* range */
515
25.1k
                          "%s" /* referrer */
516
25.1k
                          "%s" /* user-agent */
517
25.1k
                          "%s" /* hd_proxy_auth */
518
25.1k
                          "%s" /* hd_auth */
519
25.1k
                          ,
520
25.1k
                          block.transport ? block.transport : "",
521
25.1k
                          block.accept ? block.accept : "",
522
25.1k
                          block.accept_encoding ? block.accept_encoding : "",
523
25.1k
                          block.range ? block.range : "",
524
25.1k
                          block.referrer ? block.referrer : "",
525
25.1k
                          block.uagent ? block.uagent : "",
526
25.1k
                          block.hd_proxy_auth ? block.hd_proxy_auth : "",
527
25.1k
                          block.hd_auth ? block.hd_auth : "");
528
529
25.1k
  if(result)
530
6
    goto out;
531
532
25.1k
  if((rtspreq == RTSPREQ_SETUP) || (rtspreq == RTSPREQ_DESCRIBE)) {
533
2.62k
    result = Curl_add_timecondition(data, &req_buffer);
534
2.62k
    if(result)
535
0
      goto out;
536
2.62k
  }
537
538
25.1k
  result = Curl_add_custom_headers(data, FALSE, HTTPVERSION, &req_buffer);
539
25.1k
  if(result)
540
15
    goto out;
541
542
25.1k
  result = rtsp_setup_body(data, rtspreq, &req_buffer);
543
25.1k
  if(result)
544
3
    goto out;
545
546
  /* Finish the request buffer */
547
25.1k
  result = curlx_dyn_addn(&req_buffer, STRCONST("\r\n"));
548
25.1k
  if(result)
549
1
    goto out;
550
551
25.1k
  Curl_xfer_setup_sendrecv(data, FIRSTSOCKET, -1);
552
553
  /* issue the request */
554
25.1k
  result = Curl_req_send(data, &req_buffer, HTTPVERSION);
555
25.1k
  if(result) {
556
3
    failf(data, "Failed sending RTSP request");
557
3
    goto out;
558
3
  }
559
560
  /* Increment the CSeq on success */
561
25.1k
  data->state.rtsp_next_client_CSeq++;
562
563
25.1k
  if(data->req.writebytecount) {
564
    /* if a request-body has been sent off, we make sure this progress is
565
       noted properly */
566
1.06k
    Curl_pgrsSetUploadCounter(data, data->req.writebytecount);
567
1.06k
    result = Curl_pgrsUpdate(data);
568
1.06k
  }
569
25.2k
out:
570
25.2k
  curlx_dyn_free(&req_buffer);
571
25.2k
  return result;
572
25.1k
}
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
1.32M
{
582
1.32M
  curl_off_t body_remain;
583
1.32M
  bool in_body;
584
585
1.32M
  in_body = (data->req.headerline && !rtspc->in_header) &&
586
457k
            (data->req.size >= 0) &&
587
457k
            (data->req.bytecount < data->req.size);
588
1.32M
  body_remain = in_body ? (data->req.size - data->req.bytecount) : 0;
589
1.32M
  DEBUGASSERT(body_remain >= 0);
590
1.32M
  if(body_remain) {
591
285k
    if((curl_off_t)blen > body_remain)
592
489
      blen = (size_t)body_remain;
593
285k
    return Curl_client_write(data, CLIENTWRITE_BODY, buf, blen);
594
285k
  }
595
1.03M
  return CURLE_OK;
596
1.32M
}
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
65.0k
{
647
65.0k
  CURLcode result = CURLE_OK;
648
65.0k
  size_t skip_len = 0;
649
650
65.0k
  *pconsumed = 0;
651
2.62M
  while(blen) {
652
2.58M
    bool in_body = (data->req.headerline && !rtspc->in_header) &&
653
897k
                   (data->req.size >= 0) &&
654
897k
                   (data->req.bytecount < data->req.size);
655
2.58M
    switch(rtspc->state) {
656
657
1.32M
    case RTP_PARSE_SKIP: {
658
1.32M
      DEBUGASSERT(curlx_dyn_len(&rtspc->buf) == 0);
659
14.1M
      while(blen && buf[0] != '$') {
660
12.8M
        if(!in_body && buf[0] == 'R' &&
661
80.1k
           data->set.rtspreq != RTSPREQ_RECEIVE) {
662
79.9k
          if(!strncmp(buf, "RTSP/", (blen < 5) ? blen : 5)) {
663
            /* This could be the next response, no consume and return */
664
22.1k
            if(*pconsumed) {
665
20.8k
              DEBUGF(infof(data, "RTP rtsp_filter_rtp[SKIP] RTSP/ prefix, "
666
20.8k
                           "skipping %zu bytes of junk", *pconsumed));
667
20.8k
            }
668
22.1k
            rtspc->state = RTP_PARSE_SKIP;
669
22.1k
            rtspc->in_header = TRUE;
670
22.1k
            goto out;
671
22.1k
          }
672
79.9k
        }
673
        /* junk/BODY, consume without buffering */
674
12.8M
        *pconsumed += 1;
675
12.8M
        ++buf;
676
12.8M
        --blen;
677
12.8M
        ++skip_len;
678
12.8M
      }
679
1.30M
      if(blen && buf[0] == '$') {
680
        /* possible start of an RTP message, buffer */
681
1.26M
        if(skip_len) {
682
          /* end of junk/BODY bytes, flush */
683
1.25M
          result = rtp_write_body_junk(data, rtspc, buf - skip_len, skip_len);
684
1.25M
          skip_len = 0;
685
1.25M
          if(result)
686
130
            goto out;
687
1.25M
        }
688
1.26M
        if(curlx_dyn_addn(&rtspc->buf, buf, 1)) {
689
0
          result = CURLE_OUT_OF_MEMORY;
690
0
          goto out;
691
0
        }
692
1.26M
        *pconsumed += 1;
693
1.26M
        ++buf;
694
1.26M
        --blen;
695
1.26M
        rtspc->state = RTP_PARSE_CHANNEL;
696
1.26M
      }
697
1.30M
      break;
698
1.30M
    }
699
700
1.30M
    case RTP_PARSE_CHANNEL: {
701
1.26M
      int idx = ((unsigned char)buf[0]) / 8;
702
1.26M
      int off = ((unsigned char)buf[0]) % 8;
703
1.26M
      DEBUGASSERT(curlx_dyn_len(&rtspc->buf) == 1);
704
1.26M
      if(!(data->state.rtp_channel_mask[idx] & (1 << off))) {
705
        /* invalid channel number, junk or BODY data */
706
1.26M
        rtspc->state = RTP_PARSE_SKIP;
707
1.26M
        DEBUGASSERT(skip_len == 0);
708
        /* we do not consume this byte, it is BODY data */
709
1.26M
        DEBUGF(infof(data, "RTSP: invalid RTP channel %d, skipping", idx));
710
1.26M
        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
2.39k
          result = rtp_write_body_junk(data, rtspc,
715
2.39k
                                       curlx_dyn_ptr(&rtspc->buf), 1);
716
2.39k
          if(result)
717
1
            goto out;
718
2.39k
        }
719
1.25M
        else {
720
          /* count the '$' as skip and continue */
721
1.25M
          skip_len = 1;
722
1.25M
        }
723
1.26M
        curlx_dyn_free(&rtspc->buf);
724
1.26M
        break;
725
1.26M
      }
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
2.58M
    }
809
2.58M
  }
810
65.0k
out:
811
65.0k
  if(!result && skip_len)
812
60.5k
    result = rtp_write_body_junk(data, rtspc, buf - skip_len, skip_len);
813
65.0k
  return result;
814
65.0k
}
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
76.3k
{
831
76.3k
  struct rtsp_conn *rtspc =
832
76.3k
    Curl_conn_meta_get(data->conn, CURL_META_RTSP_CONN);
833
76.3k
  CURLcode result = CURLE_OK;
834
76.3k
  size_t consumed = 0;
835
836
76.3k
  if(!rtspc)
837
0
    return CURLE_FAILED_INIT;
838
839
76.3k
  if(!data->req.header)
840
1.21k
    rtspc->in_header = FALSE;
841
76.3k
  if(!blen) {
842
5.83k
    goto out;
843
5.83k
  }
844
845
70.5k
  DEBUGF(infof(data, "rtsp_rtp_write_resp(len=%zu, in_header=%d, eos=%d)",
846
70.5k
               blen, rtspc->in_header, is_eos));
847
848
  /* If header parsing is not ongoing, extract RTP messages */
849
70.5k
  if(!rtspc->in_header) {
850
46.3k
    result = rtsp_filter_rtp(data, rtspc, buf, blen, &consumed);
851
46.3k
    if(result)
852
16
      goto out;
853
46.3k
    buf += consumed;
854
46.3k
    blen -= consumed;
855
    /* either we consumed all or are at the start of header parsing */
856
46.3k
    if(blen && !data->req.header)
857
1
      DEBUGF(infof(data, "RTSP: %zu bytes, possibly excess in response body",
858
46.3k
                   blen));
859
46.3k
  }
860
861
  /* we want to parse headers, do so */
862
70.5k
  if(data->req.header && blen) {
863
46.0k
    rtspc->in_header = TRUE;
864
46.0k
    result = Curl_http_write_resp_hds(data, buf, blen, &consumed);
865
46.0k
    if(result)
866
1.28k
      goto out;
867
868
44.7k
    buf += consumed;
869
44.7k
    blen -= consumed;
870
871
44.7k
    if(!data->req.header)
872
18.6k
      rtspc->in_header = FALSE;
873
874
44.7k
    if(!rtspc->in_header) {
875
      /* If header parsing is done, extract interleaved RTP messages */
876
18.6k
      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
6.28k
        data->req.size = 0;
880
6.28k
        data->req.download_done = TRUE;
881
6.28k
      }
882
18.6k
      result = rtsp_filter_rtp(data, rtspc, buf, blen, &consumed);
883
18.6k
      if(result)
884
446
        goto out;
885
18.1k
      buf += consumed;
886
18.1k
      blen -= consumed;
887
18.1k
    }
888
44.7k
  }
889
890
68.7k
  if(rtspc->state != RTP_PARSE_SKIP)
891
2.51k
    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
68.7k
  DEBUGF(infof(data, "rtsp_rtp_write_resp(len=%zu, in_header=%d, done=%d, "
896
68.7k
               "rtspc->state=%d, req.size=%" FMT_OFF_T ")",
897
68.7k
               blen, rtspc->in_header, data->req.done, (int)rtspc->state,
898
68.7k
               data->req.size));
899
68.7k
  if(!result && (is_eos || blen)) {
900
291
    result = Curl_client_write(data, CLIENTWRITE_BODY |
901
291
                               (is_eos ? CLIENTWRITE_EOS : 0), buf, blen);
902
291
  }
903
904
76.3k
out:
905
76.3k
  if((data->set.rtspreq == RTSPREQ_RECEIVE) &&
906
51
     (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
12
    data->req.download_done = TRUE;
911
12
  }
912
76.3k
  return result;
913
68.7k
}
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
148k
{
968
148k
  if(checkprefix("CSeq:", header)) {
969
506
    curl_off_t CSeq = 0;
970
506
    struct RTSP *rtsp = Curl_meta_get(data, CURL_META_RTSP_EASY);
971
506
    const char *p = &header[5];
972
506
    if(!rtsp)
973
0
      return CURLE_FAILED_INIT;
974
506
    curlx_str_passblanks(&p);
975
506
    if(curlx_str_number(&p, &CSeq, UINT_MAX)) {
976
2
      failf(data, "Unable to read the CSeq header: [%s]", header);
977
2
      return CURLE_RTSP_CSEQ_ERROR;
978
2
    }
979
504
    data->state.rtsp_CSeq_recv = rtsp->CSeq_recv = (uint32_t)CSeq;
980
504
  }
981
148k
  else if(checkprefix("Session:", header)) {
982
1.05k
    const char *start, *end;
983
1.05k
    size_t idlen;
984
985
    /* Find the first non-space letter */
986
1.05k
    start = header + 8;
987
1.05k
    curlx_str_passblanks(&start);
988
989
1.05k
    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
1.05k
    end = start;
1001
5.36k
    while((*end > ' ') && (*end != ';'))
1002
4.31k
      end++;
1003
1.05k
    idlen = end - start;
1004
1005
1.05k
    if(data->set.str[STRING_RTSP_SESSION_ID]) {
1006
1007
      /* If the Session ID is set, then compare */
1008
933
      if(strlen(data->set.str[STRING_RTSP_SESSION_ID]) != idlen ||
1009
926
         strncmp(start, data->set.str[STRING_RTSP_SESSION_ID], idlen)) {
1010
98
        failf(data, "Got RTSP Session ID Line [%s], but wanted ID [%s]",
1011
98
              start, data->set.str[STRING_RTSP_SESSION_ID]);
1012
98
        return CURLE_RTSP_SESSION_ERROR;
1013
98
      }
1014
933
    }
1015
120
    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
120
      data->set.str[STRING_RTSP_SESSION_ID] = curlx_memdup0(start, idlen);
1022
120
      if(!data->set.str[STRING_RTSP_SESSION_ID])
1023
0
        return CURLE_OUT_OF_MEMORY;
1024
120
    }
1025
1.05k
  }
1026
147k
  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
148k
  return CURLE_OK;
1033
148k
}
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 */