Coverage Report

Created: 2025-12-14 06:23

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