Coverage Report

Created: 2025-11-15 08:43

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