Coverage Report

Created: 2025-08-26 07:08

/src/PROJ/curl/lib/rtsp.c
Line
Count
Source (jump to first uncovered line)
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 "curlx/strparse.h"
44
/* The last 3 #include files should be in this order */
45
#include "curl_printf.h"
46
#include "curl_memory.h"
47
#include "memdebug.h"
48
49
50
/* meta key for storing protocol meta at easy handle */
51
0
#define CURL_META_RTSP_EASY   "meta:proto:rtsp:easy"
52
/* meta key for storing protocol meta at connection */
53
0
#define CURL_META_RTSP_CONN   "meta:proto:rtsp:conn"
54
55
typedef enum {
56
  RTP_PARSE_SKIP,
57
  RTP_PARSE_CHANNEL,
58
  RTP_PARSE_LEN,
59
  RTP_PARSE_DATA
60
} rtp_parse_st;
61
62
/* RTSP Connection data
63
 * Currently, only used for tracking incomplete RTP data reads */
64
struct rtsp_conn {
65
  struct dynbuf buf;
66
  int rtp_channel;
67
  size_t rtp_len;
68
  rtp_parse_st state;
69
  BIT(in_header);
70
};
71
72
/* RTSP transfer data */
73
struct RTSP {
74
  long CSeq_sent; /* CSeq of this request */
75
  long CSeq_recv; /* CSeq received */
76
};
77
78
79
0
#define RTP_PKT_LENGTH(p) ((((unsigned int)((unsigned char)((p)[2]))) << 8) | \
80
0
                            ((unsigned int)((unsigned char)((p)[3]))))
81
82
/* protocol-specific functions set up to be called by the main engine */
83
static CURLcode rtsp_do(struct Curl_easy *data, bool *done);
84
static CURLcode rtsp_done(struct Curl_easy *data, CURLcode, bool premature);
85
static CURLcode rtsp_connect(struct Curl_easy *data, bool *done);
86
static CURLcode rtsp_do_pollset(struct Curl_easy *data,
87
                                struct easy_pollset *ps);
88
89
/*
90
 * Parse and write out an RTSP response.
91
 * @param data     the transfer
92
 * @param conn     the connection
93
 * @param buf      data read from connection
94
 * @param blen     amount of data in buf
95
 * @param is_eos   TRUE iff this is the last write
96
 * @param readmore out, TRUE iff complete buf was consumed and more data
97
 *                 is needed
98
 */
99
static CURLcode rtsp_rtp_write_resp(struct Curl_easy *data,
100
                                    const char *buf,
101
                                    size_t blen,
102
                                    bool is_eos);
103
static CURLcode rtsp_rtp_write_resp_hd(struct Curl_easy *data,
104
                                       const char *buf,
105
                                       size_t blen,
106
                                       bool is_eos);
107
108
static CURLcode rtsp_setup_connection(struct Curl_easy *data,
109
                                      struct connectdata *conn);
110
static unsigned int rtsp_conncheck(struct Curl_easy *data,
111
                                   struct connectdata *check,
112
                                   unsigned int checks_to_perform);
113
114
/* this returns the socket to wait for in the DO and DOING state for the multi
115
   interface and then we are always _sending_ a request and thus we wait for
116
   the single socket to become writable only */
117
static CURLcode rtsp_do_pollset(struct Curl_easy *data,
118
                                struct easy_pollset *ps)
119
0
{
120
  /* write mode */
121
0
  return Curl_pollset_add_out(data, ps, data->conn->sock[FIRSTSOCKET]);
122
0
}
123
124
static
125
CURLcode rtp_client_write(struct Curl_easy *data, const char *ptr, size_t len);
126
static
127
CURLcode rtsp_parse_transport(struct Curl_easy *data, const char *transport);
128
129
130
/*
131
 * RTSP handler interface.
132
 */
