Coverage Report

Created: 2026-09-01 06:58

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
                                unsigned char 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
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
0
{
282
0
  static const struct rtspselect req[] = {
283
0
    { "OPTIONS",       TRUE },
284
0
    { "DESCRIBE",      FALSE },
285
0
    { "ANNOUNCE",      TRUE },
286
0
    { "SETUP",         TRUE },
287
0
    { "PLAY",          TRUE },
288
0
    { "PAUSE",         TRUE },
289
0
    { "TEARDOWN",      TRUE },
290
0
    { "GET_PARAMETER", FALSE },
291
0
    { "SET_PARAMETER", TRUE },
292
0
    { "RECORD",        TRUE },
293
0
    { "", FALSE }, /* RECEIVE: treat interleaved RTP as body */
294
0
  };
295
  /* this is verified already in setopt, this is just added precaution */
296
0
  DEBUGASSERT((rtspreq > RTSPREQ_NONE) && (rtspreq < RTSPREQ_LAST));
297
0
  if((rtspreq <= RTSPREQ_NONE) || (rtspreq >= RTSPREQ_LAST))
298
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
299
0
  *p = req[rtspreq - 1].method;
300
0
  data->req.no_body = req[rtspreq - 1].no_body;
301
0
  return CURLE_OK;
302
0
}
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
0
{
309
0
  if(!value)
310
0
    return CURLE_OK;
311
0
  curlx_free(*target);
312
0
  *target = curl_maprintf("%s: %s\r\n", header_name, value);
313
0
  if(!*target)
314
0
    return CURLE_OUT_OF_MEMORY;
315
0
  return CURLE_OK;
316
0
}
317
318
struct rtsp_blocks {
319
  const char *request;
320
  const char *session_id;
321
  const char *accept;
322
  const char *range;
323
  const char *stream_uri;
324
  const char *hd_proxy_auth;
325
  const char *hd_auth;
326
  char *referrer;
327
  char *accept_encoding;
328
  char *transport;
329
  BIT(transport_alloc); /* if 'transport' is allocated */
330
};
331
332
static CURLcode rtsp_setup_request(struct Curl_easy *data,
333
                                   struct rtsp_blocks *b,
334
                                   const unsigned char rtspreq)
