FFmpeg
Loading...
Searching...
No Matches
rtc.c
Go to the documentation of this file.
1/*
2 * Shared WebRTC helpers
3 * Copyright (c) 2023 The FFmpeg Project
4 *
5 * This file is part of FFmpeg.
6 *
7 * FFmpeg is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU Lesser General Public
9 * License as published by the Free Software Foundation; either
10 * version 2.1 of the License, or (at your option) any later version.
11 *
12 * FFmpeg is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * Lesser General Public License for more details.
16 *
17 * You should have received a copy of the GNU Lesser General Public
18 * License along with FFmpeg; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22#include "libavutil/avstring.h"
23#include "libavutil/base64.h"
24#include "libavutil/bprint.h"
25#include "libavutil/crc.h"
26#include "libavutil/hmac.h"
28#include "libavutil/mem.h"
30#include "libavutil/time.h"
31
32#include "avio_internal.h"
33#include "http.h"
34#include "internal.h"
35#include "network.h"
36#include "rtc.h"
37#include "tls.h"
38
39/**
40 * If we try to read from UDP and get EAGAIN, we sleep for 5ms and retry up to 10 times.
41 * This will limit the total duration (in milliseconds, 50ms)
42 */
43#define RTC_ICE_DTLS_READ_MAX_RETRY 10
44#define RTC_ICE_DTLS_READ_SLEEP_DURATION 5
45
46/* The magic cookie for Session Traversal Utilities for NAT (STUN) messages. */
47#define STUN_MAGIC_COOKIE 0x2112A442
48
49/**
50 * Refer to RFC 8445 5.1.2
51 * priority = (2^24)*(type preference) + (2^8)*(local preference) + (2^0)*(256 - component ID)
52 * host candidate priority is 126 << 24 | 65535 << 8 | 255
53 */
54#define STUN_HOST_CANDIDATE_PRIORITY 126 << 24 | 65535 << 8 | 255
55
56/**
57 * The STUN message header, which is 20 bytes long, comprises the
58 * STUNMessageType (1B), MessageLength (2B), MagicCookie (4B),
59 * and TransactionID (12B).
60 * See https://datatracker.ietf.org/doc/html/rfc5389#section-6
61 */
62#define RTC_ICE_STUN_HEADER_SIZE 20
63
64/**
65 * For RTCP, PT is [128, 223] (or without marker [0, 95]). Literally, RTCP starts
66 * from 64 not 0, so PT is [192, 223] (or without marker [64, 95]), see "RTCP Control
67 * Packet Types (PT)" at
68 * https://www.iana.org/assignments/rtp-parameters/rtp-parameters.xhtml#rtp-parameters-4
69 *
70 * For RTP, the PT is [96, 127], or [224, 255] with marker. See "RTP Payload Types (PT)
71 * for standard audio and video encodings" at
72 * https://www.iana.org/assignments/rtp-parameters/rtp-parameters.xhtml#rtp-parameters-1
73 */
74#define RTC_RTCP_PT_START 192
75#define RTC_RTCP_PT_END 223
76
77/**
78 * Refer to RFC 7675 5.1,
79 *
80 * To prevent expiry of consent, a STUN binding request can be sent periodically.
81 * Implementations SHOULD set a default interval of 5 seconds(5000ms).
82 *
83 * Consent expires after 30 seconds(30000ms).
84 */
85#define RTC_ICE_CONSENT_CHECK_INTERVAL 5000
86#define RTC_ICE_CONSENT_EXPIRED_TIMER 30000
87
88/* STUN Attribute, comprehension-required range (0x0000-0x7FFF) */
90 STUN_ATTR_USERNAME = 0x0006, /// shared secret response/bind request
91 STUN_ATTR_PRIORITY = 0x0024, /// must be included in a Binding request
92 STUN_ATTR_USE_CANDIDATE = 0x0025, /// bind request
93 STUN_ATTR_MESSAGE_INTEGRITY = 0x0008, /// bind request/response
94 STUN_ATTR_FINGERPRINT = 0x8028, /// rfc5389
95 STUN_ATTR_ICE_CONTROLLING = 0x802A, /// ICE controlling role
96};
97
98/**
99 * Get or Generate a self-signed certificate and private key for DTLS,
100 * fingerprint for SDP
101 */
103{
104 int ret = 0;
105
106 if (rtc->cert_file && rtc->key_file) {
107 /* Read the private key and certificate from the file. */
108 if ((ret = ff_ssl_read_key_cert(rtc->key_file, rtc->cert_file,
109 rtc->key_buf, sizeof(rtc->key_buf),
110 rtc->cert_buf, sizeof(rtc->cert_buf),
111 &rtc->dtls_fingerprint)) < 0) {
112 av_log(rtc->ctx, AV_LOG_ERROR, "Failed to read DTLS certificate from cert=%s, key=%s\n",
113 rtc->cert_file, rtc->key_file);
114 return ret;
115 }
116 } else {
117 /* Generate a private key to ctx->dtls_pkey and self-signed certificate. */
118 if ((ret = ff_ssl_gen_key_cert(rtc->key_buf, sizeof(rtc->key_buf),
119 rtc->cert_buf, sizeof(rtc->cert_buf),
120 &rtc->dtls_fingerprint)) < 0) {
121 av_log(rtc->ctx, AV_LOG_ERROR, "Failed to generate DTLS private key and certificate\n");
122 return ret;
123 }
124 }
125
126 return ret;
127}
128
130{
131 int ret = 0;
132 int is_dtls_active = rtc->flags & RTC_DTLS_ACTIVE;
134 char buf[256];
135
136 ff_url_join(buf, sizeof(buf), "dtls", NULL, rtc->ice_host, rtc->ice_port, NULL);
137 av_dict_set_int(&opts, "mtu", rtc->pkt_size, 0);
138 if (rtc->cert_file) {
139 av_dict_set(&opts, "cert_file", rtc->cert_file, 0);
140 } else
141 av_dict_set(&opts, "cert_pem", rtc->cert_buf, 0);
142
143 if (rtc->key_file) {
144 av_dict_set(&opts, "key_file", rtc->key_file, 0);
145 } else
146 av_dict_set(&opts, "key_pem", rtc->key_buf, 0);
147 av_dict_set_int(&opts, "external_sock", 1, 0);
148 av_dict_set_int(&opts, "use_srtp", 1, 0);
149 av_dict_set_int(&opts, "listen", is_dtls_active ? 0 : 1, 0);
150 // Do not verify CA
151 av_dict_set_int(&opts, "verify", 0, 0);
155 if (ret < 0) {
156 av_log(rtc->ctx, AV_LOG_ERROR, "Failed to open DTLS url:%s\n", buf);
157 goto end;
158 }
159 /* reuse the udp socket created by the caller */
161end:
162 return ret;
163}
164
166{
167 int ret;
168 uint32_t seed;
169
171
173 if (ret < 0) {
174 av_log(rtc->ctx, AV_LOG_ERROR, "Failed to init certificate and key\n");
175 return ret;
176 }
177
178 /* Initialize the random number generator. */
180 av_lfg_init(&rtc->rnd, seed);
181
182 /* 64 bit tie breaker for ICE-CONTROLLING (RFC 8445 16.1) */
183 ret = av_random_bytes((uint8_t *)&rtc->ice_tie_breaker, sizeof(rtc->ice_tie_breaker));
184 if (ret < 0) {
185 av_log(rtc->ctx, AV_LOG_ERROR, "Couldn't generate random bytes for ICE tie breaker\n");
186 return ret;
187 }
188
189 if (rtc->state < RTC_STATE_INIT)
190 rtc->state = RTC_STATE_INIT;
192 av_log(rtc->ctx, AV_LOG_VERBOSE, "Init state=%d, handshake_timeout=%dms, pkt_size=%d, seed=%d, elapsed=%.2fms\n",
194
195 return 0;
196}
197
198/**
199 * Exchange SDP offer with WebRTC peer to get the answer.
200 *
201 * @return 0 if OK, AVERROR_xxx on error
202 */
204{
205 int ret;
206 char buf[MAX_URL_SIZE];
207 AVBPrint bp;
208 /* The URL context is an HTTP transport layer for the RTC session. */
209 URLContext *uc = NULL;
211 char *hex_data = NULL;
212 const char *proto_name = avio_find_protocol_name(rtc->ctx->url);
213
214 /* To prevent a crash during cleanup, always initialize it. */
216
217 if (!av_strstart(proto_name, "http", NULL)) {
218 av_log(rtc->ctx, AV_LOG_ERROR, "Protocol %s is not supported by RTC, choose http, url is %s\n",
219 proto_name, rtc->ctx->url);
220 ret = AVERROR(EINVAL);
221 goto end;
222 }
223
224 if (!rtc->sdp_offer || !*rtc->sdp_offer) {
225 av_log(rtc->ctx, AV_LOG_ERROR, "No offer to exchange\n");
226 ret = AVERROR(EINVAL);
227 goto end;
228 }
229
230 ret = snprintf(buf, sizeof(buf), "Cache-Control: no-cache\r\nContent-Type: application/sdp\r\n");
231 if (rtc->authorization)
232 ret += snprintf(buf + ret, sizeof(buf) - ret, "Authorization: Bearer %s\r\n", rtc->authorization);
233 if (ret <= 0 || ret >= sizeof(buf)) {
234 av_log(rtc->ctx, AV_LOG_ERROR, "Failed to generate headers, size=%d, %s\n", ret, buf);
235 ret = AVERROR(EINVAL);
236 goto end;
237 }
238
239 av_dict_set(&opts, "headers", buf, 0);
240 av_dict_set_int(&opts, "chunked_post", 0, 0);
241
242 if (rtc->timeout >= 0)
243 av_dict_set_int(&opts, "timeout", rtc->timeout, 0);
244
245 const size_t sdp_offer_len = strlen(rtc->sdp_offer);
246 hex_data = av_malloc(2 * sdp_offer_len + 1);
247 if (!hex_data) {
248 ret = AVERROR(ENOMEM);
249 goto end;
250 }
251 ff_data_to_hex(hex_data, rtc->sdp_offer, sdp_offer_len, 0);
252 av_dict_set(&opts, "post_data", hex_data, AV_DICT_DONT_STRDUP_VAL);
253
256 if (ret < 0) {
257 av_log(rtc->ctx, AV_LOG_ERROR, "Failed to request url=%s, offer: %s\n", rtc->ctx->url, rtc->sdp_offer);
258 goto end;
259 }
260
261 if (ff_http_get_new_location(uc)) {
263 if (!proto_name || !av_strstart(proto_name, "http", NULL)) {
264 av_log(rtc->ctx, AV_LOG_ERROR, "Unsupported resource url %s\n", ff_http_get_new_location(uc));
266 goto end;
267 }
269 if (!rtc->resource_url) {
270 ret = AVERROR(ENOMEM);
271 goto end;
272 }
273 }
274
275 while (1) {
276 ret = ffurl_read(uc, buf, sizeof(buf));
277 if (ret == AVERROR_EOF) {
278 /* Reset the error because we read all response as answer util EOF. */
279 ret = 0;
280 break;
281 }
282 if (ret <= 0) {
283 av_log(rtc->ctx, AV_LOG_ERROR, "Failed to read response from url=%s, offer is %s, answer is %s\n",
284 rtc->ctx->url, rtc->sdp_offer, rtc->sdp_answer);
285 goto end;
286 }
287
288 av_bprintf(&bp, "%.*s", ret, buf);
289 if (!av_bprint_is_complete(&bp)) {
290 av_log(rtc->ctx, AV_LOG_ERROR, "Answer exceed max size %d, %.*s, %s\n", RTC_MAX_SDP_SIZE, ret, buf, bp.str);
291 ret = AVERROR(EIO);
292 goto end;
293 }
294 }
295
296 if (!av_strstart(bp.str, "v=", NULL)) {
297 av_log(rtc->ctx, AV_LOG_ERROR, "Invalid answer: %s\n", bp.str);
298 ret = AVERROR(EINVAL);
299 goto end;
300 }
301
302 rtc->sdp_answer = av_strdup(bp.str);
303 if (!rtc->sdp_answer) {
304 ret = AVERROR(ENOMEM);
305 goto end;
306 }
307
308 if (rtc->state < RTC_STATE_ANSWER)
309 rtc->state = RTC_STATE_ANSWER;
310 av_log(rtc->ctx, AV_LOG_VERBOSE, "Got state=%d, answer: %s\n", rtc->state, rtc->sdp_answer);
311
312end:
313 ffurl_closep(&uc);
316 return ret;
317}
318
319/**
320 * Parses the ICE ufrag, pwd, and candidates from the SDP answer.
321 *
322 * This function is used to extract the ICE ufrag, pwd, and candidates from the SDP answer.
323 * It returns an error if any of these fields is NULL. The function only uses the first
324 * candidate if there are multiple candidates. However, support for multiple candidates
325 * will be added in the future.
326 *
327 * @param rtc Pointer to the RTCContext
328 * @returns Returns 0 if successful or AVERROR_xxx if an error occurs.
329 */
331{
332 int ret = 0;
333 AVIOContext *pb;
334 char line[MAX_URL_SIZE];
335 const char *ptr;
336 int i;
337
338 if (!rtc->sdp_answer || !strlen(rtc->sdp_answer)) {
339 av_log(rtc->ctx, AV_LOG_ERROR, "No answer to parse\n");
340 return AVERROR(EINVAL);
341 }
342
343 pb = avio_alloc_context(rtc->sdp_answer, strlen(rtc->sdp_answer), 0, NULL, NULL, NULL, NULL);
344 if (!pb)
345 return AVERROR(ENOMEM);
346
347 for (i = 0; !avio_feof(pb); i++) {
348 ff_get_chomp_line(pb, line, sizeof(line));
349 if (av_strstart(line, "a=ice-lite", &ptr))
350 rtc->is_peer_ice_lite = 1;
351 if (av_strstart(line, "a=ice-ufrag:", &ptr) && !rtc->ice_ufrag_remote) {
352 rtc->ice_ufrag_remote = av_strdup(ptr);
353 if (!rtc->ice_ufrag_remote) {
354 ret = AVERROR(ENOMEM);
355 goto end;
356 }
357 } else if (av_strstart(line, "a=ice-pwd:", &ptr) && !rtc->ice_pwd_remote) {
358 rtc->ice_pwd_remote = av_strdup(ptr);
359 if (!rtc->ice_pwd_remote) {
360 ret = AVERROR(ENOMEM);
361 goto end;
362 }
363 } else if (av_strstart(line, "a=fingerprint:", &ptr) && !rtc->remote_fingerprint) {
364 /* SDP a=fingerprint format is "<algo> <hex:hex:...>". Skip
365 * the algo token, store the hex string for post-handshake compare. */
366 const char *space = strchr(ptr, ' ');
367 if (space) {
369 if (!rtc->remote_fingerprint) {
370 ret = AVERROR(ENOMEM);
371 goto end;
372 }
373 }
374 } else if (av_strstart(line, "a=candidate:", &ptr) && !rtc->ice_protocol) {
375 if (ptr && av_stristr(ptr, "host")) {
376 /* Refer to RFC 5245 15.1 */
377 char foundation[33], protocol[17], host[129];
378 int component_id, priority, port;
379 ret = sscanf(ptr, "%32s %d %16s %d %128s %d typ host", foundation, &component_id, protocol, &priority, host, &port);
380 if (ret != 6) {
381 av_log(rtc->ctx, AV_LOG_ERROR, "Failed %d to parse line %d %s from %s\n",
382 ret, i, line, rtc->sdp_answer);
383 ret = AVERROR(EIO);
384 goto end;
385 }
386
387 if (av_strcasecmp(protocol, "udp")) {
388 av_log(rtc->ctx, AV_LOG_ERROR, "Protocol %s is not supported by RTC, choose udp, line %d %s of %s\n",
389 protocol, i, line, rtc->sdp_answer);
390 ret = AVERROR(EIO);
391 goto end;
392 }
393
394 rtc->ice_protocol = av_strdup(protocol);
395 rtc->ice_host = av_strdup(host);
396 rtc->ice_port = port;
397 if (!rtc->ice_protocol || !rtc->ice_host) {
398 ret = AVERROR(ENOMEM);
399 goto end;
400 }
401 }
402 }
403 }
404
405 if (!rtc->ice_pwd_remote || !strlen(rtc->ice_pwd_remote)) {
406 av_log(rtc->ctx, AV_LOG_ERROR, "No remote ice pwd parsed from %s\n", rtc->sdp_answer);
407 ret = AVERROR(EINVAL);
408 goto end;
409 }
410
411 if (!rtc->ice_ufrag_remote || !strlen(rtc->ice_ufrag_remote)) {
412 av_log(rtc->ctx, AV_LOG_ERROR, "No remote ice ufrag parsed from %s\n", rtc->sdp_answer);
413 ret = AVERROR(EINVAL);
414 goto end;
415 }
416
417 if (!rtc->ice_protocol || !rtc->ice_host || !rtc->ice_port) {
418 av_log(rtc->ctx, AV_LOG_ERROR, "No ice candidate parsed from %s\n", rtc->sdp_answer);
419 ret = AVERROR(EINVAL);
420 goto end;
421 }
422
423 /* per RFC 8829/8842, SDP answer MUST carry a=fingerprint and that
424 * fingerprint MUST match the DTLS peer certificate. Without it, an
425 * on-path attacker can complete DTLS with an arbitrary self-signed
426 * certificate and the resulting SRTP session is unauthenticated. */
427 if (!rtc->remote_fingerprint || !strlen(rtc->remote_fingerprint)) {
428 av_log(rtc->ctx, AV_LOG_ERROR,
429 "No remote DTLS fingerprint in SDP answer; refusing unauthenticated session\n");
430 ret = AVERROR(EINVAL);
431 goto end;
432 }
433
434 if (rtc->state < RTC_STATE_NEGOTIATED)
437 av_log(rtc->ctx, AV_LOG_VERBOSE, "SDP state=%d, offer=%zuB, answer=%zuB, ufrag=%s, pwd=%zuB, transport=%s://%s:%d, elapsed=%.2fms\n",
438 rtc->state, strlen(rtc->sdp_offer), strlen(rtc->sdp_answer), rtc->ice_ufrag_remote, strlen(rtc->ice_pwd_remote),
440
441end:
443 return ret;
444}
445
446/**
447 * Creates and marshals an ICE binding request packet.
448 *
449 * This function creates and marshals an ICE binding request packet. The function only
450 * generates the username attribute and does not include goog-network-info,
451 * use-candidate. However, some of these attributes may be added in the future.
452 *
453 * @param rtc Pointer to the RTCContext
454 * @param buf Pointer to memory buffer to store the request packet
455 * @param buf_size Size of the memory buffer
456 * @param request_size Pointer to an integer that receives the size of the request packet
457 * @return Returns 0 if successful or AVERROR_xxx if an error occurs.
458 */
460 uint8_t *buf, int buf_size,
461 int *request_size)
462{
463 int ret, size, crc32;
464 char username[128];
465 AVIOContext *pb = NULL;
466 AVHMAC *hmac = NULL;
467
468 pb = avio_alloc_context(buf, buf_size, 1, NULL, NULL, NULL, NULL);
469 if (!pb)
470 return AVERROR(ENOMEM);
471
473 if (!hmac) {
474 ret = AVERROR(ENOMEM);
475 goto end;
476 }
477
478 /* Write 20 bytes header */
479 avio_wb16(pb, 0x0001); /* STUN binding request */
480 avio_wb16(pb, 0); /* length */
481 avio_wb32(pb, STUN_MAGIC_COOKIE); /* magic cookie */
482 avio_wb32(pb, av_lfg_get(&rtc->rnd)); /* transaction ID */
483 avio_wb32(pb, av_lfg_get(&rtc->rnd)); /* transaction ID */
484 avio_wb32(pb, av_lfg_get(&rtc->rnd)); /* transaction ID */
485
486 /* The username is the concatenation of the two ICE ufrag */
487 ret = snprintf(username, sizeof(username), "%s:%s", rtc->ice_ufrag_remote, rtc->ice_ufrag_local);
488 if (ret <= 0 || ret >= sizeof(username)) {
489 av_log(rtc->ctx, AV_LOG_ERROR, "Failed to build username %s:%s, max=%zu, ret=%d\n",
490 rtc->ice_ufrag_remote, rtc->ice_ufrag_local, sizeof(username), ret);
491 ret = AVERROR(EIO);
492 goto end;
493 }
494
495 /* Write the username attribute */
496 avio_wb16(pb, STUN_ATTR_USERNAME); /* attribute type username */
497 avio_wb16(pb, ret); /* size of username */
498 avio_write(pb, username, ret); /* bytes of username */
499 ffio_fill(pb, 0, (4 - (ret % 4)) % 4); /* padding */
500
501 /* Write the use-candidate attribute */
502 avio_wb16(pb, STUN_ATTR_USE_CANDIDATE); /* attribute type use-candidate */
503 avio_wb16(pb, 0); /* size of use-candidate */
504
506 avio_wb16(pb, 4);
508
510 avio_wb16(pb, 8);
511 avio_wb64(pb, rtc->ice_tie_breaker);
512
513 /* Build and update message integrity */
514 avio_wb16(pb, STUN_ATTR_MESSAGE_INTEGRITY); /* attribute type message integrity */
515 avio_wb16(pb, 20); /* size of message integrity */
516 ffio_fill(pb, 0, 20); /* fill with zero to directly write and skip it */
517 size = avio_tell(pb);
518 buf[2] = (size - 20) >> 8;
519 buf[3] = (size - 20) & 0xFF;
520 av_hmac_init(hmac, rtc->ice_pwd_remote, strlen(rtc->ice_pwd_remote));
521 av_hmac_update(hmac, buf, size - 24);
522 av_hmac_final(hmac, buf + size - 20, 20);
523
524 /* Write the fingerprint attribute */
525 avio_wb16(pb, STUN_ATTR_FINGERPRINT); /* attribute type fingerprint */
526 avio_wb16(pb, 4); /* size of fingerprint */
527 ffio_fill(pb, 0, 4); /* fill with zero to directly write and skip it */
528 size = avio_tell(pb);
529 buf[2] = (size - 20) >> 8;
530 buf[3] = (size - 20) & 0xFF;
531 /* Refer to the av_hash_alloc("CRC32"), av_hash_init and av_hash_final */
532 crc32 = av_crc(av_crc_get_table(AV_CRC_32_IEEE_LE), 0xFFFFFFFF, buf, size - 8) ^ 0xFFFFFFFF;
533 avio_skip(pb, -4);
534 avio_wb32(pb, crc32 ^ 0x5354554E); /* xor with "STUN" */
535
537
538end:
540 av_hmac_free(hmac);
541 return ret;
542}
543
544/**
545 * Create an ICE binding response.
546 *
547 * This function generates an ICE binding response and writes it to the provided
548 * buffer. The response is signed using the local password for message integrity.
549 *
550 * @param rtc Pointer to the RTCContext structure.
551 * @param tid Pointer to the transaction ID of the binding request. The tid_size should be 12.
552 * @param tid_size The size of the transaction ID, should be 12.
553 * @param buf Pointer to the buffer where the response will be written.
554 * @param buf_size The size of the buffer provided for the response.
555 * @param response_size Pointer to an integer that will store the size of the generated response.
556 * @return Returns 0 if successful or AVERROR_xxx if an error occurs.
557 */
559 char *tid, int tid_size,
560 uint8_t *buf, int buf_size,
561 int *response_size)
562{
563 int ret = 0, size, crc32;
564 AVIOContext *pb = NULL;
565 AVHMAC *hmac = NULL;
566
567 if (tid_size != 12) {
568 av_log(rtc->ctx, AV_LOG_ERROR, "Invalid transaction ID size. Expected 12, got %d\n", tid_size);
569 return AVERROR(EINVAL);
570 }
571
572 pb = avio_alloc_context(buf, buf_size, 1, NULL, NULL, NULL, NULL);
573 if (!pb)
574 return AVERROR(ENOMEM);
575
577 if (!hmac) {
578 ret = AVERROR(ENOMEM);
579 goto end;
580 }
581
582 /* Write 20 bytes header */
583 avio_wb16(pb, 0x0101); /* STUN binding response */
584 avio_wb16(pb, 0); /* length */
585 avio_wb32(pb, STUN_MAGIC_COOKIE); /* magic cookie */
586 avio_write(pb, tid, tid_size); /* transaction ID */
587
588 /* Build and update message integrity */
589 avio_wb16(pb, STUN_ATTR_MESSAGE_INTEGRITY); /* attribute type message integrity */
590 avio_wb16(pb, 20); /* size of message integrity */
591 ffio_fill(pb, 0, 20); /* fill with zero to directly write and skip it */
592 size = avio_tell(pb);
593 buf[2] = (size - 20) >> 8;
594 buf[3] = (size - 20) & 0xFF;
595 av_hmac_init(hmac, rtc->ice_pwd_local, strlen(rtc->ice_pwd_local));
596 av_hmac_update(hmac, buf, size - 24);
597 av_hmac_final(hmac, buf + size - 20, 20);
598
599 /* Write the fingerprint attribute */
600 avio_wb16(pb, STUN_ATTR_FINGERPRINT); /* attribute type fingerprint */
601 avio_wb16(pb, 4); /* size of fingerprint */
602 ffio_fill(pb, 0, 4); /* fill with zero to directly write and skip it */
603 size = avio_tell(pb);
604 buf[2] = (size - 20) >> 8;
605 buf[3] = (size - 20) & 0xFF;
606 /* Refer to the av_hash_alloc("CRC32"), av_hash_init and av_hash_final */
607 crc32 = av_crc(av_crc_get_table(AV_CRC_32_IEEE_LE), 0xFFFFFFFF, buf, size - 8) ^ 0xFFFFFFFF;
608 avio_skip(pb, -4);
609 avio_wb32(pb, crc32 ^ 0x5354554E); /* xor with "STUN" */
610
611 *response_size = size;
612
613end:
615 av_hmac_free(hmac);
616 return ret;
617}
618
619/**
620 * A Binding request has class=0b00 (request) and method=0b000000000001 (Binding)
621 * and is encoded into the first 16 bits as 0x0001.
622 * See https://datatracker.ietf.org/doc/html/rfc5389#section-6
623 */
624static int ice_is_binding_request(uint8_t *b, int size)
625{
626 return size >= RTC_ICE_STUN_HEADER_SIZE && AV_RB16(&b[0]) == 0x0001;
627}
628
629/**
630 * A Binding response has class=0b10 (success response) and method=0b000000000001,
631 * and is encoded into the first 16 bits as 0x0101.
632 */
633static int ice_is_binding_response(const uint8_t *b, int size)
634{
635 return size >= RTC_ICE_STUN_HEADER_SIZE && AV_RB16(&b[0]) == 0x0101;
636}
637
638/**
639 * In RTP packets, the first byte is represented as 0b10xxxxxx, where the initial
640 * two bits (0b10) indicate the RTP version,
641 * see https://www.rfc-editor.org/rfc/rfc3550#section-5.1
642 * The RTCP packet header is similar to RTP,
643 * see https://www.rfc-editor.org/rfc/rfc3550#section-6.4.1
644 */
645int ff_rtc_media_is_rtp_rtcp(const uint8_t *b, int size)
646{
647 return size >= RTC_RTP_HEADER_SIZE && (b[0] & 0xC0) == 0x80;
648}
649
650/* Whether the packet is RTCP. */
651int ff_rtc_media_is_rtcp(const uint8_t *b, int size)
652{
653 return size >= RTC_RTP_HEADER_SIZE && b[1] >= RTC_RTCP_PT_START && b[1] <= RTC_RTCP_PT_END;
654}
655
656/**
657 * This function handles incoming binding request messages by responding to them.
658 * If the message is not a binding request, it will be ignored.
659 */
660static int ice_handle_binding_request(RTCContext *rtc, char *buf, int buf_size)
661{
662 int ret = 0, size;
663 char tid[12];
664
665 /* Ignore if not a binding request. */
666 if (!ice_is_binding_request(buf, buf_size))
667 return ret;
668
669 if (buf_size < RTC_ICE_STUN_HEADER_SIZE) {
670 av_log(rtc->ctx, AV_LOG_ERROR, "Invalid STUN message, expected at least %d, got %d\n",
671 RTC_ICE_STUN_HEADER_SIZE, buf_size);
672 return AVERROR(EINVAL);
673 }
674
675 /* Parse transaction id from binding request in buf. */
676 memcpy(tid, buf + 8, 12);
677
678 /* Build the STUN binding response. */
679 ret = ice_create_response(rtc, tid, sizeof(tid), rtc->buf,
680 sizeof(rtc->buf), &size);
681 if (ret < 0) {
682 av_log(rtc->ctx, AV_LOG_ERROR, "Failed to create STUN binding response, size=%d\n", size);
683 return ret;
684 }
685
686 ret = ffurl_write(rtc->udp, rtc->buf, size);
687 if (ret < 0) {
688 av_log(rtc->ctx, AV_LOG_ERROR, "Failed to send STUN binding response, size=%d\n", size);
689 return ret;
690 }
691
692 return 0;
693}
694
695/**
696 * To establish a connection with the UDP server, we utilize ICE-LITE in a Client-Server
697 * mode. In this setup, FFmpeg acts as the UDP client, while the peer functions as the
698 * UDP server.
699 */
701{
702 int ret = 0;
703 char url[256];
705
706 /* Build UDP URL and create the UDP context as transport. */
707 ff_url_join(url, sizeof(url), "udp", NULL, rtc->ice_host, rtc->ice_port, NULL);
708
709 av_dict_set_int(&opts, "connect", 1, 0);
710 av_dict_set_int(&opts, "fifo_size", 0, 0);
711 /* Pass through the pkt_size and buffer_size to underling protocol */
712 av_dict_set_int(&opts, "pkt_size", rtc->pkt_size, 0);
713 av_dict_set_int(&opts, "buffer_size", rtc->ts_buffer_size, 0);
714
717 if (ret < 0) {
718 av_log(rtc->ctx, AV_LOG_ERROR, "Failed to connect udp://%s:%d\n", rtc->ice_host, rtc->ice_port);
719 goto end;
720 }
721
722 /* Make the socket non-blocking, set to READ and WRITE mode after connected */
725
729 av_log(rtc->ctx, AV_LOG_VERBOSE, "UDP state=%d, elapsed=%.2fms, connected to udp://%s:%d\n",
731
732end:
734 return ret;
735}
736
738{
739 int ret = 0, size, i;
740 int64_t starttime = av_gettime_relative(), now;
741 int is_dtls_active = rtc->flags & RTC_DTLS_ACTIVE;
742
743 if (rtc->state < RTC_STATE_UDP_CONNECTED || !rtc->udp) {
744 av_log(rtc->ctx, AV_LOG_ERROR, "UDP not connected, state=%d, udp=%p\n", rtc->state, rtc->udp);
745 return AVERROR(EINVAL);
746 }
747
748 while (1) {
749 if (rtc->state <= RTC_STATE_ICE_CONNECTING) {
750 /* Build the STUN binding request. */
751 ret = ice_create_request(rtc, rtc->buf, sizeof(rtc->buf), &size);
752 if (ret < 0) {
753 av_log(rtc->ctx, AV_LOG_ERROR, "Failed to create STUN binding request, size=%d\n", size);
754 goto end;
755 }
756
757 ret = ffurl_write(rtc->udp, rtc->buf, size);
758 if (ret < 0) {
759 av_log(rtc->ctx, AV_LOG_ERROR, "Failed to send STUN binding request, size=%d\n", size);
760 goto end;
761 }
762
765 }
766
767next_packet:
768 if (rtc->state >= RTC_STATE_DTLS_FINISHED)
769 /* DTLS handshake is done, exit the loop. */
770 break;
771
772 now = av_gettime_relative();
773 if (now - starttime >= rtc->handshake_timeout * RTC_US_PER_MS) {
774 av_log(rtc->ctx, AV_LOG_ERROR, "DTLS handshake timeout=%dms, cost=%.2fms, elapsed=%.2fms, state=%d\n",
775 rtc->handshake_timeout, RTC_ELAPSED(starttime, now), RTC_ELAPSED(rtc->starttime, now), rtc->state);
776 ret = AVERROR(ETIMEDOUT);
777 goto end;
778 }
779
780 /* Read the STUN or DTLS messages from peer. */
781 for (i = 0; i < RTC_ICE_DTLS_READ_MAX_RETRY; i++) {
783 break;
784 ret = ffurl_read(rtc->udp, rtc->buf, sizeof(rtc->buf));
785 if (ret > 0)
786 break;
787 if (ret == AVERROR(EAGAIN)) {
789 continue;
790 }
791 if (is_dtls_active)
792 break;
793 av_log(rtc->ctx, AV_LOG_ERROR, "Failed to read message\n");
794 goto end;
795 }
796
797 /* Handle the ICE binding response. */
798 if (ice_is_binding_response(rtc->buf, ret)) {
799 if (rtc->state < RTC_STATE_ICE_CONNECTED) {
800 if (rtc->is_peer_ice_lite)
802 }
803 goto next_packet;
804 }
805
806 /* When a binding request is received, it is necessary to respond immediately. */
807 if (ice_is_binding_request(rtc->buf, ret)) {
808 if ((ret = ice_handle_binding_request(rtc, rtc->buf, ret)) < 0)
809 goto end;
810 goto next_packet;
811 }
812
813 /* Handle DTLS handshake */
814 if (ff_is_dtls_packet(rtc->buf, ret) || is_dtls_active) {
816 /* Start consent timer when ICE selected */
819 av_log(rtc->ctx, AV_LOG_VERBOSE, "ICE STUN ok, state=%d, url=udp://%s:%d, location=%s, username=%s:%s, res=%dB, elapsed=%.2fms\n",
820 rtc->state, rtc->ice_host, rtc->ice_port, rtc->resource_url ? rtc->resource_url : "",
822
823 ret = dtls_initialize(rtc);
824 if (ret < 0)
825 goto end;
827 if (ret < 0) {
828 rtc->state = RTC_STATE_FAILED;
829 av_log(rtc->ctx, AV_LOG_ERROR, "DTLS session failed\n");
830 goto end;
831 }
832 if (!ret) {
835 av_log(rtc->ctx, AV_LOG_VERBOSE, "DTLS handshake is done, elapsed=%.2fms\n",
836 RTC_ELAPSED(rtc->starttime, rtc->dtls_time));
837 }
838 goto next_packet;
839 }
840 }
841
842end:
843 return ret;
844}
845
847{
848 int ret;
851 int is_dtls_active = rtc->flags & RTC_DTLS_ACTIVE;
852 char *cp = is_dtls_active ? send_key : recv_key;
853 char *sp = is_dtls_active ? recv_key : send_key;
854
856 if (ret < 0)
857 goto end;
858 /**
859 * This represents the material used to build the SRTP master key. It is
860 * generated by DTLS and has the following layout:
861 * 16B 16B 14B 14B
862 * client_key | server_key | client_salt | server_salt
863 */
864 char *client_key = rtc->dtls_srtp_materials;
865 char *server_key = rtc->dtls_srtp_materials + RTC_DTLS_SRTP_KEY_LEN;
866 char *client_salt = server_key + RTC_DTLS_SRTP_KEY_LEN;
867 char *server_salt = client_salt + RTC_DTLS_SRTP_SALT_LEN;
868
869 memcpy(cp, client_key, RTC_DTLS_SRTP_KEY_LEN);
870 memcpy(cp + RTC_DTLS_SRTP_KEY_LEN, client_salt, RTC_DTLS_SRTP_SALT_LEN);
871
872 memcpy(sp, server_key, RTC_DTLS_SRTP_KEY_LEN);
873 memcpy(sp + RTC_DTLS_SRTP_KEY_LEN, server_salt, RTC_DTLS_SRTP_SALT_LEN);
874
875 if (!av_base64_encode(rtc->srtp_send_key, sizeof(rtc->srtp_send_key), send_key, sizeof(send_key))) {
876 av_log(rtc->ctx, AV_LOG_ERROR, "Failed to encode send key\n");
877 ret = AVERROR(EIO);
878 goto end;
879 }
880
881 if (!av_base64_encode(rtc->srtp_recv_key, sizeof(rtc->srtp_recv_key), recv_key, sizeof(recv_key))) {
882 av_log(rtc->ctx, AV_LOG_ERROR, "Failed to encode recv key\n");
883 ret = AVERROR(EIO);
884 goto end;
885 }
886
887end:
888 return ret;
889}
890
891/**
892 * RTC is connectionless, for it's based on UDP, so it check whether sesison is
893 * timeout. In such case, publishers can't republish the stream util the session
894 * is timeout.
895 * This function is called to notify the server that the stream is ended, server
896 * should expire and close the session immediately, so that publishers can republish
897 * the stream quickly.
898 */
900{
901 int ret;
902 char buf[MAX_URL_SIZE];
903 URLContext *uc = NULL;
905
906 if (!rtc->resource_url)
907 return 0;
908
909 ret = snprintf(buf, sizeof(buf), "Cache-Control: no-cache\r\n");
910 if (rtc->authorization)
911 ret += snprintf(buf + ret, sizeof(buf) - ret, "Authorization: Bearer %s\r\n", rtc->authorization);
912 if (ret <= 0 || ret >= sizeof(buf)) {
913 av_log(rtc->ctx, AV_LOG_ERROR, "Failed to generate headers, size=%d, %s\n", ret, buf);
914 ret = AVERROR(EINVAL);
915 goto end;
916 }
917
918 av_dict_set(&opts, "headers", buf, 0);
919 av_dict_set_int(&opts, "chunked_post", 0, 0);
920 av_dict_set(&opts, "method", "DELETE", 0);
921
922 if (rtc->timeout >= 0)
923 av_dict_set_int(&opts, "timeout", rtc->timeout, 0);
924
927 if (ret < 0) {
928 av_log(rtc->ctx, AV_LOG_ERROR, "Failed to DELETE url=%s\n", rtc->resource_url);
929 goto end;
930 }
931
932 while (1) {
933 ret = ffurl_read(uc, buf, sizeof(buf));
934 if (ret == AVERROR_EOF) {
935 ret = 0;
936 break;
937 }
938 if (ret < 0) {
939 av_log(rtc->ctx, AV_LOG_ERROR, "Failed to read response from DELETE url=%s\n", rtc->resource_url);
940 goto end;
941 }
942 }
943
944 av_log(rtc->ctx, AV_LOG_INFO, "Dispose resource %s ok\n", rtc->resource_url);
945
946end:
947 ffurl_closep(&uc);
949 return ret;
950}
951
952/**
953 * Refer to RFC 7675
954 * Periodically send Consent Freshness STUN Binding Request
955 */
957{
958 int ret = 0;
959
961 int size;
962 ret = ice_create_request(rtc, rtc->buf, sizeof(rtc->buf), &size);
963 if (ret < 0) {
964 av_log(rtc->ctx, AV_LOG_ERROR, "Failed to create STUN binding request, size=%d\n", size);
965 goto end;
966 }
967 ret = ffurl_write(rtc->udp, rtc->buf, size);
968 if (ret < 0) {
969 av_log(rtc->ctx, AV_LOG_ERROR, "Failed to send STUN binding request, size=%d\n", size);
970 goto end;
971 }
972 rtc->last_consent_tx_time = now;
973 av_log(rtc->ctx, AV_LOG_DEBUG, "Consent Freshness check sent\n");
974 }
975
976end:
977 return ret;
978}
979
980void ff_rtc_ice_check_and_update_consent(RTCContext *rtc, const uint8_t *buf, int size)
981{
982 if (ice_is_binding_response(buf, size)) {
984 av_log(rtc->ctx, AV_LOG_DEBUG, "Consent Freshness check received\n");
985 }
986}
987
989{
991 av_log(rtc->ctx, AV_LOG_ERROR,
992 "Consent Freshness expired after %.2fms (limited %dms), terminate session\n",
994 return AVERROR(ETIMEDOUT);
995 }
996
997 return 0;
998}
999
1001{
1002 av_freep(&rtc->sdp_offer);
1003 av_freep(&rtc->sdp_answer);
1004 av_freep(&rtc->resource_url);
1006 av_freep(&rtc->ice_pwd_remote);
1007 av_freep(&rtc->ice_protocol);
1008 av_freep(&rtc->ice_host);
1009 av_freep(&rtc->authorization);
1010 av_freep(&rtc->cert_file);
1011 av_freep(&rtc->key_file);
1012 ffurl_closep(&rtc->dtls_uc);
1013 ffurl_closep(&rtc->udp);
1016}
static AVDictionary * opts
static uint32_t crc32(const uint8_t *data, size_t size)
Definition apnggen.c:68
int ffurl_handshake(URLContext *c)
Perform one step of the protocol handshake to accept a new client.
Definition avio.c:296
int ffurl_open_whitelist(URLContext **puc, const char *filename, int flags, const AVIOInterruptCB *int_cb, AVDictionary **options, const char *whitelist, const char *blacklist, URLContext *parent)
Create an URLContext for accessing to the resource indicated by url, and open it.
Definition avio.c:467
int ffurl_closep(URLContext **hh)
Close the resource accessed by the URLContext h, and free the memory used by it.
Definition avio.c:664
int ffurl_get_file_handle(URLContext *h)
Return the file descriptor associated with this URL.
Definition avio.c:895
const char * avio_find_protocol_name(const char *url)
Return the name of the protocol that will handle the passed URL.
Definition avio.c:733
void avio_wb32(AVIOContext *s, unsigned int val)
Definition aviobuf.c:368
void avio_wb16(AVIOContext *s, unsigned int val)
Definition aviobuf.c:446
#define AVIO_FLAG_READ
read-only
Definition avio.h:630
int avio_feof(AVIOContext *s)
Similar to feof() but also returns nonzero on read errors.
Definition aviobuf.c:349
#define AVIO_FLAG_WRITE
write-only
Definition avio.h:631
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition avio.h:507
void avio_wb64(AVIOContext *s, uint64_t val)
Definition aviobuf.c:434
AVIOContext * avio_alloc_context(unsigned char *buffer, int buffer_size, int write_flag, void *opaque, int(*read_packet)(void *opaque, uint8_t *buf, int buf_size), int(*write_packet)(void *opaque, const uint8_t *buf, int buf_size), int64_t(*seek)(void *opaque, int64_t offset, int whence))
Allocate and initialize an AVIOContext for buffered I/O.
Definition aviobuf.c:109
int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition aviobuf.c:321
#define AVIO_FLAG_READ_WRITE
read-write pseudo flag
Definition avio.h:632
void avio_write(AVIOContext *s, const unsigned char *buf, int size)
Definition aviobuf.c:206
void avio_context_free(AVIOContext **s)
Free the supplied IO context and everything associated with it.
Definition aviobuf.c:126
#define AVIO_FLAG_NONBLOCK
Use non-blocking mode.
Definition avio.h:649
void ffio_fill(AVIOContext *s, int b, int64_t count)
Definition aviobuf.c:192
int ff_get_chomp_line(AVIOContext *s, char *buf, int maxlen)
Same as ff_get_line but strip the white-space characters in the text tail.
Definition aviobuf.c:765
void av_bprintf(AVBPrint *buf, const char *fmt,...)
Definition bprint.c:121
void av_bprint_init(AVBPrint *buf, unsigned size_init, unsigned size_max)
Definition bprint.c:68
AVBPrint public header.
#define i(width, name, range_min, range_max)
Definition cbs_h264.c:63
#define NULL
Definition coverity.c:32
long long int64_t
Definition coverity.c:34
Public header for CRC hash function implementation.
int ret
Definition ffplay.c:391
static int av_bprint_is_complete(const AVBPrint *buf)
Test if the print buffer is complete (not truncated).
Definition bprint.h:218
int av_bprint_finalize(AVBPrint *buf, char **ret_str)
Finalize a print buffer.
Definition bprint.c:234
char * av_base64_encode(char *out, int out_size, const uint8_t *in, int in_size)
Encode data to base64 and null-terminate.
Definition base64.c:152
const AVCRC * av_crc_get_table(AVCRCId crc_id)
Get an initialized standard CRC table.
Definition crc.c:389
uint32_t av_crc(const AVCRC *ctx, uint32_t crc, const uint8_t *buffer, size_t length)
Calculate the CRC of a block.
Definition crc.c:421
@ AV_CRC_32_IEEE_LE
Definition crc.h:53
uint32_t av_get_random_seed(void)
Get a seed to use in conjunction with random functions.
int av_random_bytes(uint8_t *buf, size_t len)
Generate cryptographically secure random data, i.e.
void av_dict_free(AVDictionary **pm)
Free all the memory allocated for an AVDictionary struct and all keys and values.
Definition dict.c:236
#define AV_DICT_DONT_STRDUP_VAL
Take ownership of a value that's been allocated with av_malloc() or another memory allocation functio...
Definition dict.h:79
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition dict.c:87
int av_dict_set_int(AVDictionary **pm, const char *key, int64_t value, int flags)
Convenience wrapper for av_dict_set() that converts the value to a string and stores it.
Definition dict.c:180
#define AVERROR_INVALIDDATA
Invalid data found when processing input.
Definition error.h:61
#define AVERROR_EOF
End of file.
Definition error.h:57
#define AVERROR(e)
Definition error.h:45
int av_hmac_final(AVHMAC *c, uint8_t *out, unsigned int outlen)
Finish hashing and output the HMAC digest.
Definition hmac.c:181
AVHMAC * av_hmac_alloc(enum AVHMACType type)
Allocate an AVHMAC context.
Definition hmac.c:82
void av_hmac_update(AVHMAC *c, const uint8_t *data, unsigned int len)
Hash data with the HMAC.
Definition hmac.c:176
void av_hmac_free(AVHMAC *c)
Free an AVHMAC context.
Definition hmac.c:147
void av_hmac_init(AVHMAC *c, const uint8_t *key, unsigned int keylen)
Initialize an AVHMAC context with an authentication key.
Definition hmac.c:155
@ AV_HMAC_SHA1
Definition hmac.h:34
#define AV_LOG_DEBUG
Stuff which is only useful for libav* developers.
Definition log.h:231
#define AV_LOG_VERBOSE
Detailed information.
Definition log.h:226
#define AV_LOG_INFO
Standard information.
Definition log.h:221
#define AV_LOG_ERROR
Something went wrong and cannot losslessly be recovered.
Definition log.h:210
char * av_stristr(const char *s1, const char *s2)
Locate the first case-independent occurrence in the string haystack of the string needle.
Definition avstring.c:58
int av_strcasecmp(const char *a, const char *b)
Locale-independent case-insensitive compare.
Definition avstring.c:208
int av_strstart(const char *str, const char *pfx, const char **ptr)
Return non-zero if pfx is a prefix of str.
Definition avstring.c:36
static uint64_t request_size(URLContext *h)
Definition http.c:1620
const char * ff_http_get_new_location(URLContext *h)
Definition http.c:661
#define b
Definition input.c:43
#define AV_RB16(p)
av_cold void av_lfg_init(AVLFG *c, unsigned int seed)
Definition lfg.c:32
static unsigned int av_lfg_get(AVLFG *c)
Get the next random unsigned 32-bit number using an ALFG.
Definition lfg.h:53
char * ff_data_to_hex(char *buf, const uint8_t *src, int size, int lowercase)
Write hexadecimal string corresponding to given binary data.
Definition utils.c:473
#define MAX_URL_SIZE
Definition internal.h:30
#define av_cold
Definition attributes.h:117
enum AVColorSpace space
Memory handling functions.
char * host
Definition mscl.c:249
int ff_socket_nonblock(int socket, int enable)
#define av_strdup(s)
Definition ops_static.c:55
#define av_malloc(s)
Definition ops_static.c:52
static int ice_is_binding_response(const uint8_t *b, int size)
A Binding response has class=0b10 (success response) and method=0b000000000001, and is encoded into t...
Definition rtc.c:633
#define STUN_MAGIC_COOKIE
Definition rtc.c:47
#define RTC_RTCP_PT_END
Definition rtc.c:75
void ff_rtc_ice_check_and_update_consent(RTCContext *rtc, const uint8_t *buf, int size)
Definition rtc.c:980
int ff_rtc_parse_answer(RTCContext *rtc)
Parses the ICE ufrag, pwd, and candidates from the SDP answer.
Definition rtc.c:330
static int ice_handle_binding_request(RTCContext *rtc, char *buf, int buf_size)
This function handles incoming binding request messages by responding to them.
Definition rtc.c:660
av_cold int ff_rtc_initialize(RTCContext *rtc)
Definition rtc.c:165
int ff_rtc_media_is_rtcp(const uint8_t *b, int size)
Definition rtc.c:651
static int ice_create_response(RTCContext *rtc, char *tid, int tid_size, uint8_t *buf, int buf_size, int *response_size)
Create an ICE binding response.
Definition rtc.c:558
int ff_rtc_ice_dtls_handshake(RTCContext *rtc)
Definition rtc.c:737
#define RTC_ICE_CONSENT_EXPIRED_TIMER
Definition rtc.c:86
STUNAttr
Definition rtc.c:89
@ STUN_ATTR_PRIORITY
shared secret response/bind request
Definition rtc.c:91
@ STUN_ATTR_MESSAGE_INTEGRITY
bind request
Definition rtc.c:93
@ STUN_ATTR_ICE_CONTROLLING
rfc5389
Definition rtc.c:95
@ STUN_ATTR_USE_CANDIDATE
must be included in a Binding request
Definition rtc.c:92
@ STUN_ATTR_FINGERPRINT
bind request/response
Definition rtc.c:94
@ STUN_ATTR_USERNAME
Definition rtc.c:90
#define RTC_RTCP_PT_START
For RTCP, PT is [128, 223] (or without marker [0, 95]).
Definition rtc.c:74
int ff_rtc_ice_check_consent(RTCContext *rtc, int64_t now)
Definition rtc.c:988
static av_cold int dtls_initialize(RTCContext *rtc)
Definition rtc.c:129
static int ice_is_binding_request(uint8_t *b, int size)
A Binding request has class=0b00 (request) and method=0b000000000001 (Binding) and is encoded into th...
Definition rtc.c:624
int ff_rtc_srtp_export_keys(RTCContext *rtc)
Definition rtc.c:846
static av_cold int certificate_key_init(RTCContext *rtc)
Get or Generate a self-signed certificate and private key for DTLS, fingerprint for SDP.
Definition rtc.c:102
#define STUN_HOST_CANDIDATE_PRIORITY
Refer to RFC 8445 5.1.2 priority = (2^24)*(type preference) + (2^8)*(local preference) + (2^0)*(256 -...
Definition rtc.c:54
int ff_rtc_dispose_session(RTCContext *rtc)
RTC is connectionless, for it's based on UDP, so it check whether sesison is timeout.
Definition rtc.c:899
int ff_rtc_media_is_rtp_rtcp(const uint8_t *b, int size)
In RTP packets, the first byte is represented as 0b10xxxxxx, where the initial two bits (0b10) indica...
Definition rtc.c:645
#define RTC_ICE_STUN_HEADER_SIZE
The STUN message header, which is 20 bytes long, comprises the STUNMessageType (1B),...
Definition rtc.c:62
static int ice_create_request(RTCContext *rtc, uint8_t *buf, int buf_size, int *request_size)
Creates and marshals an ICE binding request packet.
Definition rtc.c:459
#define RTC_ICE_CONSENT_CHECK_INTERVAL
Refer to RFC 7675 5.1,.
Definition rtc.c:85
av_cold void ff_rtc_deinit(RTCContext *rtc)
Definition rtc.c:1000
#define RTC_ICE_DTLS_READ_SLEEP_DURATION
Definition rtc.c:44
#define RTC_ICE_DTLS_READ_MAX_RETRY
If we try to read from UDP and get EAGAIN, we sleep for 5ms and retry up to 10 times.
Definition rtc.c:43
int ff_rtc_exchange_sdp(RTCContext *rtc)
Exchange SDP offer with WebRTC peer to get the answer.
Definition rtc.c:203
int ff_rtc_ice_check_and_send_consent(RTCContext *rtc, int64_t now)
Refer to RFC 7675 Periodically send Consent Freshness STUN Binding Request.
Definition rtc.c:956
int ff_rtc_udp_connect(RTCContext *rtc)
To establish a connection with the UDP server, we utilize ICE-LITE in a Client-Server mode.
Definition rtc.c:700
#define RTC_US_PER_MS
Definition rtc.h:66
#define RTC_MAX_SDP_SIZE
Maximum size limit of a Session Description Protocol (SDP), be it an offer or answer.
Definition rtc.h:39
#define RTC_DTLS_SRTP_SALT_LEN
Definition rtc.h:48
#define RTC_RTP_HEADER_SIZE
The RTP header is 12 bytes long, comprising the Version(1B), PT(1B), SequenceNumber(2B),...
Definition rtc.h:82
@ RTC_DTLS_ACTIVE
Definition rtc.h:118
#define RTC_DTLS_SRTP_KEY_LEN
The size of the Secure Real-time Transport Protocol (SRTP) master key material that is exported by Se...
Definition rtc.h:47
#define RTC_ELAPSED(starttime, endtime)
Definition rtc.h:85
@ RTC_STATE_FAILED
Definition rtc.h:114
@ RTC_STATE_ANSWER
Definition rtc.h:95
@ RTC_STATE_ICE_CONNECTED
Definition rtc.h:106
@ RTC_STATE_DTLS_FINISHED
Definition rtc.h:108
@ RTC_STATE_INIT
Definition rtc.h:91
@ RTC_STATE_UDP_CONNECTED
Definition rtc.h:102
@ RTC_STATE_ICE_CONNECTING
Definition rtc.h:104
@ RTC_STATE_NEGOTIATED
After parsing the answer received from the peer, the local peer negotiates the abilities in the offer...
Definition rtc.h:100
AVIOInterruptCB interrupt_callback
Custom interrupt callbacks for the I/O layer.
Definition avformat.h:1687
char * url
input or output URL.
Definition avformat.h:1518
char * protocol_whitelist
',' separated list of allowed protocols.
Definition avformat.h:1926
char * protocol_blacklist
',' separated list of disallowed protocols.
Definition avformat.h:1933
Definition hmac.c:40
Bytestream IO Context.
Definition avio.h:160
char srtp_send_key[RTC_SRTP_KEY_SIZE]
Definition rtc.h:188
uint8_t dtls_srtp_materials[(RTC_DTLS_SRTP_KEY_LEN+RTC_DTLS_SRTP_SALT_LEN) *2]
This represents the material used to build the SRTP master key.
Definition rtc.h:186
char * ice_host
Definition rtc.h:152
int64_t init_time
Definition rtc.h:162
char key_buf[MAX_CERTIFICATE_SIZE]
Definition rtc.h:174
int64_t dtls_time
Definition rtc.h:167
char * remote_fingerprint
Definition rtc.h:178
int pkt_size
The size of RTP packet, should generally be set to MTU.
Definition rtc.h:207
char * sdp_answer
Definition rtc.h:156
uint32_t flags
Definition rtc.h:124
char buf[RTC_MAX_UDP_BUFFER_SIZE]
Definition rtc.h:197
char * key_file
Definition rtc.h:216
AVLFG rnd
Definition rtc.h:129
char * dtls_fingerprint
Definition rtc.h:176
int ts_buffer_size
Definition rtc.h:208
char ice_ufrag_local[9]
Definition rtc.h:132
int64_t ice_time
Definition rtc.h:166
int64_t timeout
Definition rtc.h:202
URLContext * udp
Definition rtc.h:195
char * cert_file
Definition rtc.h:215
char ice_pwd_local[33]
Definition rtc.h:133
int64_t starttime
Definition rtc.h:161
char * ice_protocol
This represents the ICE candidate protocol, priority, host and port.
Definition rtc.h:151
char * sdp_offer
This is the SDP offer generated by the local peer based on the codec parameters, DTLS,...
Definition rtc.h:139
int64_t last_consent_rx_time
Definition rtc.h:170
int64_t answer_time
Definition rtc.h:164
int is_peer_ice_lite
Definition rtc.h:141
int ice_port
Definition rtc.h:153
char * ice_ufrag_remote
Definition rtc.h:144
int64_t udp_time
Definition rtc.h:165
enum RTCState state
Definition rtc.h:126
int handshake_timeout
Definition rtc.h:200
uint64_t ice_tie_breaker
Definition rtc.h:142
char srtp_recv_key[RTC_SRTP_KEY_SIZE]
Definition rtc.h:189
char * resource_url
Definition rtc.h:158
char cert_buf[MAX_CERTIFICATE_SIZE]
Definition rtc.h:173
int64_t last_consent_tx_time
Definition rtc.h:169
URLContext * dtls_uc
Definition rtc.h:192
AVFormatContext * ctx
Definition rtc.h:122
char * authorization
The optional Bearer token for HTTP Authorization.
Definition rtc.h:213
char * ice_pwd_remote
Definition rtc.h:145
int flags
Definition url.h:40
#define av_freep(p)
#define av_log(a,...)
int av_usleep(unsigned usec)
Sleep for a period of time.
Definition time.c:93
int64_t av_gettime_relative(void)
Get the current time in microseconds since some unspecified starting point.
Definition time.c:57
int ff_is_dtls_packet(const uint8_t *buf, int size)
Whether the packet is a DTLS packet, as defined by RFC 5764 Section 5.1.2.
Definition tls.c:167
int ff_ssl_gen_key_cert(char *key_buf, size_t key_sz, char *cert_buf, size_t cert_sz, char **fingerprint)
Definition tls_gnutls.c:299
int ff_ssl_read_key_cert(char *key_url, char *cert_url, char *key_buf, size_t key_sz, char *cert_buf, size_t cert_sz, char **fingerprint)
Definition tls_gnutls.c:115
int ff_dtls_export_materials(URLContext *h, char *dtls_srtp_materials, size_t materials_sz)
Definition tls_gnutls.c:379
int ff_tls_set_external_socket(URLContext *h, URLContext *sock)
Definition tls_gnutls.c:366
int size
int ff_url_join(char *str, int size, const char *proto, const char *authorization, const char *hostname, int port, const char *fmt,...)
Definition url.c:40
static int ffurl_write(URLContext *h, const uint8_t *buf, int size)
Write size bytes from buf to the resource accessed by h.
Definition url.h:205
static int ffurl_read(URLContext *h, uint8_t *buf, int size)
Read up to size bytes from the resource accessed by h, and store the read bytes in buf.
Definition url.h:184
static unsigned int seed
Definition videogen.c:78