133
const struct Curl_handler Curl_handler_rtsp = {
134
  "rtsp",                               /* scheme */
135
  rtsp_setup_connection,                /* setup_connection */
136
  rtsp_do,                              /* do_it */
137
  rtsp_done,                            /* done */
138
  ZERO_NULL,                            /* do_more */
139
  rtsp_connect,                         /* connect_it */
140
  ZERO_NULL,                            /* connecting */
141
  ZERO_NULL,                            /* doing */
142
  ZERO_NULL,                            /* proto_pollset */
143
  rtsp_do_pollset,                      /* doing_pollset */
144
  ZERO_NULL,                            /* domore_pollset */
145
  ZERO_NULL,                            /* perform_pollset */
146
  ZERO_NULL,                            /* disconnect */
147
  rtsp_rtp_write_resp,                  /* write_resp */
148
  rtsp_rtp_write_resp_hd,               /* write_resp_hd */
149
  rtsp_conncheck,                       /* connection_check */
150
  ZERO_NULL,                            /* attach connection */
151
  Curl_http_follow,                     /* follow */
152
  PORT_RTSP,                            /* defport */
153
  CURLPROTO_RTSP,                       /* protocol */
154
  CURLPROTO_RTSP,                       /* family */
155
  PROTOPT_NONE                          /* flags */
156
};
157
158
0
#define MAX_RTP_BUFFERSIZE 1000000 /* arbitrary */
159
160
static void rtsp_easy_dtor(void *key, size_t klen, void *entry)
161
0
{
162
0
  struct RTSP *rtsp = entry;
163
0
  (void)key;
164
0
  (void)klen;
165
0
  free(rtsp);
166
0
}
167
168
static void rtsp_conn_dtor(void *key, size_t klen, void *entry)
169
0
{
170
0
  struct rtsp_conn *rtspc = entry;
171
0
  (void)key;
172
0
  (void)klen;
173
0
  curlx_dyn_free(&rtspc->buf);
174
0
  free(rtspc);
175
0
}
176
177
static CURLcode rtsp_setup_connection(struct Curl_easy *data,
178
                                      struct connectdata *conn)
179
0
{
180
0
  struct rtsp_conn *rtspc;
181
0
  struct RTSP *rtsp;
182
183
0
  rtspc = calloc(1, sizeof(*rtspc));
184
0
  if(!rtspc)
185
0
    return CURLE_OUT_OF_MEMORY;
186
0
  curlx_dyn_init(&rtspc->buf, MAX_RTP_BUFFERSIZE);
187
0
  if(Curl_conn_meta_set(conn, CURL_META_RTSP_CONN, rtspc, rtsp_conn_dtor))
188
0
    return CURLE_OUT_OF_MEMORY;
189
190
0
  rtsp = calloc(1, sizeof(struct RTSP));
191
0
  if(!rtsp ||
192
0
     Curl_meta_set(data, CURL_META_RTSP_EASY, rtsp, rtsp_easy_dtor))
193
0
    return CURLE_OUT_OF_MEMORY;
194
195
0
  return CURLE_OK;
196
0
}
197
198
199
/*
200
 * Function to check on various aspects of a connection.
201
 */
202
static unsigned int rtsp_conncheck(struct Curl_easy *data,
203
                                   struct connectdata *conn,
204
                                   unsigned int checks_to_perform)
205
0
{
206
0
  unsigned int ret_val = CONNRESULT_NONE;
207
0
  (void)data;
208
209
0
  if(checks_to_perform & CONNCHECK_ISDEAD) {
210
0
    bool input_pending;
211
0
    if(!Curl_conn_is_alive(data, conn, &input_pending))
212
0
      ret_val |= CONNRESULT_DEAD;
213
0
  }
214
215
0
  return ret_val;
216
0
}
217
218
219
static CURLcode rtsp_connect(struct Curl_easy *data, bool *done)
220
0
{
221
0
  struct rtsp_conn *rtspc =
222
0
    Curl_conn_meta_get(data->conn, CURL_META_RTSP_CONN);
223
0
  CURLcode httpStatus;
224
225
0
  if(!rtspc)
226
0
    return CURLE_FAILED_INIT;
227
228
0
  httpStatus = Curl_http_connect(data, done);
229
230
  /* Initialize the CSeq if not already done */
231
0
  if(data->state.rtsp_next_client_CSeq == 0)
232
0
    data->state.rtsp_next_client_CSeq = 1;
233
0
  if(data->state.rtsp_next_server_CSeq == 0)
234
0
    data->state.rtsp_next_server_CSeq = 1;
235
236
0
  rtspc->rtp_channel = -1;
237
238
0
  return httpStatus;
239
0
}
240
241
static CURLcode rtsp_done(struct Curl_easy *data,
242
                          CURLcode status, bool premature)