335
0
{
336
0
  CURLcode result = CURLE_OK;
337
0
  struct connectdata *conn = data->conn;
338
339
0
  b->session_id = CURL_EASY_STR(data, STRING_RTSP_SESSION_ID);
340
341
  /* Stream URI. Default to server '*' if not specified */
342
0
  if(CURL_EASY_STR(data, STRING_RTSP_STREAM_URI))
343
0
    b->stream_uri = CURL_EASY_STR(data, STRING_RTSP_STREAM_URI);
344
0
  else
345
0
    b->stream_uri = "*";
346
347
  /* Transport Header for SETUP requests */
348
0
  b->transport = Curl_checkheaders(data, STRCONST("Transport"));
349
0
  if(rtspreq == RTSPREQ_SETUP && !b->transport) {
350
    /* New Transport: setting? */
351
0
    if(CURL_EASY_STR(data, STRING_RTSP_TRANSPORT)) {
352
0
      result = rtsp_header_alloc(
353
0
        "Transport", CURL_EASY_STR(data, STRING_RTSP_TRANSPORT),
354
0
        &b->transport);
355
0
      if(result)
356
0
        return result;
357
0
      b->transport_alloc = TRUE;
358
0
    }
359
0
    else {
360
0
      failf(data,
361
0
            "Refusing to issue an RTSP SETUP without a Transport: header.");
362
0
      return CURLE_BAD_FUNCTION_ARGUMENT;
363
0
    }
364
0
  }
365
366
  /* Accept Headers for DESCRIBE requests */
367
0
  if(rtspreq == RTSPREQ_DESCRIBE) {
368
    /* Accept Header */
369
0
    b->accept = Curl_checkheaders(data, STRCONST("Accept")) ?
370
0
      NULL : "Accept: application/sdp\r\n";
371
372
    /* Accept-Encoding header */
373
0
    if(!Curl_checkheaders(data, STRCONST("Accept-Encoding")) &&
374
0
       CURL_EASY_STR(data, STRING_ENCODING)) {
375
0
      result = rtsp_header_alloc("Accept-Encoding",
376
0
                                 CURL_EASY_STR(data, STRING_ENCODING),
377
0
                                 &b->accept_encoding);
378
0
      if(result)
379
0
        return result;
380
0
    }
381
0
  }
382
383
  /* setup the authentication headers */
384
0
  result = Curl_http_output_auth(data, conn, b->request, HTTPREQ_GET,
385
0
                                 b->stream_uri, NULL, FALSE);
386
0
  if(result)
387
0
    return result;
388
389
0
#ifndef CURL_DISABLE_PROXY
390
0
  b->hd_proxy_auth = data->req.hd_proxy_auth;
391
0
#endif
392
0
  b->hd_auth = data->req.hd_auth;
393
394
  /* Referrer */
395
0
  if(Curl_bufref_ptr(&data->state.referer) &&
396
0
     !Curl_checkheaders(data, STRCONST("Referer"))) {
397
0
    b->referrer =
398
0
      curl_maprintf("Referer: %s\r\n", Curl_bufref_ptr(&data->state.referer));
399
0
    if(!b->referrer)
400
0
      result = CURLE_OUT_OF_MEMORY;
401
0
  }
402
403
  /*
404
   * Range Header
405
   * Only applies to PLAY, PAUSE, RECORD
406
   *
407
   * Go ahead and use the Range stuff supplied for HTTP
408
   */
409
0
  if(!result &&
410
0
     data->state.use_range &&
411
0
     ((rtspreq == RTSPREQ_PLAY) ||
412
0
      (rtspreq == RTSPREQ_PAUSE) ||
413
0
      (rtspreq == RTSPREQ_RECORD))) {
414
415
    /* Check to see if there is a range set in the custom headers */
416
0
    if(!Curl_checkheaders(data, STRCONST("Range")) && data->state.range) {
417
0
      result = rtsp_header_alloc("Range",
418
0
                                 data->state.range,
419
0
                                 &data->state.rangeline);
420
0
      if(!result)
421
0
        b->range = data->state.rangeline;
422
0
    }
423
0
  }
424
0
  return result;
425
0
}
426
427
0
#define HTTPVERSION 11 /* RTSP is close to HTTP/1.1, sort of... */
428
429
static CURLcode rtsp_do(struct Curl_easy *data, bool *done)
430
0
{
431
0
  CURLcode result = CURLE_OK;
432
0
  const unsigned char rtspreq = data->set.rtspreq;
433
0
  const char *str;
434
0
  struct RTSP *rtsp = Curl_meta_get(data, CURL_META_RTSP_EASY);
435
0
  struct dynbuf req_buffer;
436
0
  struct rtsp_blocks block;
437
0
  memset(&block, 0, sizeof(block));
438
439
0
  *done = TRUE;
440
0
  if(!rtsp)
441
0
    return CURLE_FAILED_INIT;
442
443
  /* Initialize a dynamic send buffer */
444
0
  curlx_dyn_init(&req_buffer, DYN_RTSP_REQ_HEADER);
445
446
0
  rtsp->CSeq_sent = data->state.rtsp_next_client_CSeq;
447
0
  rtsp->CSeq_recv = 0;
448
449
  /* Setup the 'p_request' pointer to the proper method. */
450
0
  result = pick_method(data, rtspreq, &block.request);
451
0
  if(result)
452
0
    goto out;
453
454
0
  if(rtspreq == RTSPREQ_RECEIVE) {
455
0
    Curl_xfer_setup_recv(data, FIRSTSOCKET, -1);
456
0
    goto out;
457
0
  }
458
459
0
  result = rtsp_setup_request(data, &block,  rtspreq);
460
0
  if(result)
461
0
    goto out;
462
  /*
463
   * Sanity check the custom headers
464
   */
465
0
  if(Curl_checkheaders(data, STRCONST("CSeq"))) {
466
0
    failf(data, "CSeq cannot be set as a custom header.");
467
0
    result = CURLE_RTSP_CSEQ_ERROR;
468
0
    goto out;
469
0
  }
470
0
  if(Curl_checkheaders(data, STRCONST("Session"))) {
471
0
    failf(data, "Session ID cannot be set as a custom header.");
472
0
    result = CURLE_BAD_FUNCTION_ARGUMENT;
473
0
    goto out;
474
0
  }
475
476
0
  result =
477
0
    curlx_dyn_addf(&req_buffer,
478
0
                   "%s %s RTSP/1.0\r\n" /* Request Stream-URI RTSP/1.0 */
479
0
                   "CSeq: %u\r\n", /* CSeq */
480
0
                   block.request, block.stream_uri, rtsp->CSeq_sent);
481
0
  if(result)
482
0
    goto out;
483
484
  /*
485
   * Rather than do a normal alloc line, keep the session_id unformatted
486
   * to make comparison easier
487
   */
488
0
  if(block.session_id) {
489
0
    result = curlx_dyn_addf(&req_buffer, "Session: %s\r\n", block.session_id);
490
0
    if(result)
491
0
      goto out;
492
0
  }
493
494
  /*
495
   * Shared HTTP-like options
496
   */
497
0
  result = curlx_dyn_addf(&req_buffer,
498
0
                          "%s" /* transport */
499
0
                          "%s" /* accept */
500
0
                          "%s" /* accept-encoding */
501
0
                          "%s" /* range */
502
0
                          "%s" /* referrer */
503
0
                          ,
504
0
                          block.transport ? block.transport : "",
505
0
                          block.accept ? block.accept : "",
506
0
                          block.accept_encoding ? block.accept_encoding : "",
507
0
                          block.range ? block.range : "",
508
0
                          block.referrer ? block.referrer : "");
509
510
0
  str = CURL_EASY_STR(data, STRING_USERAGENT);
511
0
  if(!result && str && *str &&
512
0
     !Curl_checkheaders(data, STRCONST("User-Agent")))
513
0
    result = curlx_dyn_addf(&req_buffer,
514
0
                            "User-Agent: %s\r\n", str);
515
516
0
  if(!result)
517
0
    result = curlx_dyn_addf(&req_buffer,
518
0
                            "%s" /* hd_proxy_auth */
519
0
                            "%s", /* hd_auth */
520
0
                            block.hd_proxy_auth ? block.hd_proxy_auth : "",
521
0
                            block.hd_auth ? block.hd_auth : "");
522
0
  if(result)
523
0
    goto out;
524
525
0
  if((rtspreq == RTSPREQ_SETUP) || (rtspreq == RTSPREQ_DESCRIBE)) {
526
0
    result = Curl_add_timecondition(data, &req_buffer);
527
0
    if(result)
528
0
      goto out;
529
0
  }
530
531
0
  result = Curl_add_custom_headers(data, FALSE, HTTPVERSION, &req_buffer);
532
0
  if(result)
533
0
    goto out;
534
535
0
  result = rtsp_setup_body(data, rtspreq, &req_buffer);
536
0
  if(result)
537
0
    goto out;
538
539
  /* Finish the request buffer */
540
0
  result = curlx_dyn_addn(&req_buffer, STRCONST("\r\n"));
541
0
  if(result)
542
0
    goto out;
543
544
0
  Curl_xfer_setup_sendrecv(data, FIRSTSOCKET, -1);
545
546
  /* issue the request */
547
0
  result = Curl_req_send(data, &req_buffer, HTTPVERSION);
548
0
  if(result) {
549
0
    failf(data, "Failed sending RTSP request");
550
0
    goto out;
551
0
  }
552
553
  /* Increment the CSeq on success */
554
0
  data->state.rtsp_next_client_CSeq++;
555
556
0
  if(data->req.writebytecount) {
557
    /* if a request-body has been sent off, we make sure this progress is
558
       noted properly */
559
0
    Curl_pgrsSetUploadCounter(data, data->req.writebytecount);
560
0
    result = Curl_pgrsUpdate(data);
561
0
  }
562
0
out:
563
0
  if(block.transport_alloc)
564
0
    curlx_free(block.transport);
565
0
  curlx_free(block.accept_encoding);
566
0
  curlx_free(block.referrer);
567
0
  curlx_dyn_free(&req_buffer);
568
0
  return result;
569
0
}
570
571
/**
572
 * write any BODY bytes missing to the client, ignore the rest.
573
 */
