# addressing all remaining code scanning instances of warning C6011,
null pointer dereference
this pr aims to address more static code analyser warnings, specifically
null pointer dereferences. the majority of changes are solely to quieten
the analyser, as `malloc` and `calloc` are unlikely to fail, but this
should at least lead to the code analysis being more readable and
usable.
where functions addressed had existing failure strategies, they were
used, however some functions will now silently fail rather than
attempting to dereference a null pointer. if there is a preferred
solution in these cases, i will be happy to implement it.
---
this is an extension of [this pull
request](https://github.com/coturn/coturn/pull/1729)
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>
In decrypt_aes_128() at src/apps/replay/mainreplay.c, it calls
base64decode() to allocates memory in encryptedText, but forgets to free
encryptedText in the end of this function. Add free() after finished
using encryptedText.
Signed-off-by: Lidong Yan <502024330056@smail.nju.edu.cn>
When using --log-file stdout to redirect turnserver logs to stdout
instead of creating a log file, a default log file was still being
created. This happened because the --log-file argument was processed
after logging had already occurred during startup.
Fix#1670
implemented change suggested in TODO to speed up aes key generation
without, hopefully, negatively impacting the overall randomness of the
function
---------
Co-authored-by: Gustavo Garcia <gustavogb@gmail.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This PR fixes a null pointer dereference vulnerability where
`set_ssl_ctx()` could crash when passed a NULL engine handle.
## Problem
The `create_ioa_engine()` function can return NULL when invalid
parameters are provided:
```c
if (!relays_number || !relay_addrs || !tp) {
TURN_LOG_FUNC(TURN_LOG_LEVEL_ERROR, "%s: Cannot create TURN engine\n", __FUNCTION__);
return NULL;
}
```
However, two calling functions don't check for NULL before passing the
result to `set_ssl_ctx()`:
1. **`setup_relay_server()`** (line 1646):
```c
rs->ioa_eng = create_ioa_engine(...);
set_ssl_ctx(rs->ioa_eng, &turn_params); // Potential NULL dereference
```
2. **`create_new_listener_engine()`** (line 955):
```c
ioa_engine_handle e = create_ioa_engine(...);
set_ssl_ctx(e, &turn_params); // Potential NULL dereference
```
The `set_ssl_ctx()` function then dereferences the engine parameter
without checking:
```c
struct event_base *base = e->event_base; // Crashes if e is NULL
```
## Solution
Added a simple check before calling `set_ssl_ctx()`:
## Impact
- ✅ Prevents crashes when `create_ioa_engine()` fails due to invalid
configuration
- ✅ Minimal change with no functional impact on normal operation
- ✅ All existing tests continue to pass
- ✅ Follows defensive programming best practices
Fixes#1718.
This PR adds a new `--cpus` configuration option to address CPU
detection issues in virtualized and containerized environments where
`_SC_NPROCESSORS_CONF` and `_SC_NPROCESSORS_ONLN` return host CPU counts
instead of allocated container CPUs.
## Problem
In containerized deployments, coturn detects the host's CPU count (e.g.,
128 CPUs) instead of the container's allocated CPUs (e.g., 2 CPUs). This
causes the server to create excessive relay threads and database
connections, leading to resource exhaustion and performance issues.
## Solution
Added a new `cpus` configuration option that allows manual override of
CPU detection:
### Command Line Usage
```bash
turnserver --cpus 2
```
### Configuration File Usage
```ini
# Override system CPU count detection for containers
cpus=2
```
## Key Features
- **Backward Compatible**: No changes needed for existing deployments
- **Input Validation**: Values must be between 1 and 128 with proper
error handling
- **Comprehensive Documentation**: Updated man pages and example config
files
- **Both Interfaces**: Works via command line and configuration file
## Testing
The implementation has been thoroughly tested:
```bash
# Container with 2 allocated CPUs on 128-CPU host
$ turnserver --cpus 2
INFO: System cpu num is 128 # Host detection
INFO: System enable num is 128 # Host detection
INFO: Configured cpu num is 2 # Override applied
INFO: Total General servers: 2 # Correct thread count
```
- ✅ Command line option: `--cpus 8` creates 8 relay servers
- ✅ Config file option: `cpus=6` creates 6 relay servers
- ✅ Error handling: Invalid values show appropriate errors
- ✅ Default behavior: Without option, uses system detection
- ✅ RFC5769 tests: All protocol tests still pass
## Files Modified
- `src/apps/relay/mainrelay.c` - Core implementation
- `src/apps/relay/mainrelay.h` - Added configuration flag
- `examples/etc/turnserver.conf` - Added documentation and example
- `man/man1/turnserver.1` - Updated man page
This change directly addresses the resource consumption issues in
containerized environments while maintaining full backward
compatibility.
Fixes#1628.
### Describe
Hi,
Fixes resource and memory leaks in `udp_create_server_socket()` by
ensuring that the socket file descriptor (`udp_fd`) and dynamically
allocated memory (`server_addr`) are properly released on failure.
Specifically, if `addr_bind()`, `event_new()`, or `event_add()` fails,
the function now closes the socket and frees memory to prevent leaks.
### Expected Behavior
On any failure during socket binding or event registration, both
`udp_fd` and `server_addr` should be released to avoid leaking system
resources.
### Actual Behavior
Previously, if `addr_bind()`, `event_new()`, or `event_add()` failed,
the function would return early without closing the socket or freeing
memory, causing file descriptor and heap memory leaks.
This patch addresses overlooked memory and resource cleanup on failure
paths, improving server stability through targeted and essential
changes.
Thanks for reviewing.
Co-authored-by: Gustavo Garcia <gustavogb@gmail.com>
@ggarber i noticed too late that i used `0x03` instead of `0x02` by
mistake - this is an issue because it means that `add_requested_family`
will never be set when ipv6 is being used, so this should be fixed
removing an unnecessary null check as raised in [this code
scan](https://github.com/redraincatching/coturn/security/code-scanning/179)
the variable is confirmed to not be null in an outer loop guard
also changed the name of the variable in `rtcp_map_put`'s function
declaration to match that used in its function definition
Two compiler warnings were addressed:
* In `src/apps/relay/http_server.c`, line 77, a `-Wpointer-sign` warning
occurred when initializing a `char *` with the `uint8_t *` return type
of `ioa_network_buffer_data()`.
* An explicit cast `(char *)` was added to
`ioa_network_buffer_data(nbh_http)` to resolve the type mismatch.
* In `src/apps/relay/acme.c`, line 59, a `-Wchar-subscripts` warning was
present because a `char` variable `c` was used as an array index. `char`
can be signed, potentially leading to negative indices.
* Initially, `c` was cast to `(unsigned char)` at the point of use:
`A[(unsigned char)c]`.
* This was later improved by changing the declaration of `c` from `const
char` to `const unsigned char c = req[k]
---------
Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Fix issues with Global Allocation Count for drain mode
- move increment/decrement logic out of userdb.c and tie to Prometheus
logic for allocation tracking instead
- log global allocation count decrements at INFO level, when drain mode
is on
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)
TLSv1 and TLSv1.1 can be enabled using `--tlsv1` and `--tlsv1_1`
arguments accordingly
That assumes openssl version being used has these versions enabled
(which as of openssl-3.5 is not by default)
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.
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
Invert `--no-rfc5780` option to be true by default
Make it `--rfc5780` to enable it
Update example/recommended configuration files
Passing `--no-rfc5780` will have no effect as this is the default
behavior now
When building with default configuration at least in MacOS we get
warnings about those conversions from const char* to char*. Fix it by
making all those argv ""const char*"
This adjusts the code to allow compilation with a C++ compiler, but
doesn't change the build to use a C++ compiler. Everything should
continue working as-is with existing c-compilers. This is just a "let it
work" change, not a "change how it works" change.
Restore the support to return a 200 OK in the root prometheus endpoint
(/) as stated in the documentation.
This feature was lost when removing libpromhttp
Fixes#1672
Address #270
MySQL reconnectiong after priviledge drop and reporting missleading
error log.
"Cannot open MySQL DB connection: <%s>, runtime error\n"
Always include the mysql error message for additional context.
Fixes a regression pointed out at
<https://github.com/coturn/coturn/pull/1488#issuecomment-2801027711>.
A regression was introduced in the last PR where the dbname parameter
was not respected if using redis without authentication. The logic for
sending the select command responsible for switching to the correct
database was wrongly guarded behind authentication being provided. This
PR flattens the control flow so the select command is always sent,
whether using authentication or not.
Fix#1657
This log was added in a recent refactor for draining support and it is
very noisy. With this change the log is moved behind the "verbose" flag
and also does a minor cleanup to not have 2 duplicated lines for logging
when one is enough.
Co-authored-by: Gustavo Garcia <gustavogb@mail.com>
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>
- libsystemd does not exist on macOS - ignore it and reduce warnings
during cmake step
- mongo-c has cmake file on macOS - reusing the same code path and
reduce warnings
With requiring openssl version at least 1.1.1 all versions of TLS (up to
and including 1.3) and DTLS 1.2 are supported
With that, no detection or ability to disable a version will be provided
Add a `--prometheus-path` parameter which allows users to specify at
what
path the metrics should be exposed.
This simplifies serving metrics on a specific path behind some
restrictive reverse proxies that expect the upstream server to serve
URLs with paths matching the requested path.
Co-authored-by: Pavel Punsky <eakraly@users.noreply.github.com>
Openssl 1.1.1 is end-of-life in September 2023.
This PR removes support for versions of openssl OLDER than 1.1.1
1.1.1 should still be usable after this change is merged.
I don't see any value in supporting 1.1.1, but didn't see a reason to
purge support for 1.1.1 when there are so few checks for >= 3.0.
Note that this does also remove CI support for Ubuntu 16.04. The
official version of OpenSSL from Ubuntu for this release is listed here:
https://launchpad.net/ubuntu/+source/openssl as 1.0.2g
Since no newer releases of coturn will be backported by Canonical to
Ubuntu 16.04, anyone using Coturn on this operating system will have to
download and compile it themselves. They may build their own version of
OpenSSL if they somehow cannot upgrade to a newer version of Ubuntu.
My position is that these users should prefer to upgrade to a newer
operating system than worry about chasing newer releases of Coturn.
Co-authored-by: Pavel Punsky <eakraly@users.noreply.github.com>
Following configuration options deleted:
- `--secret-ts-exp-time`
- `--prod` - disables SOFTWARE_ATTRIBUTE in messages. Now it is default.
To enable SOFTWARE_ATTRIBUTE use `--software-attribute`
- `--no-sslv2`, `--no-sslv3` - old versions of SSL are not supported and
it is not possible to enable them
These are breaking changes - if the CLI command has any of those
arguments it will cause turnserver to terminate and notify about unknown
argument
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