Coverage Report

Created: 2026-12-01 06:24

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