574
static CURLcode rtp_write_body_junk(struct Curl_easy *data,
575
                                    struct rtsp_conn *rtspc,
576
                                    const char *buf,
577
                                    size_t blen)
578
0
{
579
0
  curl_off_t body_remain;
580
0
  bool in_body;
581
582
0
  in_body = (data->req.headerline && !rtspc->in_header) &&
583
0
            (data->req.size >= 0) &&
584
0
            (data->req.bytecount < data->req.size);
585
0
  body_remain = in_body ? (data->req.size - data->req.bytecount) : 0;
586
0
  DEBUGASSERT(body_remain >= 0);
587
0
  if(body_remain) {
588
0
    if((curl_off_t)blen > body_remain)
589
0
      blen = (size_t)body_remain;
590
0
    return Curl_client_write(data, CLIENTWRITE_BODY, buf, blen);
591
0
  }
592
0
  return CURLE_OK;
593
0
}
594
595
static CURLcode rtp_client_write(struct Curl_easy *data, const char *ptr,
596
                                 size_t len)
597
0
{
598
0
  struct Curl_mapi_guard guard;
599
0
  size_t wrote;
600
0
  curl_write_callback writeit;
601
0
  void *user_ptr;
602
603
0
  if(len == 0) {
604
0
    failf(data, "Cannot write a 0 size RTP packet.");
605
0
    return CURLE_WRITE_ERROR;
606
0
  }
607
608
  /* If the user has configured CURLOPT_INTERLEAVEFUNCTION then use that
609
     function and any configured CURLOPT_INTERLEAVEDATA to write out the RTP
610
     data. Otherwise, use the CURLOPT_WRITEFUNCTION with the CURLOPT_WRITEDATA
611
     pointer to write out the RTP data. */
612
0
  if(data->set.fwrite_rtp) {
613
0
    writeit = data->set.fwrite_rtp;
614
0
    user_ptr = data->set.rtp_out;
615
0
  }
616
0
  else {
617
0
    writeit = data->set.fwrite_func;
618
0
    user_ptr = data->set.out;
619
0
  }
620
621
0
  CURL_CBAPI_START(&guard, data, easy_fwrite_rtp);
622
0
  wrote = writeit((char *)CURL_UNCONST(ptr), 1, len, user_ptr);
623
0
  CURL_CBAPI_END(&guard);
624
625
0
  if(wrote == CURL_WRITEFUNC_PAUSE) {
626
0
    failf(data, "Cannot pause RTP");
627
0
    return CURLE_WRITE_ERROR;
628
0
  }
629
630
0
  if(wrote != len) {
631
0
    failf(data, "Failed writing RTP data");
632
0
    return CURLE_WRITE_ERROR;
633
0
  }
634
635
0
  return CURLE_OK;
636
0
}
637
638
static CURLcode rtsp_filter_rtp(struct Curl_easy *data,
639
                                struct rtsp_conn *rtspc,
640
                                const char *buf,
641
                                size_t blen,
642
                                size_t *pconsumed)