243
0
{
244
0
  struct rtsp_conn *rtspc =
245
0
    Curl_conn_meta_get(data->conn, CURL_META_RTSP_CONN);
246
0
  struct RTSP *rtsp = Curl_meta_get(data, CURL_META_RTSP_EASY);
247
0
  CURLcode httpStatus;
248
249
0
  if(!rtspc || !rtsp)
250
0
    return CURLE_FAILED_INIT;
251
252
  /* Bypass HTTP empty-reply checks on receive */
253
0
  if(data->set.rtspreq == RTSPREQ_RECEIVE)
254
0
    premature = TRUE;
255
256
0
  httpStatus = Curl_http_done(data, status, premature);
257
258
0
  if(!status && !httpStatus) {
259
    /* Check the sequence numbers */
260
0
    long CSeq_sent = rtsp->CSeq_sent;
261
0
    long CSeq_recv = rtsp->CSeq_recv;
262
0
    if((data->set.rtspreq != RTSPREQ_RECEIVE) && (CSeq_sent != CSeq_recv)) {
263
0
      failf(data,
264
0
            "The CSeq of this request %ld did not match the response %ld",
265
0
            CSeq_sent, CSeq_recv);
266
0
      return CURLE_RTSP_CSEQ_ERROR;
267
0
    }
268
0
    if(data->set.rtspreq == RTSPREQ_RECEIVE && (rtspc->rtp_channel == -1)) {
269
0
      infof(data, "Got an RTP Receive with a CSeq of %ld", CSeq_recv);
270
0
    }
271
0
    if(data->set.rtspreq == RTSPREQ_RECEIVE &&
272
0
       data->req.eos_written) {
273
0
      failf(data, "Server prematurely closed the RTSP connection.");
274
0
      return CURLE_RECV_ERROR;
275
0
    }
276
0
  }
277
278
0
  return httpStatus;
279
0
}
280
281
static CURLcode rtsp_do(struct Curl_easy *data, bool *done)
282
0
{
283
0
  struct connectdata *conn = data->conn;
284
0
  CURLcode result = CURLE_OK;
285
0
  Curl_RtspReq rtspreq = data->set.rtspreq;
286
0
  struct RTSP *rtsp = Curl_meta_get(data, CURL_META_RTSP_EASY);
287
0
  struct dynbuf req_buffer;
288
0
  unsigned char httpversion = 11; /* RTSP is close to HTTP/1.1, sort of... */
289
290
0
  const char *p_request = NULL;
291
0
  const char *p_session_id = NULL;
292
0
  const char *p_accept = NULL;
293
0
  const char *p_accept_encoding = NULL;
294
0
  const char *p_range = NULL;
295
0
  const char *p_referrer = NULL;
296
0
  const char *p_stream_uri = NULL;
297
0
  const char *p_transport = NULL;
298
0
  const char *p_uagent = NULL;
299
0
  const char *p_proxyuserpwd = NULL;
300
0
  const char *p_userpwd = NULL;
301
302
0
  *done = TRUE;
303
0
  if(!rtsp)
304
0
    return CURLE_FAILED_INIT;
305
306
  /* Initialize a dynamic send buffer */
307
0
  curlx_dyn_init(&req_buffer, DYN_RTSP_REQ_HEADER);
308
309
0
  rtsp->CSeq_sent = data->state.rtsp_next_client_CSeq;
310
0
  rtsp->CSeq_recv = 0;
311
312
  /* Setup the first_* fields to allow auth details get sent
313
     to this origin */
314
315
0
  if(!data->state.first_host) {
316
0
    data->state.first_host = strdup(conn->host.name);
317
0
    if(!data->state.first_host)
318
0
      return CURLE_OUT_OF_MEMORY;
319
320
0
    data->state.first_remote_port = conn->remote_port;
321
0
    data->state.first_remote_protocol = conn->handler->protocol;
322
0
  }
323
324
  /* Setup the 'p_request' pointer to the proper p_request string
325
   * Since all RTSP requests are included here, there is no need to
326
   * support custom requests like HTTP.
327
   **/
328
0
  data->req.no_body = TRUE; /* most requests do not contain a body */
329
0
  switch(rtspreq) {
330
0
  default:
331
0
    failf(data, "Got invalid RTSP request");
332
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
333
0
  case RTSPREQ_OPTIONS:
334
0
    p_request = "OPTIONS";
335
0
    break;
336
0
  case RTSPREQ_DESCRIBE:
337
0
    p_request = "DESCRIBE";
338
0
    data->req.no_body = FALSE;
339
0
    break;
340
0
  case RTSPREQ_ANNOUNCE:
341
0
    p_request = "ANNOUNCE";
342
0
    break;
343
0
  case RTSPREQ_SETUP:
344
0
    p_request = "SETUP";
345
0
    break;
346
0
  case RTSPREQ_PLAY:
347
0
    p_request = "PLAY";
348
0
    break;
349
0
  case RTSPREQ_PAUSE:
350
0
    p_request = "PAUSE";
351
0
    break;
352
0
  case RTSPREQ_TEARDOWN:
353
0
    p_request = "TEARDOWN";
354
0
    break;
355
0
  case RTSPREQ_GET_PARAMETER:
356
    /* GET_PARAMETER's no_body status is determined later */
357
0
    p_request = "GET_PARAMETER";
358
0
    data->req.no_body = FALSE;
359
0
    break;
360
0
  case RTSPREQ_SET_PARAMETER:
361
0
    p_request = "SET_PARAMETER";
362
0
    break;
363
0
  case RTSPREQ_RECORD:
364
0
    p_request = "RECORD";
365
0
    break;
366
0
  case RTSPREQ_RECEIVE:
367
0
    p_request = "";
368
    /* Treat interleaved RTP as body */
369
0
    data->req.no_body = FALSE;
370
0
    break;
371
0
  case RTSPREQ_LAST:
372
0
    failf(data, "Got invalid RTSP request: RTSPREQ_LAST");
373
0
    return CURLE_BAD_FUNCTION_ARGUMENT;
374
0
  }
375
376
0
  if(rtspreq == RTSPREQ_RECEIVE) {
377
0
    Curl_xfer_setup_recv(data, FIRSTSOCKET, -1);
378
0
    goto out;
379
0
  }
380
381
0
  p_session_id = data->set.str[STRING_RTSP_SESSION_ID];
382
0
  if(!p_session_id &&
383
0
     (rtspreq & ~(Curl_RtspReq)(RTSPREQ_OPTIONS |
384
0
                                RTSPREQ_DESCRIBE |
385
0
                                RTSPREQ_SETUP))) {
386
0
    failf(data, "Refusing to issue an RTSP request [%s] without a session ID.",
387
0
          p_request);
388
0
    result = CURLE_BAD_FUNCTION_ARGUMENT;
389
0
    goto out;
390
0
  }
391
392
  /* Stream URI. Default to server '*' if not specified */
393
0
  if(data->set.str[STRING_RTSP_STREAM_URI]) {
394
0
    p_stream_uri = data->set.str[STRING_RTSP_STREAM_URI];
395
0
  }
396
0
  else {
397
0
    p_stream_uri = "*";
398
0
  }
399
400
  /* Transport Header for SETUP requests */
401
0
  p_transport = Curl_checkheaders(data, STRCONST("Transport"));
402
0
  if(rtspreq == RTSPREQ_SETUP && !p_transport) {
403
    /* New Transport: setting? */
404
0
    if(data->set.str[STRING_RTSP_TRANSPORT]) {
405
0
      free(data->state.aptr.rtsp_transport);
406
0
      data->state.aptr.rtsp_transport =
407
0
        aprintf("Transport: %s\r\n",
408
0
                data->set.str[STRING_RTSP_TRANSPORT]);
409
0
      if(!data->state.aptr.rtsp_transport)
410
0
        return CURLE_OUT_OF_MEMORY;
411
0
    }
412
0
    else {
413
0
      failf(data,
414
0
            "Refusing to issue an RTSP SETUP without a Transport: header.");
415
0
      result = CURLE_BAD_FUNCTION_ARGUMENT;
416
0
      goto out;
417
0
    }
418
419
0
    p_transport = data->state.aptr.rtsp_transport;
420
0
  }
421
422
  /* Accept Headers for DESCRIBE requests */
423
0
  if(rtspreq == RTSPREQ_DESCRIBE) {
424
    /* Accept Header */
425
0
    p_accept = Curl_checkheaders(data, STRCONST("Accept")) ?
426
0
      NULL : "Accept: application/sdp\r\n";
427
428
    /* Accept-Encoding header */
429
0
    if(!Curl_checkheaders(data, STRCONST("Accept-Encoding")) &&
430
0
       data->set.str[STRING_ENCODING]) {
431
0
      free(data->state.aptr.accept_encoding);
432
0
      data->state.aptr.accept_encoding =
433
0
        aprintf("Accept-Encoding: %s\r\n", data->set.str[STRING_ENCODING]);
434
435
0
      if(!data->state.aptr.accept_encoding) {
436
0
        result = CURLE_OUT_OF_MEMORY;
437
0
        goto out;
438
0
      }
439
0
      p_accept_encoding = data->state.aptr.accept_encoding;
440
0
    }
441
0
  }
442
443
  /* The User-Agent string might have been allocated in url.c already, because
444
     it might have been used in the proxy connect, but if we have got a header
445
     with the user-agent string specified, we erase the previously made string
446
     here. */
447
0
  if(Curl_checkheaders(data, STRCONST("User-Agent")) &&
448
0
     data->state.aptr.uagent) {
449
0
    Curl_safefree(data->state.aptr.uagent);
450
0
  }
451
0
  else if(!Curl_checkheaders(data, STRCONST("User-Agent")) &&
452
0
          data->set.str[STRING_USERAGENT]) {
453
0
    p_uagent = data->state.aptr.uagent;
454
0
  }
455
456
  /* setup the authentication headers */
457
0
  result = Curl_http_output_auth(data, conn, p_request, HTTPREQ_GET,
458
0
                                 p_stream_uri, FALSE);
459
0
  if(result)
460
0
    goto out;
461
462
0
#ifndef CURL_DISABLE_PROXY
463
0
  p_proxyuserpwd = data->state.aptr.proxyuserpwd;
464
0
#endif
465
0
  p_userpwd = data->state.aptr.userpwd;
466
467
  /* Referrer */
468
0
  Curl_safefree(data->state.aptr.ref);
469
0
  if(data->state.referer && !Curl_checkheaders(data, STRCONST("Referer")))
470
0
    data->state.aptr.ref = aprintf("Referer: %s\r\n", data->state.referer);
471
472
0
  p_referrer = data->state.aptr.ref;
473
474
  /*
475
   * Range Header
476
   * Only applies to PLAY, PAUSE, RECORD
477
   *
478
   * Go ahead and use the Range stuff supplied for HTTP
479
   */
480
0
  if(data->state.use_range &&
481
0
     (rtspreq  & (RTSPREQ_PLAY | RTSPREQ_PAUSE | RTSPREQ_RECORD))) {
482
483
    /* Check to see if there is a range set in the custom headers */
484
0
    if(!Curl_checkheaders(data, STRCONST("Range")) && data->state.range) {
485
0
      free(data->state.aptr.rangeline);
486
0
      data->state.aptr.rangeline = aprintf("Range: %s\r\n", data->state.range);
487
0
      p_range = data->state.aptr.rangeline;
488
0
    }
489
0
  }
490
491
  /*
492
   * Sanity check the custom headers
493
   */
494
0
  if(Curl_checkheaders(data, STRCONST("CSeq"))) {
495
0
    failf(data, "CSeq cannot be set as a custom header.");
496
0
    result = CURLE_RTSP_CSEQ_ERROR;
497
0
    goto out;
498
0
  }
499
0
  if(Curl_checkheaders(data, STRCONST("Session"))) {
500
0
    failf(data, "Session ID cannot be set as a custom header.");
501
0
    result = CURLE_BAD_FUNCTION_ARGUMENT;
502
0
    goto out;
503
0
  }
504
505
0
  result =
506
0
    curlx_dyn_addf(&req_buffer,
507
0
                   "%s %s RTSP/1.0\r\n" /* Request Stream-URI RTSP/1.0 */
508
0
                   "CSeq: %ld\r\n", /* CSeq */
509
0
                   p_request, p_stream_uri, rtsp->CSeq_sent);
510
0
  if(result)
511
0
    goto out;
512
513
  /*
514
   * Rather than do a normal alloc line, keep the session_id unformatted
515
   * to make comparison easier
516
   */
517
0
  if(p_session_id) {
518
0
    result = curlx_dyn_addf(&req_buffer, "Session: %s\r\n", p_session_id);
519
0
    if(result)
520
0
      goto out;
521
0
  }
522
523
  /*
524
   * Shared HTTP-like options
525
   */
526
0
  result = curlx_dyn_addf(&req_buffer,
527
0
                          "%s" /* transport */
528
0
                          "%s" /* accept */
529
0
                          "%s" /* accept-encoding */
530
0
                          "%s" /* range */
531
0
                          "%s" /* referrer */
532
0
                          "%s" /* user-agent */
533
0
                          "%s" /* proxyuserpwd */
534
0
                          "%s" /* userpwd */
535
0
                          ,
536
0
                          p_transport ? p_transport : "",
537
0
                          p_accept ? p_accept : "",
538
0
                          p_accept_encoding ? p_accept_encoding : "",
539
0
                          p_range ? p_range : "",
540
0
                          p_referrer ? p_referrer : "",
541
0
                          p_uagent ? p_uagent : "",
542
0
                          p_proxyuserpwd ? p_proxyuserpwd : "",
543
0
                          p_userpwd ? p_userpwd : "");
544
545
  /*
546
   * Free userpwd now --- cannot reuse this for Negotiate and possibly NTLM
547
   * with basic and digest, it will be freed anyway by the next request
548
   */
549
0
  Curl_safefree(data->state.aptr.userpwd);
550
551
0
  if(result)
552
0
    goto out;
553
554
0
  if((rtspreq == RTSPREQ_SETUP) || (rtspreq == RTSPREQ_DESCRIBE)) {
555
0
    result = Curl_add_timecondition(data, &req_buffer);
556
0
    if(result)
557
0
      goto out;
558
0
  }
559
560
0
  result = Curl_add_custom_headers(data, FALSE, httpversion, &req_buffer);
561
0
  if(result)
562
0
    goto out;
563
564
0
  if(rtspreq == RTSPREQ_ANNOUNCE ||
565
0
     rtspreq == RTSPREQ_SET_PARAMETER ||
566
0
     rtspreq == RTSPREQ_GET_PARAMETER) {
567
0
    curl_off_t req_clen; /* request content length */
568
569
0
    if(data->state.upload) {
570
0
      req_clen = data->state.infilesize;
571
0
      data->state.httpreq = HTTPREQ_PUT;
572
0
      result = Curl_creader_set_fread(data, req_clen);
573
0
      if(result)
574
0
        goto out;
575
0
    }
576
0
    else {
577
0
      if(data->set.postfields) {
578
0
        size_t plen = strlen(data->set.postfields);
579
0
        req_clen = (curl_off_t)plen;
580
0
        result = Curl_creader_set_buf(data, data->set.postfields, plen);
581
0
      }
582
0
      else if(data->state.infilesize >= 0) {
583
0
        req_clen = data->state.infilesize;
584
0
        result = Curl_creader_set_fread(data, req_clen);
585
0
      }
586
0
      else {
587
0
        req_clen = 0;
588
0
        result = Curl_creader_set_null(data);
589
0
      }
590
0
      if(result)
591
0
        goto out;
592
0
    }
593
594
0
    if(req_clen > 0) {
595
      /* As stated in the http comments, it is probably not wise to
596
       * actually set a custom Content-Length in the headers */
597
0
      if(!Curl_checkheaders(data, STRCONST("Content-Length"))) {
598
0
        result =
599
0
          curlx_dyn_addf(&req_buffer, "Content-Length: %" FMT_OFF_T"\r\n",
600
0
                         req_clen);
601
0
        if(result)
602
0
          goto out;
603
0
      }
604
605
0
      if(rtspreq == RTSPREQ_SET_PARAMETER ||
606
0
         rtspreq == RTSPREQ_GET_PARAMETER) {
607
0
        if(!Curl_checkheaders(data, STRCONST("Content-Type"))) {
608
0
          result = curlx_dyn_addn(&req_buffer,
609
0
                                  STRCONST("Content-Type: "
610
0
                                           "text/parameters\r\n"));
611
0
          if(result)
612
0
            goto out;
613
0
        }
614
0
      }
615
616
0
      if(rtspreq == RTSPREQ_ANNOUNCE) {
617
0
        if(!Curl_checkheaders(data, STRCONST("Content-Type"))) {
618
0
          result = curlx_dyn_addn(&req_buffer,
619
0
                                  STRCONST("Content-Type: "
620
0
                                           "application/sdp\r\n"));
621
0
          if(result)
622
0
            goto out;
623
0
        }
624
0
      }
625
0
    }
626
0
    else if(rtspreq == RTSPREQ_GET_PARAMETER) {
627
      /* Check for an empty GET_PARAMETER (heartbeat) request */
628
0
      data->state.httpreq = HTTPREQ_HEAD;
629
0
      data->req.no_body = TRUE;
630
0
    }
631
0
  }
632
0
  else {
633
0
    result = Curl_creader_set_null(data);
634
0
    if(result)
635
0
      goto out;
636
0
  }
637
638
  /* Finish the request buffer */
639
0
  result = curlx_dyn_addn(&req_buffer, STRCONST("\r\n"));
640
0
  if(result)
641
0
    goto out;
642
643
0
  Curl_xfer_setup_sendrecv(data, FIRSTSOCKET, -1);
644
645
  /* issue the request */
646
0
  result = Curl_req_send(data, &req_buffer, httpversion);
647
0
  if(result) {
648
0
    failf(data, "Failed sending RTSP request");
649
0
    goto out;
650
0
  }
651
652
  /* Increment the CSeq on success */
653
0
  data->state.rtsp_next_client_CSeq++;
654
655
0
  if(data->req.writebytecount) {
656
    /* if a request-body has been sent off, we make sure this progress is
657
       noted properly */
658
0
    Curl_pgrsSetUploadCounter(data, data->req.writebytecount);
659
0
    if(Curl_pgrsUpdate(data))
660
0
      result = CURLE_ABORTED_BY_CALLBACK;
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
951
CURLcode rtp_client_write(struct Curl_easy *data, const char *ptr, 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
1063
CURLcode rtsp_parse_transport(struct Curl_easy *data, 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
1106
#endif /* CURL_DISABLE_RTSP */