Coverage Report

Created: 2026-10-15 06:17

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