643
0
{
644
0
  CURLcode result = CURLE_OK;
645
0
  size_t skip_len = 0;
646
647
0
  *pconsumed = 0;
648
0
  while(blen) {
649
0
    bool in_body = (data->req.headerline && !rtspc->in_header) &&
650
0
                   (data->req.size >= 0) &&
651
0
                   (data->req.bytecount < data->req.size);
652
0
    switch(rtspc->state) {
653
654
0
    case RTP_PARSE_SKIP: {
655
0
      DEBUGASSERT(curlx_dyn_len(&rtspc->buf) == 0);
656
0
      while(blen && buf[0] != '$') {
657
0
        if(!in_body && buf[0] == 'R' &&
658
0
           data->set.rtspreq != RTSPREQ_RECEIVE) {
659
0
          if(!strncmp(buf, "RTSP/", (blen < 5) ? blen : 5)) {
660
            /* This could be the next response, no consume and return */
661
0
            if(*pconsumed) {
662
0
              DEBUGF(infof(data, "RTP rtsp_filter_rtp[SKIP] RTSP/ prefix, "
663
0
                           "skipping %zu bytes of junk", *pconsumed));
664
0
            }
665
0
            rtspc->state = RTP_PARSE_SKIP;
666
0
            rtspc->in_header = TRUE;
667
0
            goto out;
668
0
          }
669
0
        }
670
        /* junk/BODY, consume without buffering */
671
0
        *pconsumed += 1;
672
0
        ++buf;
673
0
        --blen;
674
0
        ++skip_len;
675
0
      }
676
0
      if(blen && buf[0] == '$') {
677
        /* possible start of an RTP message, buffer */
678
0
        if(skip_len) {
679
          /* end of junk/BODY bytes, flush */
680
0
          result = rtp_write_body_junk(data, rtspc, buf - skip_len, skip_len);
681
0
          skip_len = 0;
682
0
          if(result)
683
0
            goto out;
684
0
        }
685
0
        if(curlx_dyn_addn(&rtspc->buf, buf, 1)) {
686
0
          result = CURLE_OUT_OF_MEMORY;
687
0
          goto out;
688
0
        }
689
0
        *pconsumed += 1;
690
0
        ++buf;
691
0
        --blen;
692
0
        rtspc->state = RTP_PARSE_CHANNEL;
693
0
      }
694
0
      break;
695
0
    }
696
697
0
    case RTP_PARSE_CHANNEL: {
698
0
      int idx = ((unsigned char)buf[0]) / 8;
699
0
      int off = ((unsigned char)buf[0]) % 8;
700
0
      DEBUGASSERT(curlx_dyn_len(&rtspc->buf) == 1);
701
0
      if(!(data->state.rtp_channel_mask[idx] & (1 << off))) {
702
        /* invalid channel number, junk or BODY data */
703
0
        rtspc->state = RTP_PARSE_SKIP;
704
0
        DEBUGASSERT(skip_len == 0);
705
        /* we do not consume this byte, it is BODY data */
706
0
        DEBUGF(infof(data, "RTSP: invalid RTP channel %d, skipping", idx));
707
0
        if(*pconsumed == 0) {
708
          /* We did not consume the initial '$' in our buffer, but had
709
           * it from an earlier call. We cannot un-consume it and have
710
           * to write it directly as BODY data */
711
0
          result = rtp_write_body_junk(data, rtspc,
712
0
                                       curlx_dyn_ptr(&rtspc->buf), 1);
713
0
          if(result)
714
0
            goto out;
715
0
        }
716
0
        else {
717
          /* count the '$' as skip and continue */
718
0
          skip_len = 1;
719
0
        }
720
0
        curlx_dyn_free(&rtspc->buf);
721
0
        break;
722
0
      }
723
      /* a valid channel, so we expect this to be a real RTP message */
724
0
      rtspc->rtp_channel = (unsigned char)buf[0];
725
0
      if(curlx_dyn_addn(&rtspc->buf, buf, 1)) {
726
0
        result = CURLE_OUT_OF_MEMORY;
727
0
        goto out;
728
0
      }
729
0
      *pconsumed += 1;
730
0
      ++buf;
731
0
      --blen;
732
0
      rtspc->state = RTP_PARSE_LEN;
733
0
      break;
734
0
    }
735
736
0
    case RTP_PARSE_LEN: {
737
0
      size_t rtp_len = curlx_dyn_len(&rtspc->buf);
738
0
      const char *rtp_buf;
739
0
      DEBUGASSERT(rtp_len >= 2 && rtp_len < 4);
740
0
      if(curlx_dyn_addn(&rtspc->buf, buf, 1)) {
741
0
        result = CURLE_OUT_OF_MEMORY;
742
0
        goto out;
743
0
      }
744
0
      *pconsumed += 1;
745
0
      ++buf;
746
0
      --blen;
747
0
      if(rtp_len == 2)
748
0
        break;
749
0
      rtp_buf = curlx_dyn_ptr(&rtspc->buf);
750
0
      rtspc->rtp_len = RTP_PKT_LENGTH(rtp_buf) + 4;
751
0
      if(rtspc->rtp_len == 4) {
752
        /* zero-length payload, the 4-byte header is the complete RTP
753
           message. Dispatch immediately without entering RTP_PARSE_DATA. */
754
0
        DEBUGF(infof(data, "RTP write channel %d rtp_len %zu (no payload)",
755
0
                     rtspc->rtp_channel, rtspc->rtp_len));
756
0
        result = rtp_client_write(data, rtp_buf, rtspc->rtp_len);
757
0
        curlx_dyn_free(&rtspc->buf);
758
0
        rtspc->state = RTP_PARSE_SKIP;
759
0
        if(result)
760
0
          goto out;
761
0
        break;
762
0
      }
763
0
      rtspc->state = RTP_PARSE_DATA;
764
0
      break;
765
0
    }
766
767
0
    case RTP_PARSE_DATA: {
768
0
      size_t rtp_len = curlx_dyn_len(&rtspc->buf);
769
0
      size_t needed;
770
0
      DEBUGASSERT(rtp_len < rtspc->rtp_len);
771
0
      needed = rtspc->rtp_len - rtp_len;
772
0
      if(needed <= blen) {
773
0
        if(curlx_dyn_addn(&rtspc->buf, buf, needed)) {
774
0
          result = CURLE_OUT_OF_MEMORY;
775
0
          goto out;
776
0
        }
777
0
        *pconsumed += needed;
778
0
        buf += needed;
779
0
        blen -= needed;
780
        /* complete RTP message in buffer */
781
0
        DEBUGF(infof(data, "RTP write channel %d rtp_len %zu",
782
0
                     rtspc->rtp_channel, rtspc->rtp_len));
783
0
        result = rtp_client_write(data, curlx_dyn_ptr(&rtspc->buf),
784
0
                                  rtspc->rtp_len);
785
0
        curlx_dyn_free(&rtspc->buf);
786
0
        rtspc->state = RTP_PARSE_SKIP;
787
0
        if(result)
788
0
          goto out;
789
0
      }
790
0
      else {
791
0
        if(curlx_dyn_addn(&rtspc->buf, buf, blen)) {
792
0
          result = CURLE_OUT_OF_MEMORY;
793
0
          goto out;
794
0
        }
795
0
        *pconsumed += blen;
796
0
        buf += blen;
797
0
        blen = 0;
798
0
      }
799
0
      break;
800
0
    }
801
802
0
    default:
803
0
      DEBUGASSERT(0);
804
0
      return CURLE_RECV_ERROR;
805
0
    }
806
0
  }
807
0
out:
808
0
  if(!result && skip_len)
809
0
    result = rtp_write_body_junk(data, rtspc, buf - skip_len, skip_len);
810
0
  return result;
811
0
}
812
813
/*
814
 * Parse and write out an RTSP response.
815
 * @param data     the transfer
816
 * @param conn     the connection
817
 * @param buf      data read from connection
818
 * @param blen     amount of data in buf
819
 * @param is_eos   TRUE iff this is the last write
820
 * @param readmore out, TRUE iff complete buf was consumed and more data
821
 *                 is needed
822
 */
