1
0
mirror of https://github.com/coturn/coturn.git synced 2026-05-04 18:36:10 +02:00

225 Commits

Author SHA1 Message Date
Pavel Punsky
4b97d032ad
Cache hot lookups in TURN data-path handlers (#1893)
write_to_peerchannel(): get_relay_socket_ss() and
ioa_network_buffer_get_size() were each called twice per channel-data
packet. The compiler can't CSE the calls (cross-TU through a
get_relay_socket() accessor in ns_turn_allocation.c that it can't prove
pure), so cache the relay socket and the inbound size once.

handle_turn_send(): same get_relay_socket_ss() duplication on the
STUN_SEND path.

read_client_connection(): the inbound size was fetched four times
(received_bytes accumulator, verbose log, blen seed, ret check). Reuse
ret as orig_blen.

No behavior change. Targets the ~0.4% per-packet overhead these helpers
were contributing in the m=1 packet-flood profile.
2026-05-03 21:45:54 -07:00
Pavel Punsky
51520c77a2
Delete log line per relay thread on start (#1876)
This is a unique log per relay thread. Auth threads do not log.
2026-04-20 22:14:34 -07:00
Pavel Punsky
c37ccf4df9
Pin session origin only after MESSAGE-INTEGRITY validates (#1871)
The first ALLOCATE set ss->origin_set=1 before check_stun_auth ran, so
an unauthenticated attacker could lock the session into a realm of their
choice by forging the ORIGIN attribute on the first packet. If per-realm
ACLs differ, this lets the attacker pick the most permissive realm for
that session.

Defer the commit of ss->origin_set until check_stun_auth succeeds with a
valid MESSAGE-INTEGRITY. Until auth passes, every request re-parses
ORIGIN, so the 401 challenge still carries the correct realm derived
from the current ORIGIN attribute.
2026-04-18 17:16:47 -07:00
Pavel Punsky
14572fa091
Skip response buffer allocation for STUN indications (#1863)
## Summary

- Skip allocating a 65 KB response buffer for STUN indications (SEND,
DATA, BINDING indication) in `read_client_connection()` — indications
never produce a response, so the buffer was immediately freed
- Guard the unknown-attributes error-response block in
`handle_turn_command()` with a NULL check on `nbh` to match

## Motivation

On the UDP data-relay hot path, every SEND indication triggered a
pool-get + pool-put cycle for a response buffer that was never used.
This is the highest-frequency STUN command type during active media
relay. The change eliminates one unnecessary 65 KB buffer round-trip per
SEND indication.

## Test plan

- [ ] Build passes clean (`cmake .. && make -j$(nproc)`)
- [ ] Run RFC 5769 conformance tests (`examples/scripts/rfc5769.sh`)
- [ ] Run basic UDP relay test to verify SEND indications still relay
data correctly
- [ ] Verify STUN requests (ALLOCATE, REFRESH, BINDING request) still
receive proper error responses
2026-04-12 22:49:44 -07:00
Carlos Ruiz Ballesteros
a4756d482f
fix: restore RFC 3489 (old STUN) backward compatibility broken since 4.7.0 (#1839)
## Problem

Since 4.7.0, `--stun-backward-compatibility` no longer works. Legacy
STUN clients (RFC 3489, pre-magic-cookie) receive no response even when
the option is explicitly enabled.

## Root Cause

Commit 4cc076d renamed `no_stun_backward_compatibility` (negative logic)
to `stun_backward_compatibility` (positive logic). Two call sites were
not updated correctly:

1. **`src/server/ns_turn_server.c`**: the
`old_stun_is_command_message_str` branch in the TCP/stream socket
handler kept `!` on the renamed variable, inverting the condition. Old
STUN was processed only when backward compat was *off*.

2. **`src/apps/relay/dtls_listener.c`**: the UDP/DTLS early packet
validation block never included an `old_stun_is_command_message_str`
check, so old STUN packets were always classified as invalid regardless
of the backward compat flag.

## Fix

- **`ns_turn_server.c`**: Remove the stray `!` negation restoring
correct condition semantics.
- **`dtls_listener.c`**: Add the missing old-STUN branch in the UDP
packet validation block, guarded by
`turn_params.stun_backward_compatibility`.
2026-03-25 23:16:21 -07:00
redraincatching
86e5e72718
Change port identifiers to use uint16_t (#1752)
based on the ideas originally developed in [this
pr](https://github.com/coturn/coturn/pull/1535) by @WHYHD

---------

Co-authored-by: Pavel Punsky <eakraly@users.noreply.github.com>
2026-03-14 19:47:15 -07:00
Pavel Punsky
44d201a4f9
Initialize variables before use (#1832) 2026-03-08 16:24:32 -07:00
Pavel Punsky
20d8e38297
Disable reason string in response messages to reduce amplification factor (#1829)
Disable the messages by default - they can be re-enabled using
`--include-reason-string` option

As a result of not sending reason string (which is optional by standard
and provide debugging information for the actual numeric error code)
response message size can be decreased by up to NNN bytes.
2026-03-06 17:59:21 -08:00
Pavel Punsky
e5ed78583d
Fixes: int to bool conversion and comparison (#1810)
In multiple places int is converted to bool
2026-02-21 18:27:16 -08:00
Pavel Punsky
6c38ccb08d
Migrate AES-128 encryption from deprecated OpenSSL API to EVP (#1808)
The AES_encrypt, AES_set_encrypt_key, CRYPTO_ctr128_encrypt, and
SSL_CTX_use_RSAPrivateKey_file functions are deprecated in OpenSSL 3.0+
and produce compiler warnings.Replace deprecated low-level OpenSSL
AES/CRYPTO functions with the modern EVP (Envelope) API, and remove the
deprecated SSL_CTX_use_RSAPrivateKey_file fallback.

Changes
encrypt_aes_128 — Replaced AES_set_encrypt_key + CRYPTO_ctr128_encrypt
with EVP_EncryptInit_ex / EVP_EncryptUpdate / EVP_EncryptFinal_ex using
EVP_aes_128_ctr(). Added proper error handling (context cleanup on
failure), input length bounds checking, and enlarged the total buffer
from 256 to 1024 bytes to match the output buffer. The IV was corrected
from 8 to 16 bytes (as required by AES-CTR).

decrypt_aes_128 — Same migration from CRYPTO_ctr128_encrypt to
EVP_DecryptInit_ex / EVP_DecryptUpdate / EVP_DecryptFinal_ex. Added
proper cleanup of both the EVP context and the encryptedText allocation
on every error path. Retained the existing bounds check on newTotalSize.
Output is now explicitly null-terminated using the actual decrypted
length (outlen + final_len).

set_ctx (TLS context setup) — Removed the SSL_CTX_use_RSAPrivateKey_file
fallback that was nested inside the SSL_CTX_use_PrivateKey_file failure
path. SSL_CTX_use_PrivateKey_file already handles RSA keys, so the
RSA-specific fallback was redundant and used a function deprecated since
OpenSSL 3.0.
2026-02-19 18:05:05 -08:00
Pavel Punsky
b209191ba1
Fix unbounded strcpy in stun_method_str (ns_turn_msg.c) (#1798)
## Issue
strcpy(smethod, s) with no size check. Callers pass fixed buffers (e.g.
32 bytes); if API were misused with a smaller
buffer, or s were ever longer, this could overflow.

## Fix
Use strncpy with a fixed maximum (32), then null-terminate,
so at most 32 bytes are written regardless of caller buffer size.
2026-02-16 21:23:10 -08:00
Pavel Punsky
667b661e80
Fix missing null termination in addr_to_string (ns_turn_ioaddr.c) (#1806)
## Issue
Multiple changes in this PR related to address printing (with and
without port)
- Change buffer size to be 64 (enough to hold IPv6 - 46, and port - 5,
and formatting "[ip]:port")
- Align buffer size across all usages (were 65, 129, 256, 257, 1025).
Even 65 is bad - takes extra cache line.
- Change argument to `addr_to_string_no_port`/`addr_to_string` to be of
type char inasted of uint8_t (double converted)
- Eliminate extra buffer in `addr_to_string_no_port`
- Defensively terminate string with null in addr_to_string`

## Explanations
- `addr_to_string_no_port` rely on `inet_ntop` to convert address to
null terminated string
- `addr_to_string` with port==0 rely on `inet_ntop`, otherwise null
terminate at the end of the buffer of size MAX_IOA_ADDR_STRING
2026-02-16 21:20:41 -08:00
Pavel Punsky
11fc465f4b
Merge commit from fork
This returns the code to the state before #1279 that made turn_random() less secure and introduced more secure version with urn_random_number()  (which is actually the same as turn_random() before the change)
2025-12-29 09:05:16 -08:00
Pavel Punsky
c7936e449b
Fix order of arguments to calloc (#1790)
Proper use of the api: count and then size
This gives a warning on some of the compilers
2025-12-28 11:39:01 -08:00
Pavel Punsky
59921981bb
Implement configurable buffer sizes (#1780)
# Description

Replace the hardcoded buffer sizes inside coturn to make them
configurable for different use cases (low bitrate use cases can save
memory and high bitrate use case can avoid congestion) - based on #1089

Add this feature in both sides (listener and relay connections).

# Tests

For now it is only the automated CI tests.
Confirmed with debugger that buffer sizes are set according to the
arguments.
2025-12-25 14:06:28 -08:00
Michael Jones
98d91a73cf
Improve const correctness in coturn (#1424)
Marking variables as const when they won't be modified after
initialization helps programmers trying to understand a codebase to
manage the cognative load.

This pull request uses a clang-tidy fixit (Hard to automate, since the
code needs to be temporarily compiled as C++ for it to work) to try to
mechanically apply the const keyword to code where the automated tool
can determine that the variable won't be modified.

I then follow this up with a manual improvement pass to
turnutils_uclient, where I address const correctness of local variables,
as well as do some adjustments to loops and scoping to help with
reducing complexity.

Co-authored-by: redraincatching <redraincatching@disroot.org>
Co-authored-by: Pavel Punsky <eakraly@users.noreply.github.com>
2025-09-08 21:14:56 -07:00
redraincatching
16f801f646
addressed null pointer deref warnings (#1712)
addressing issues raised by code scanning, specifically null pointer
dereferences in server

ns_turn_server.c
-
[33](https://github.com/redraincatching/coturn/security/code-scanning/33)
ignored, the `is_rfc5780()` function exits early if the server is null
- this also catches
[36](https://github.com/redraincatching/coturn/security/code-scanning/36)
-
[34](https://github.com/redraincatching/coturn/security/code-scanning/34)
addressed
-
[174](https://github.com/redraincatching/coturn/security/code-scanning/174)
addressed

ns_turn_maps.c
-
[27](https://github.com/redraincatching/coturn/security/code-scanning/27),
[160](https://github.com/redraincatching/coturn/security/code-scanning/160),
[161](https://github.com/redraincatching/coturn/security/code-scanning/161),
[162](https://github.com/redraincatching/coturn/security/code-scanning/162),
[163](https://github.com/redraincatching/coturn/security/code-scanning/163),
[164](https://github.com/redraincatching/coturn/security/code-scanning/164),
[165](https://github.com/redraincatching/coturn/security/code-scanning/165)
false positives, suppressed with assert()

ns_turn_allocations.c
-
[9](https://github.com/redraincatching/coturn/security/code-scanning/9)
addressed

---------

Co-authored-by: Gustavo Garcia <gustavogb@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-07-01 12:40:11 +02:00
Pavel Punsky
678996a529
Update version to 4.7.0 (#1691)
Set new release version to 4.7.0
Updating minor version due to some breaking changes in options to enable
more secure/robust configuration without additional flags (or relying on
recommended conf file which people seem to skip during updates)
2025-05-30 14:13:59 -07:00
Gustavo Garcia
d7197fa263
Add missing close socket when ioa_socket call fails (#1694)
Fixes [#1071](https://github.com/coturn/coturn/issues/1071)

Not sure how this case can happen but better to handle the error case.

Co-authored-by: tyranron <tyranron@gmail.com>
2025-05-30 09:19:24 -07:00
Michael Jones
9ae1e3b3cb
Add spdx tags to all source files (#1510)
With notable exceptions of:

src/apps/common/win/*
src/apps/relay/telnet.*

The purpose of this change is to add the SPDX tags from
https://spdx.dev/, which is a linux foundation project, to the source
code.

This provides automated code provenance tools, which are used in setting
up software bill of materials reports, an easy time verifying that the
code license is known and no incompatibilities are present in a
codebase.

No copyright date, author, or license changes are made.

Note also that
7e525c8e1c
is the original commit for the ACME code (acme.h and acme.c) which was
then moved to acme.h and acme.c in this commit
d4686750ee
but neither commit indicates what license the ACME code was submitted
as.

https://github.com/coturn/coturn?tab=License-1-ov-file#readme is the
3-clause BSD license, but https://github.com/coturn/coturn/pull/672
documents that the author's intent was for the MIT license. So I've used
the SPDX tag and content of the MIT license for this change.
2025-05-30 11:56:04 +02:00
Michael Jones
0af0fc3ec2
Address various minor clang-tidy warnings (#1513)
No specific methodology other than checking the github CI output for the
`clang-tidy` job, and fixing things one at a time.
2025-05-29 19:12:50 -07:00
Pavel Punsky
14f84fa48c
[BREAKING] Deprecate response-origin-only-with-rfc5780 (#1690)
Make this true - response-origin-only will only be enabled with rfc5780 option enabled
2025-05-28 16:37:20 -07:00
Pavel Punsky
4cc076d424
[BREAKING] Invert no-stun-backward-compatibility to be default on (#1689)
Deprecate `--no-stun-backward-compatibility` and set it to true by
default
Add new option `--stun-backward-compatibility`, off by default

Update example/recommended configuration files

This is a breaking change as passing `--no-stun-backward-compatibility`
will be rejected as invalid argument
2025-05-28 16:23:33 -07:00
Asmir Mehic
823fd71c98
Fix infinite loop in ns_turn_server.c (#1460)
In case ur_map_get returns 1 server will enter infinite loop because
newid != 0.

Co-authored-by: Asmir <asmir.mehic@viber.com>
2025-05-25 15:38:42 +02:00
redraincatching
01628a7a01
updated types to bool in _turn_params_ to reflect C11 (#1406)
approach was as follows, for the `_turn_params_` struct:
- if a variable of type `int` or `vint` was only being used as a
boolean, replace it with bool as defined in `<stdbool.h>`
- replace its declaration with true/false, depending on prior assignment
as 0/1

changes were only made when i was certain the variables were not being
used as an `int`, so i may have missed some

no changes were made to other sections of the code as int-to-bool
assignment is allowed in C, only code within the structs were changed,
but that can be changed with a later commit

---

from a documentation perspective, it's not clear as to what purpose or
benefit the vint alias has. the definition in `ns_turn_defs.h` simply
reads

```c
typedef int vint;
typedef vint *vintp;
```
with no comments, and it seems most (but not all) `vint`s are being used
as interim booleans through the code. this may just be from lack of
knowledge of the codebase, but it doesn't seem useful in any way, so it
would be helpful if someone with more expertise could clarify

---------

Co-authored-by: Pavel Punsky <eakraly@users.noreply.github.com>
2025-02-20 21:03:13 -08:00
Pavel Punsky
9f779a64d0
Fix warnings type conversion (#1615) 2024-12-19 09:05:37 -08:00
Pavel Punsky
94fcfadce1
[BREAKING] Reverse SOFTWARE_ATTRIBUTE_OPT to avoid inverse logic (#1598)
As part of looking at #1588 , I figured that sending `SOFTWARE`
attribute is also part of a problem as it increases messages sent out by
coturn and thus increasing amplification factor. For 4.6.2, the
additional size is 24 bytes (4 bytes attribute header, and 20 bytes for
"Coturn-4.6.2 'Gorst'")

If we are to use an example from #1588, "A 62 byte request will be met
with Coturn’s 401 Unauthorized response which is 150 bytes, a factor of
~2.42." - without SOFTWARE the response will be 126 bytes which reduces
amplification factor to ~2.

As I observed with multiple providers using coturn - some of the are
sending it. Meaning, they do not set `--no-software-attribute` - most
probably due to lack of clarity about this setting.

I believe sending SOFTWARE_ATTRIBUTE should be off by default which is
hinted in the RFC
(https://datatracker.ietf.org/doc/html/rfc8489#section-16.1.2)

Detailed changes:
- Extract setting the attribute into a function to avoid code
duplication
- This option is now not reloadable
- The option is now called `software_attribute` because inverse logic
creates multiple double-not in the code which makes it harder to read.
- `no-software_attribute` is still functional but marked as deprecated
in documentation

Test Plan:
- Run local tests with different cli arguments (new and deprecated) and
confirm SOFTWARE attribute is off by default, and added when arguments
say so
2024-12-13 09:28:45 -08:00
Scott Godin
edcdfc8b02
Add new Drain feature (#1529)
Add new Drain feature

-when coturn server is in drain mode
  -current allocations will continue to work as usual
  -new allocations will be rejected with a 403 (Forbidden) response
  -when all allocations go away, then coturn will shutdown
-Enable drain mode with either
  -signaling SIGUSR1
  -turn_admin_server "drain" CLI command

This contribution is from Wire. https://wire.com/
2024-10-27 18:56:58 -07:00
Sven Tennie
cbb04aa9a2
Delete dead code (#1563)
`stun_port` isn't read after setting it. Thus, we can remove it.
2024-10-04 10:27:31 -07:00
Michael Jones
b523616b1f
Use bool, instead of int, for the functions in ns_turn_msg.c (#1553)
And address knockon effects in other files, e.g. adjust if-statements
and other function parameters and return types.
2024-08-23 17:49:14 -07:00
Michael Jones
958f70d5c2
Use calloc where appropriate, avoid memset when normal buffer initialization works (#1550)
Depends on https://github.com/coturn/coturn/pull/1547
2024-08-04 17:30:58 -07:00
Michael Jones
5fa67a65f5
Fix compiler warnings from continuous integration (#1555)
Almost all of the warnings were about truncating pointers, because
sizeof(void*) != sizeof(long) on all platforms.
2024-08-04 15:44:15 -07:00
Michael Jones
d1db5e590d
Include what you use (#1512)
Use the include-what-you-use program to (partially) clean up header
includes, so that only includes which are needed, and no includes that
are not needed (or at least closer to that ideal) are done.

For a c-language project, the build-time improvements from this change
is minimal. This would have a much bigger impact on a C++ project than a
C-project for build times.

So for coturn, this change is mostly intended to just provide
consistency and make it easier to locate weird issues like strange
dependencies, and unnecessary connections between code.
2024-06-01 18:13:08 -07:00
Michael Jones
544382f313
Fix mingw and MSVC ci build (#1491) 2024-05-27 13:43:40 -07:00
Pavel Punsky
47fcc99853
Address some build issues introduced by api changes (#1505)
#1502 made APIs consistent with using bool as a return value where true
is success and false is failure
In a few places the change broke code

This PR fixes the breakage
2024-05-27 12:00:23 -07:00
Michael Jones
2c45aa731c
Avoid nullptr dereference of server variable in various functions (#1504) 2024-05-26 17:32:02 -07:00
Gustavo Garcia
c2d13700ac Fix clang-format lint warnings 2024-04-19 17:08:49 +02:00
Kang Lin
5b68014699
Refactor: peer_input_handle (#1325) 2024-04-19 12:09:43 +02:00
Michael Jones
da332ed9e7
Add the InsertBraces command for clang-format to ensure that all conditionals always have braces (#1408)
- Why? Because code where conditionals lack braces is much harder to read, and prone to indentation confusion.
- How? Just added an extra flag to .clang-format and re-ran clang-format on all the files.

I also moved .clang-format up to the top level of the repo so that it can be applied to the fuzz targets as well.
2024-01-27 16:38:40 -08:00
korayvt
348380f248
Added sessionID to some log lines (#1334)
Co-authored-by: KORAY VATANSEVER <koray.vatansever@turkcell.com.tr>

Some events are missed when logs are filtered by session ID. That's why I added the sessionID to some log lines.
2024-01-17 22:16:57 -08:00
Cybermilitia
7546c24b2f
Missing session ID in coturn logs for denied IP - 1330 (#1332)
Co-authored-by: CUMHUR KARAHAN <cumhur.karahan@turkcell.com.tr>

Added session id parameter to use it in "A peer IP denied in the range" logs. Besides, server ID has been made visible in this logs.
Before
```
023-08-24T17:23:17.221745770+03:00 stdout F 268472: : ERROR: A peer IP 169.254.38.68 denied in the range: 169.254.0.0-169.254.255.255
```

And after - new view:
```
2023-09-28T10:53:49.627778472+03:00 stdout F 1247: : ERROR: session 006000000000000004: A peer IP 172.21.198.41 denied in the range: 172.21.198.40-172.21.198.50 in server 6
```
2024-01-15 19:12:24 -08:00
Subhra264
9485c9567e
Fix: Return correct error code for create_relay_connection in case of RESERVATION-TOKEN failure (#1319)
Fixes #1266 

According to RFC 5766, [section 6.2](https://www.rfc-editor.org/rfc/rfc5766#section-6.2) point no. 5, the turn server needs to reject the request with 508 (Insufficient Capacity) error code when the given RESERVATION-TOKEN is not valid.
2023-11-22 20:30:27 -08:00
Dave Lambley
20c8d86a34
Return a 400 response to HTTP requests (#1231)
For our deployment, it is useful if coturn returns a valid HTTP response to an HTTP request. To do this on the same port as STUN/TURN and without enabling the admin site, I have extended `read_client_connection()` to return a canned HTTP response, in response to an HTTP request, rather than immediately closing the connection.
2023-11-05 17:25:12 -08:00
Gustavo Garcia
4e0d21e1b5
Fix memcpy len checks stun_is_challenge_response_str (#1280)
Add missing checks for length of realm/nonce/server_name before copying
those values to the buffer passed to stun_is_challenge_response_str.

The function stun_is_challenge_response_str is only used in uclient test
application.

Thank you very much @0xdea

Co-authored-by: Gustavo Garcia <gustavogb@mail.com>
2023-10-02 16:19:38 +02:00
Pavel Punsky
7038763627
Add STUN request/response/error prometheus counters (#1115)
Somewhat relevant to #1075
2022-12-17 17:50:09 +01:00
Pavel Punsky
95373d3e2a
Cleanup logs on turnserver start (#1088)
Reformatting and removing some duplications:
- Some lines have WARNING WARNING: cleaned up.
- Lines printed using perror: only LOG_ mechanism should be used.
- Printing IO mechanism (epoll for example) for each thread: selected
mechanism logged once
- Duplicate lines (perror and also LOG): duplication removed
- Duplicates: clean up (because calling function multiple times -
configuration load)
2022-11-14 17:45:20 -08:00
Gustavo Garcia
d9108a4b54
Add clang format rules and checks (#935)
I would like to get feedback on this and see if people is confortable
with these clang rules.

Right now is using the "llvm" style increasing the line length from 80
to 120 given that coturn is using long lines often.

Co-authored-by: Pavel Punsky <eakraly@users.noreply.github.com>
2022-11-06 22:05:17 +01:00
Paul Kramer
5a28394200
feature(1026): add sessioncount to prometheus metrics (#1075)
Co-authored-by: Paul Kramer <paul.kramer@logmein.com>
2022-11-06 10:19:20 -08:00
Kang Lin
40c99db6ba
Support Windows MSVC (#855)
The following changes have been made:
1. Replace deprecated functions with new standard functions
2. Add corresponding MSVC functions for non-standard functions 
3. Remove warnings about unsafe functions
4. CMAKE: modify find pack Libevent and openssl 
5. Modify include files
6. Use pthread4W
7. Modify socket in windows
8. Add CI - github action
8.1. msvc
8.2. mingw
10. The database:
9.1. sqlite, pgsql, hiredis, mongo  is test compiled.
9.2. mysql, isnot test compiled.
11. The applications、server can be compiled and run successfully! 
12. Add vcpkg manifest mode in cmake.
2022-10-28 19:32:23 -07:00
Gregor Jasny
6f14716149
Use %zu format specifier for size_t (#1040) 2022-10-24 22:34:48 +02:00