823
static CURLcode rtsp_rtp_write_resp(struct Curl_easy *data,
824
                                    const char *buf,
825
                                    size_t blen,
826
                                    bool is_eos)
827
0
{
828
0
  struct rtsp_conn *rtspc =
829
0
    Curl_conn_meta_get(data->conn, CURL_META_RTSP_CONN);
830
0
  CURLcode result = CURLE_OK;
831
0
  size_t consumed = 0;
832
833
0
  if(!rtspc)
834
0
    return CURLE_FAILED_INIT;
835
836
0
  if(!data->req.header)
837
0
    rtspc->in_header = FALSE;
838
0
  if(!blen) {
839
0
    goto out;
840
0
  }
841
842
0
  DEBUGF(infof(data, "rtsp_rtp_write_resp(len=%zu, in_header=%d, eos=%d)",
843
0
               blen, rtspc->in_header, is_eos));
844
845
  /* If header parsing is not ongoing, extract RTP messages */
846
0
  if(!rtspc->in_header) {
847
0
    result = rtsp_filter_rtp(data, rtspc, buf, blen, &consumed);
848
0
    if(result)
849
0
      goto out;
850
0
    buf += consumed;
851
0
    blen -= consumed;
852
    /* either we consumed all or are at the start of header parsing */
853
0
    if(blen && !data->req.header)
854
0
      DEBUGF(infof(data, "RTSP: %zu bytes, possibly excess in response body",
855
0
                   blen));
856
0
  }
857
858
  /* we want to parse headers, do so */
859
0
  if(data->req.header && blen) {
860
0
    rtspc->in_header = TRUE;
861
0
    result = Curl_http_write_resp_hds(data, buf, blen, &consumed);
862
0
    if(result)
863
0
      goto out;
864
865
0
    buf += consumed;
866
0
    blen -= consumed;
867
868
0
    if(!data->req.header)
869
0
      rtspc->in_header = FALSE;
870
871
0
    if(!rtspc->in_header) {
872
      /* If header parsing is done, extract interleaved RTP messages */
873
0
      if(data->req.size <= -1) {
874
        /* Respect section 4.4 of rfc2326: If the Content-Length header is
875
           absent, a length 0 must be assumed. */
876
0
        data->req.size = 0;
877
0
        data->req.download_done = TRUE;
878
0
      }
879
0
      result = rtsp_filter_rtp(data, rtspc, buf, blen, &consumed);
880
0
      if(result)
881
0
        goto out;
882
0
      buf += consumed;
883
0
      blen -= consumed;
884
0
    }
885
0
  }
886
887
0
  if(rtspc->state != RTP_PARSE_SKIP)
888
0
    data->req.done = FALSE;
889
  /* we SHOULD have consumed all bytes, unless the response is borked.
890
   * In which case we write out the left over bytes, letting the client
891
   * writer deal with it (it will report EXCESS and fail the transfer). */
892
0
  DEBUGF(infof(data, "rtsp_rtp_write_resp(len=%zu, in_header=%d, done=%d, "
893
0
               "rtspc->state=%d, req.size=%" FMT_OFF_T ")",
894
0
               blen, rtspc->in_header, data->req.done, (int)rtspc->state,
895
0
               data->req.size));
896
0
  if(!result && (is_eos || blen)) {
897
0
    result = Curl_client_write(data, CLIENTWRITE_BODY |
898
0
                               (is_eos ? CLIENTWRITE_EOS : 0), buf, blen);
899
0
  }
900
901
0
out:
902
0
  if((data->set.rtspreq == RTSPREQ_RECEIVE) &&
903
0
     (rtspc->state == RTP_PARSE_SKIP)) {
904
    /* In special mode RECEIVE, we process one chunk of network
905
     * data, so we stop the transfer here, if we have no incomplete
906
     * RTP message pending. */
907
0
    data->req.download_done = TRUE;
908
0
  }
909
0
  return result;
910
0
}
911
912
static CURLcode rtsp_rtp_write_resp_hd(struct Curl_easy *data,
913
                                       const char *buf,
914
                                       size_t blen,
915
                                       bool is_eos)
916
0
{
917
0
  return rtsp_rtp_write_resp(data, buf, blen, is_eos);
918
0
}
919
920
static CURLcode rtsp_parse_transport(struct Curl_easy *data,
921
                                     const char *transport)
922
0
{
923
  /* If we receive multiple Transport response-headers, the interleaved
924
     channels of each response header is recorded and used together for
925
     subsequent data validity checks.*/
926
  /* e.g.: ' RTP/AVP/TCP;unicast;interleaved=5-6' */
927
0
  const char *start, *end;
928
0
  start = transport;
929
0
  while(start && *start) {
930
0
    curlx_str_passblanks(&start);
931
0
    end = strchr(start, ';');
932
0
    if(checkprefix("interleaved=", start)) {
933
0
      curl_off_t chan1, chan2, chan;
934
0
      const char *p = start + 12;
935
0
      if(!curlx_str_number(&p, &chan1, 255)) {
936
0
        unsigned char *rtp_channel_mask = data->state.rtp_channel_mask;
937
0
        chan2 = chan1;
938
0
        if(!curlx_str_single(&p, '-')) {
939
0
          if(curlx_str_number(&p, &chan2, 255)) {
940
0
            infof(data, "Unable to read the interleaved parameter from "
941
0
                  "Transport header: [%s]", transport);
942
0
            chan2 = chan1;
943
0
          }
944
0
        }
945
0
        for(chan = chan1; chan <= chan2; chan++) {
946
0
          int idx = (int)chan / 8;
947
0
          int off = (int)chan % 8;
948
0
          rtp_channel_mask[idx] |= (unsigned char)(1 << off);
949
0
        }
950
0
      }
951
0
      else {
952
0
        infof(data, "Unable to read the interleaved parameter from "
953
0
              "Transport header: [%s]", transport);
954
0
      }
955
0
      break;
956
0
    }
957
    /* skip to next parameter */
958
0
    start = (!end) ? end : (end + 1);
959
0
  }
960
0
  return CURLE_OK;
961
0
}
962
963
CURLcode Curl_rtsp_parseheader(struct Curl_easy *data, const char *header)
964
0
{
965
0
  if(checkprefix("CSeq:", header)) {
966
0
    curl_off_t CSeq = 0;
967
0
    struct RTSP *rtsp = Curl_meta_get(data, CURL_META_RTSP_EASY);
968
0
    const char *p = &header[5];
969
0
    if(!rtsp)
970
0
      return CURLE_FAILED_INIT;
971
0
    curlx_str_passblanks(&p);
972
0
    if(curlx_str_number(&p, &CSeq, UINT_MAX)) {
973
0
      failf(data, "Unable to read the CSeq header: [%s]", header);
974
0
      return CURLE_RTSP_CSEQ_ERROR;
975
0
    }
976
0
    data->state.rtsp_CSeq_recv = rtsp->CSeq_recv = (uint32_t)CSeq;
977
0
  }
978
0
  else if(checkprefix("Session:", header)) {
979
0
    const char *start, *end, *str;
980
0
    size_t idlen;
981
982
    /* Find the first non-space letter */
983
0
    start = header + 8;
984
0
    curlx_str_passblanks(&start);
985
986
0
    if(!*start) {
987
0
      failf(data, "Got a blank Session ID");
988
0
      return CURLE_RTSP_SESSION_ERROR;
989
0
    }
990
991
    /* Find the end of Session ID
992
     *
993
     * Allow any non whitespace content, up to the field separator or end of
994
     * line. RFC 2326 is not 100% clear on the session ID and for example
995
     * gstreamer does URL-encoded session ID's not covered by the standard.
996
     */
997
0
    end = start;
998
0
    while((*end > ' ') && (*end != ';'))
999
0
      end++;
1000
0
    idlen = end - start;
1001
1002
0
    str = CURL_EASY_STR(data, STRING_RTSP_SESSION_ID);
1003
0
    if(str) {
1004
1005
      /* If the Session ID is set, then compare */
1006
0
      if(strlen(str) != idlen ||
1007
0
         strncmp(start, str, idlen)) {
1008
0
        failf(data, "Got RTSP Session ID Line [%s], but wanted ID [%s]",
1009
0
              start, str);
1010
0
        return CURLE_RTSP_SESSION_ERROR;
1011
0
      }
1012
0
    }
1013
0
    else {
1014
      /* If the Session ID is not set, and we find it in a response, then set
1015
       * it.
1016
       * Copy the id substring into a new buffer */
1017
0
      void *mem = curlx_memdup0(start, idlen);
1018
0
      if(!mem ||
1019
0
         CURL_EASY_STR_SETN(data, STRING_RTSP_SESSION_ID, mem))
1020
0
        return CURLE_OUT_OF_MEMORY;
1021
0
    }
1022
0
  }
1023
0
  else if(checkprefix("Transport:", header)) {
1024
0
    CURLcode result;
1025
0
    result = rtsp_parse_transport(data, header + 10);
1026
0
    if(result)
1027
0
      return result;
1028
0
  }
1029
0
  return CURLE_OK;
1030
0
}
1031
1032
/*
1033
 * RTSP handler interface.
1034
 */
1035
const struct Curl_protocol Curl_protocol_rtsp = {
1036
  rtsp_setup_connection,                /* setup_connection */
1037
  rtsp_do,                              /* do_it */
1038
  rtsp_done,                            /* done */
1039
  ZERO_NULL,                            /* do_more */
1040
  rtsp_connect,                         /* connect_it */
1041
  ZERO_NULL,                            /* connecting */
1042
  ZERO_NULL,                            /* doing */
1043
  ZERO_NULL,                            /* proto_pollset */
1044
  rtsp_do_pollset,                      /* doing_pollset */
1045
  ZERO_NULL,                            /* domore_pollset */
1046
  Curl_http_perform_pollset,            /* perform_pollset */
1047
  ZERO_NULL,                            /* disconnect */
1048
  rtsp_rtp_write_resp,                  /* write_resp */
1049
  rtsp_rtp_write_resp_hd,               /* write_resp_hd */
1050
  rtsp_conn_is_dead,                    /* connection_is_dead */
1051
  ZERO_NULL,                            /* attach connection */
1052
  Curl_http_follow,                     /* follow */
1053
};
1054
1055
#endif /* CURL_DISABLE_RTSP */