4449 Commits

Author SHA1 Message Date
Daniel Donoghue
61ba588d58 stasis_broadcast: Add optional ARI broadcast with first-claim-wins
Adds two optional modules:
res_stasis_broadcast.so: Infrastructure for broadcasting a single incoming
channel to multiple ARI applications with atomic first-claim-wins semantics.

app_stasis_broadcast.so: Provides the StasisBroadcast() dialplan application
which invokes the broadcast infrastructure.

Both modules are self-contained; if neither is loaded there is zero runtime
impact. Loading them does not alter existing Stasis or ARI behavior unless
explicitly used.

Key Features (only active when modules are loaded):
Fisher-Yates shuffled broadcast dispatch for fair claim races
Atomic claim operations using mutex + condition variable signaling
Configurable broadcast timeouts
Safe regex application filtering with validation to mitigate ReDoS risk
Thread-safe channel variable snapshotting (channel locked during reads)
Late-claim safety: broadcast context kept alive until after the Stasis
session ends so concurrent claimants always receive 409 Conflict rather
than 404 Not Found
Memory safety via RAII_VAR, ast_json_ref/unref, and ao2 reference counting

Components Added:
res/res_stasis_broadcast.c: Core broadcast + claim logic
apps/app_stasis_broadcast.c: StasisBroadcast() dialplan application
include/asterisk/stasis_app_broadcast.h: Public API header
res/ari/resource_events.c: Integrates POST /ari/events/claim endpoint
rest-api/api-docs/events.json: New CallBroadcast and CallClaimed events

Implementation Notes:
Broadcast contexts reside in an ao2 hash container keyed by channel id. Each
context holds atomic claim state, winner application name, timeout metadata,
and a condition variable for waiters. Broadcast contexts are kept alive until
after stasis_app_exec() returns so that concurrent claimants racing against
the timeout always receive 409 Conflict. Broadcast dispatch calls
stasis_app_send() directly for each matching application in shuffled order.
Regex filters are validated with bounded length, group depth, quantified
group count, and alternation limits to reduce pathological backtracking.
Timeout calculation uses timespec arithmetic with overflow-safe millisecond
remainder handling. Event JSON follows existing Stasis/ARI conventions;
references are managed correctly to avoid leaks or double frees.

Optional Nature / Impact:
No changes to existing APIs, events, or applications when absent.
Clean fallback: systems ignoring the modules behave identically to prior
versions.

Development was assisted by Claude (Anthropic). All generated code has been
reviewed, tested, and is understood by the author.

UserNote: New optional modules res_stasis_broadcast.so and
app_stasis_broadcast.so enable broadcasting an incoming channel to multiple
ARI applications. The first application to successfully claim (via
POST /ari/events/claim) wins channel control. StasisBroadcast() dialplan
application initiates broadcasts. CallBroadcast and CallClaimed events notify
applications. When modules are not loaded, behavior is unchanged.

DeveloperNote: New public APIs in stasis_app_broadcast.h:
stasis_app_broadcast_channel(), stasis_app_claim_channel(),
stasis_app_broadcast_winner(), and stasis_app_broadcast_wait(). New ARI event
types (CallBroadcast, CallClaimed) added to events.json. All code is isolated;
no existing ABI modified.
2026-04-22 18:05:00 +00:00
Daniel Donoghue
f845b71c75 res_pjsip_maintenance: Add PJSIP endpoint maintenance mode
Introduces res_pjsip_maintenance, a loadable module that allows
operators to place individual PJSIP endpoints into maintenance mode
at runtime without unregistering or disabling them.

While an endpoint is in maintenance mode:
 * New inbound INVITE and SUBSCRIBE dialogs are rejected with
   503 Service Unavailable and a Retry-After: 300 header.
 * In-progress dialogs (re-INVITE, UPDATE, BYE, etc.) are
   unaffected and complete normally.
 * Outbound originations via Dial() or ARI originate are refused
   before any SIP session is created.

State is held in-memory only and is cleared on module unload
or Asterisk restart.

This module was developed with AI assistance (Claude).  All code
has been reviewed and tested by the author, who takes full
responsibility for the submission.

CLI interface:
  pjsip set maintenance <on|off> <endpoint|all>
  pjsip show maintenance [endpoint]

AMI interface:
  Action: PJSIPSetMaintenance
  Endpoint: <name>|all
  State: on|off

  Action: PJSIPShowMaintenance
  Endpoint: <name>  (optional; omit to list all)

  Emits PJSIPMaintenanceStatus events per result, followed by
  PJSIPMaintenanceStatusComplete. State changes also emit an
  unsolicited PJSIPMaintenanceStatus event.

To support outbound blocking, a new session_create callback is
added to ast_sip_session_supplement. Supplements that set this
callback are invoked at the start of ast_sip_session_create_outgoing()
in res_pjsip_session, before any dialog or invite session resources
are allocated. res_pjsip_maintenance registers itself as a session
supplement and uses this callback to gate outbound session creation
on a per-endpoint basis.

MODULEINFO:
  <depend>pjproject</depend>
  <depend>res_pjsip</depend>
  <depend>res_pjsip_session</depend>

UserNote: New module res_pjsip_maintenance adds runtime maintenance
mode for PJSIP endpoints. Use "pjsip set maintenance <on|off>
<endpoint|all>" to enable or disable, and "pjsip show maintenance"
to list affected endpoints. AMI actions PJSIPSetMaintenance and
PJSIPShowMaintenance provide programmatic access. No configuration
file changes required.

DeveloperNote: ast_sip_session_supplement gains a new optional
callback - int (*session_create)(struct ast_sip_endpoint *endpoint,
const char *destination). It is called from the global supplement
list (not per-session) at the start of ast_sip_session_create_outgoing()
via ast_sip_session_check_supplement_create(). Returning non-zero
blocks the outgoing session. Modules that need to gate outbound
SIP session creation should register a supplement with this callback
set rather than hooking into chan_pjsip directly.
2026-04-16 18:25:34 +00:00
Alexei Gradinari
161f12fd99 build: remove pjsua, pjsystest, Python bindings and asterisk_malloc_debug stubs from pjproject dev build
The pjsua Python module and the pjsua/pjsystest apps were used by the
Asterisk Test Suite for SIP simulation in dev mode builds. They are now
fully obsolete for three independent reasons:

1. **pjsua Python bindings officially deprecated upstream.** The pjproject
   maintainers added `pjsip-apps/src/python/DEPRECATED.txt` directing
   users to the PJSUA2 SWIG binding instead. A build-fix PR
   (https://github.com/pjsip/pjproject/pull/4892) was closed by the
   maintainer explicitly citing this deprecation.

2. **Removed from the Asterisk Test Suite.** As confirmed by @mbradeen:
   > *"We had to get rid of pjsua when we went to Python3 because it would
   > hang due to a conflict between async calls within pjsua and twisted.
   > There are still some old references to tests we couldn't fully convert
   > to sipp, but those are skipped."*

3. **Broken and unmaintained.** Building with Python 2.7 (the only version
   `configure.ac` searched for) fails with:
   ```
   _pjsua.c: error: 'INIT_RETURN' undeclared (first use in this function)
   ```
   due to a bug in pjproject 2.16's `python3_compat.h` that upstream
   declined to fix.

This PR removes all pjsua-related build artifacts from Asterisk's bundled
pjproject build: the pjsua and pjsystest application binaries, the deprecated
Python (`_pjsua.so`) bindings, the `asterisk_malloc_debug.c` stubs, and the
`PYTHONDEV` detection from `configure.ac`. Also removes `libpjsua` from
Asterisk's main linker flags.

DeveloperNote: The pjsua and pjsystest application binaries, the deprecated
Python pjsua bindings (`_pjsua.so`), and the `asterisk_malloc_debug.c` stub
implementations are no longer built or installed as part of the bundled
pjproject dev mode build. The `PYTHONDEV` (python2.7-dev) build dependency
is also removed. Developers who relied on the pjsua binary for Test Suite
SIP simulation should use SIPp instead, which is the current Asterisk Test
Suite standard.

Fixes: #1840
2026-04-07 17:18:36 +00:00
George Joseph
34b015599c chan_pjsip: Set correct cause codes for non-2XX responses.
Redirects initiated by 302 response codes weren't handled correctly
when setting the hangup cause code and tech cause code on the responding
channel.  They're now set to 23 (REDIRECTED_TO_NEW_DESTINATION) and
302 (Moved permanently).  Other non-2XX response codes also had issues.

A new API ast_channel_dialed_causes_iterator() was added to retrieve
the hangup cause codes for a channel.

chan_pjsip_session_end() in chan_pjsip has been refactored to set the
correct cause codes on a channel based on the cause codes added by
chan_pjsip_incoming_response_update_cause().  Copious amounts of
debugging and comments were also added.

Resolves: #1819
2026-03-17 16:15:36 +00:00
Naveen Albert
016b951816 dsp.c: Add support for detecting R2 signaling tones.
Extend the existing DTMF/MF tone detection support by adding support
for R2 tones, another variant of MF (R1) signaling. Both forward
and backward signaling are supported.

Resolves: #1804
2026-03-03 22:07:20 +00:00
George Joseph
00c4346307 docs: Add "Provided-by" to doc XML and CLI output.
For application, function, manager, managerEvent, managerEventInstance
and info XML documentation nodes, the make_xml_documentation script will
add a "module" attribute if not already present.  For XML in separate
"*_doc.xml" files, the script figures out the correct module name.  For
documentation in the "main" directory, the module name is set to "builtin".

The CLI handlers for "core show application", "core show function",
"manager show command" and "manager show event", have been updated to
show the following after the Synopsis...

```
[Provided By]
<modulename>
```

For modules that provide additional "info" elements (like the technologies
do for Dial), the providing module has also been added.

```
Technology: WebSocket  Provided by: chan_websocket
WebSocket Dial Strings:
...
```

UserNote: The CLI help for applications, functions, manager commands and
manager events now shows the module that provides its functionality.
2026-03-03 18:55:45 +00:00
George Joseph
9c23df049d CDR/CEL Custom Performance Improvements
There is a LOT of work in this commit but the TL;DR is that it takes
CEL processing from using 38% of the CPU instructions used by a call,
which is more than that used by the call processing itself, down to less
than 10% of the instructions.

So here's the deal...  cdr_custom, cdr_sqlite3_custom, cel_custom
and cel_sqlite3_custom all shared one ugly trait...they all used
ast_str_substitute_variables() or pbx_substitute_variables_helper()
to resolve the dialplan functions used in their config files.  Not only
are they both extraordinarily expensive, they both require a dummy
channel to be allocated and destroyed for each record written.  For CDRs,
that's not too bad because we only write one CDR per call.  For CELs however,
it's a disaster.

As far as source code goes, the modules basically all did the same thing.
Unfortunately, they did it badly.  The config files simply contained long
opaque strings which were intepreted by ast_str_substitute_variables() or
pbx_substitute_variables_helper(), the very functions that ate all the
instructions.  This meant introducing a new "advanced" config format much
like the advanced manager event filtering added to manager.conf in 2024.
Fortunately however, if the legacy config was recognizable, we were able to
parse it as an advanced config and gain the benefit.  If not, then it
goes the legacy, and very expensive, route.

Given the commonality among the modules, instead of making the same
improvements to 4 modules then trying to maintain them over time, a single
module "res_cdrel_custom" was created that contains all of the common code.
A few bonuses became possible in the process...
* The cdr_custom and cel_custom modules now support JSON formatted output.
* The cdr_sqlite_custom and cel_sqlite3_custom modules no longer have
  to share an Sqlite3 database.

Summary of changes:

A new module "res/res_cdrel_custom.c" has been created and the existing
cdr_custom, cdr_sqlite3_custom, cel_custom and cel_sqlite3_custom modules
are now just stubs that call the code in res_cdrel_custom.

res_cdrel_custom contains:
* A common configuration facility.
* Getters for both CDR and CEL fields that share the same abstraction.
* Formatters for all data types found in the ast_cdr and ast_event
  structures that share the same abstraction.
* Common writers for the text file and database backends that, you guessed it,
  share the same abstraction.

The result is that while there is certainly a net increase in the number of
lines in the code base, most of it is in the configuration handling at
load-time.  The run-time instruction path length is now significanty shorter.

```
Scenario                   Instructions     Latency
=====================================================
CEL pre changes                  38.49%     37.51%
CEL Advanced                      9.68%      6.06%
CEL Legacy (auto-conv to adv)     9.95%      6.13%

CEL Sqlite3 pre changes          39.41%     39.90%
CEL Sqlite3 Advanced             25.68%     24.24%
CEL Sqlite3 Legacy (auto conv)   25.88%     24.53%

CDR pre changes                   4.79%      2.95%
CDR Advanced                      0.79%      0.47%
CDR Legacy (auto conv to adv)     0.86%      0.51%

CDR Sqlite3 pre changes           4.47%      2.89%
CEL Sqlite3 Advanced              2.16%      1.29%
CEL Sqlite3 Legacy (auto conv)    2.19%      1.30%
```

Notes:
* We only write one CDR per call but every little bit helps.
* Sqlite3 still takes a fair amount of resources but the new config
  makes a decent improvement.
* Legacy configs that we can't auto convert will still take the
  "pre changes" path.

If you're interested in more implementation details, see the comments
at the top of the res_cdrel_custom.c file.

One minor fix to CEL is also included...Although TenantID was added to the
ast_event structure, it was always rendered as an empty string.  It's now
properly rendered.

UserNote: Significant performance improvements have been made to the
cdr_custom, cdr_sqlite3_custom, cel_custom and cel_sqlite3_custom modules.
See the new sample config files for those modules to see how to benefit
from them.
2026-03-02 16:43:24 +00:00
Prashant Srivastav
d4e366145f fix: Add macOS (Darwin) compatibility for building Asterisk
- Makefile: Skip /usr/lib/bundle1.o on modern macOS (doesn't exist)
- Makefile.rules: Skip -fno-partial-inlining for clang (gcc-only flag)
- include/asterisk/utils.h: Use asterisk/endian.h instead of <endian.h>
- main/Makefile: Add Darwin-specific pjproject linking with -force_load
- main/strcompat.c: Include poll-compat.h, use ast_poll()
- main/xml.c: Add ASTMM_LIBC ASTMM_IGNORE for libxml2 compatibility
- res/res_pjsip/config_transport.c: Define TCP keepalive constants for macOS

Tested on macOS Darwin 25.2.0 (Apple Silicon ARM64)
2026-02-26 15:51:02 +00:00
Joshua C. Colp
ef921d5db5 endpoints: Allow access to latest snapshot directly.
This change adds an API call to allow direct access to the latest
snapshot of an ast_endpoint. This is then used by chan_pjsip when
calculating device state, eliminating the need to access the cache
which would incur a container find and access.
2026-02-17 13:31:24 +00:00
Naveen Albert
30f8fdc847 app_dial, utils.h: Avoid old style declaration and discarded qualifier.
* app_dial: Use const char* for fixed strings.
* utils.h: inline should come before return type.

Resolves: #1755
2026-02-11 13:34:28 +00:00
Sean Bright
544e8b7950 cli.c: Allow 'channel request hangup' to accept patterns.
This extends 'channel request hangup' to accept multiple channel
names, a POSIX Extended Regular Expression, a glob-like pattern, or a
combination of all of them.

UserNote: The 'channel request hangup' CLI command now accepts
multiple channel names, POSIX Extended Regular Expressions, glob-like
patterns, or a combination of all of them. See the CLI command 'core
show help channel request hangup' for full details.
2026-01-13 16:03:24 +00:00
George Joseph
a1c3677d4a chan_websocket: Use the channel's ability to poll fds for the websocket read.
We now add the websocket's file descriptor to the channel's fd array and let
it poll for data availability instead if having a dedicated thread that
does the polling. This eliminates the thread and allows removal of most
explicit locking since the core channel code will lock the channel to prevent
simultaneous calls to webchan_read, webchan_hangup, etc.

While we were here, the hangup code was refactored to use ast_hangup_with_cause
instead of directly queueing an AST_CONTROL_HANGUP frame.  This allows us
to set hangup causes and generate snapshots.

For a bit of extra debugging, a table of websocket close codes was added
to http_websocket.h with an accompanying "to string" function added to
res_http_websocket.c

Resolves: #1683
2026-01-05 14:49:20 +00:00
George Joseph
445130eeab res_geolocation: Fix multiple issues with XML generation.
* 3d positions were being rendered without an enclosing `<gml:pos>`
  element resulting in invalid XML.
* There was no way to set the `id` attribute on the enclosing `tuple`, `device`
  and `person` elements.
* There was no way to set the value of the `deviceID` element.
* Parsing of degree and radian UOMs was broken resulting in them appearing
  outside an XML element.
* The UOM schemas for degrees and radians were reversed.
* The Ellipsoid shape was missing and the Ellipse shape was defined multiple
  times.
* The `crs` location_info parameter, although documented, didn't work.
* The `pos3d` location_info parameter appears in some documentation but
  wasn't being parsed correctly.
* The retransmission-allowed and retention-expiry sub-elements of usage-rules
  were using the `gp` namespace instead of the `gbp` namespace.

In addition to fixing the above, several other code refactorings were
performed and the unit test enhanced to include a round trip
XML -> eprofile -> XML validation.

Resolves: #1667

UserNote: Geolocation: Two new optional profile parameters have been added.
* `pidf_element_id` which sets the value of the `id` attribute on the top-level
  PIDF-LO `device`, `person` or `tuple` elements.
* `device_id` which sets the content of the `<deviceID>` element.
Both parameters can include channel variables.

UpgradeNote: Geolocation: In order to correct bugs in both code and
documentation, the following changes to the parameters for GML geolocation
locations are now in effect:
* The documented but unimplemented `crs` (coordinate reference system) element
  has been added to the location_info parameter that indicates whether the `2d`
  or `3d` reference system is to be used. If the crs isn't valid for the shape
  specified, an error will be generated. The default depends on the shape
  specified.
* The Circle, Ellipse and ArcBand shapes MUST use a `2d` crs.  If crs isn't
  specified, it will default to `2d` for these shapes.
  The Sphere, Ellipsoid and Prism shapes MUST use a `3d` crs. If crs isn't
  specified, it will default to `3d` for these shapes.
  The Point and Polygon shapes may use either crs.  The default crs is `2d`
  however so if `3d` positions are used, the crs must be explicitly set to `3d`.
* The `geoloc show gml_shape_defs` CLI command has been updated to show which
  coordinate reference systems are valid for each shape.
* The `pos3d` element has been removed in favor of allowing the `pos` element
  to include altitude if the crs is `3d`.  The number of values in the `pos`
  element MUST be 2 if the crs is `2d` and 3 if the crs is `3d`.  An error
  will be generated for any other combination.
* The angle unit-of-measure for shapes that use angles should now be included
  in the respective parameter.  The default is `degrees`. There were some
  inconsistent references to `orientation_uom` in some documentation but that
  parameter never worked and is now removed.  See examples below.
Examples...
```
  location_info = shape="Sphere", pos="39.0 -105.0 1620", radius="20"
  location_info = shape="Point", crs="3d", pos="39.0 -105.0 1620"
  location_info = shape="Point", pos="39.0 -105.0"
  location_info = shape=Ellipsoid, pos="39.0 -105.0 1620", semiMajorAxis="20"
                semiMinorAxis="10", verticalAxis="0", orientation="25 degrees"
  pidf_element_id = ${CHANNEL(name)}-${EXTEN}
  device_id = mac:001122334455
  Set(GEOLOC_PROFILE(pidf_element_id)=${CHANNEL(name)}/${EXTEN})
```
2026-01-05 12:45:04 +00:00
Maximilian Fridrich
569b3ed995 res_pjsip: Introduce redirect module for handling 3xx responses
This commit introduces a new redirect handling module that provides
infrastructure for following SIP 3xx redirect responses. The redirect
functionality respects the endpoint's redirect_method setting and only
follows redirects when set to 'uri_pjsip'. This infrastructure can be
used by any PJSIP module that needs to handle 3xx redirect responses.
2025-12-30 15:09:28 +00:00
Justin T. Gibbs
0e8a22caf0 rtp/rtcp: Configure dual-stack behavior via IPV6_V6ONLY
Dual-stack behavior (simultaneous listening for IPV4 and IPV6
connections on a single socket) is required by Asterisk's ICE
implementation.  On systems with the IPV6_V6ONLY sockopt, set
the option to 0 (dual-stack enabled) when binding to the IPV6
any address. This ensures correct behavior regardless of the
system's default dual-stack configuration.
2025-12-29 18:04:52 +00:00
Joshua C. Colp
6c047d3da5 pjsip: Move from threadpool to taskpool
This change moves the PJSIP module from the threadpool API
to the taskpool API. PJSIP-specific implementations for
task usage have been removed and replaced with calls to
the optimized taskpool implementations instead. The need
for a pool of serializers has also been removed as
taskpool inherently provides this. The default settings
have also been changed to be more realistic for common
usage.

UpgradeNote: The threadpool_* options in pjsip.conf have now
been deprecated though they continue to be read and used.
They have been replaced with taskpool options that give greater
control over the underlying taskpool used for PJSIP. An alembic
upgrade script has been added to add these options to realtime
as well.
2025-12-16 17:03:43 +00:00
Sean Bright
0a83b87b4c Revert "func_hangupcause.c: Add access to Reason headers via HANGUPCAUSE()"
This reverts commit 5177662990.

For rationale, see #1621 and #1606
2025-12-09 17:04:07 +00:00
Mike Bradeen
e016ba689a taskprocessors: Improve logging and add new cli options
This change makes some small changes to improve log readability in
addition to the following changes:

Modified 'core show taskprocessors' to now show Low time and High time
for task execution.

New command 'core show taskprocessor name <taskprocessor-name>' to dump
taskprocessor info and current queue.

Addionally, a new test was added to demonstrate the 'show taskprocessor
name' functionality:
test execute category /main/taskprocessor/ name taskprocessor_cli_show

Setting 'core set debug 3 taskprocessor.c' will now log pushed tasks.
(Warning this is will cause extremely high levels of logging at even
low traffic levels.)

Resolves: #1566

UserNote: New CLI command has been added -
core show taskprocessor name <taskprocessor-name>
2025-12-04 16:13:02 +00:00
George Joseph
1f47f6a836 ccss: Add option to ccss.conf to globally disable it.
The Call Completion Supplementary Service feature is rarely used but many of
it's functions are called by app_dial and channel.c "just in case".  These
functions lock and unlock the channel just to see if CCSS is enabled on it,
which it isn't 99.99% of the time.

UserNote: A new "enabled" parameter has been added to ccss.conf.  It defaults
to "yes" to preserve backwards compatibility but CCSS is rarely used so
setting "enabled = no" in the "general" section can save some unneeded channel
locking operations and log message spam.  Disabling ccss will also prevent
the func_callcompletion and chan_dahdi modules from loading.

DeveloperNote: A new API ast_is_cc_enabled() has been added.  It should be
used to ensure that CCSS is enabled before making any other ast_cc_* calls.
2025-12-01 14:05:53 +00:00
Joshua C. Colp
323f779a58 Revert "pjsip: Move from threadpool to taskpool"
This reverts commit bb6b76c2d8.
2025-10-28 12:44:52 +00:00
Joshua C. Colp
6b8e4b6106 pjsip: Move from threadpool to taskpool
This change moves the PJSIP module from the threadpool API
to the taskpool API. PJSIP-specific implementations for
task usage have been removed and replaced with calls to
the optimized taskpool implementations instead. The need
for a pool of serializers has also been removed as
taskpool inherently provides this. The default settings
have also been changed to be more realistic for common
usage.

UpgradeNote: The threadpool_* options in pjsip.conf have now
been deprecated though they continue to be read and used.
They have been replaced with taskpool options that give greater
control over the underlying taskpool used for PJSIP. An alembic
upgrade script has been added to add these options to realtime
as well.
2025-10-22 16:32:48 +00:00
Christoph Moench-Tegeder
0f4472367a Fix Endianness detection in utils.h for non-Linux
Commit 43bf8a4ded introduced endian
dependend byte-swapping code in include/asterisk/utils.h, where the
endianness was detected using the __BYTE_ORDER macro. This macro
lives in endian.h, which on Linux is included implicitely (by the
network-related headers, I think), but on FreeBSD the headers are
laid out differently and we do not get __BYTE_ORDER the implicit way.

Instead, this makes the usage of endian.h explicit by including it
where we need it, and switches the BYTE_ORDER/*ENDIAN macros to the
POSIX-defined ones (see
https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/endian.h.html
for standard compliance). Additionally, this adds a compile-time check
for the endianness-logic: compilation will fail if neither big nor
little endian can be detected.

Fixes: #1536
2025-10-22 16:27:01 +00:00
George Joseph
721fb4ed03 chan_pjsip: Add technology-specific off-nominal hangup cause to events.
Although the ISDN/Q.850/Q.931 hangup cause code is already part of the ARI
and AMI hangup and channel destroyed events, it can be helpful to know what
the actual channel technology code was if the call was unsuccessful.
For PJSIP, it's the SIP response code.

* A new "tech_hangupcause" field was added to the ast_channel structure along
with ast_channel_tech_hangupcause() and ast_channel_tech_hangupcause_set()
functions.  It should only be set for off-nominal terminations.

* chan_pjsip was modified to set the tech hangup cause in the
chan_pjsip_hangup() and chan_pjsip_session_end() functions.  This is a bit
tricky because these two functions aren't always called in the same order.
The channel that hangs up first will get chan_pjsip_session_end() called
first which will trigger the core to call chan_pjsip_hangup() on itself,
then call chan_pjsip_hangup() on the other channel.  The other channel's
chan_pjsip_session_end() function will get called last.  Unfortunately,
the other channel's HangupRequest events are sent before chan_pjsip has had a
chance to set the tech hangupcause code so the HangupRequest events for that
channel won't have the cause code set.  The ChannelDestroyed and Hangup
events however will have the code set for both channels.

* A new "tech_cause" field was added to the ast_channel_snapshot_hangup
structure. This is a public structure so a bit of refactoring was needed to
preserve ABI compatibility.

* The ARI ChannelHangupRequest and ChannelDestroyed events were modified to
include the "tech_cause" parameter in the JSON for off-nominal terminations.
The parameter is suppressed for nominal termination.

* The AMI SoftHangupRequest, HangupRequest and Hangup events were modified to
include the "TechCause" parameter for off-nominal terminations. Like their ARI
counterparts, the parameter is suppressed for nominal termination.

DeveloperNote: A "tech_cause" parameter has been added to the
ChannelHangupRequest and ChannelDestroyed ARI event messages and a "TechCause"
parameter has been added to the HangupRequest, SoftHangupRequest and Hangup
AMI event messages.  For chan_pjsip, these will be set to the last SIP
response status code for off-nominally terminated calls.  The parameter is
suppressed for nominal termination.
2025-10-20 13:22:48 +00:00
Sven Kube
f32e52721d res_audiosocket: add message types for all slin sample rates
Extend audiosocket messages with types 0x11 - 0x18 to create asterisk
frames in slin12, slin16, slin24, slin32, slin44, slin48, slin96, and
slin192 format, enabling the transmission of audio at a higher sample
rates. For audiosocket messages sent by Asterisk, the message kind is
determined by the format of the originating asterisk frame.

UpgradeNote: New audiosocket message types 0x11 - 0x18 has been added
for slin12, slin16, slin24, slin32, slin44, slin48, slin96, and
slin192 audio. External applications using audiosocket may need to be
updated to support these message types if the audiosocket channel is
created with one of these audio formats.
2025-10-17 13:05:27 +00:00
Joshua C. Colp
ddc38c6e48 endpoints: Remove need for stasis subscription.
When an endpoint is created in the core of Asterisk a subscription
was previously created alongside it to monitor any channels being
destroyed that were related to it. This was done by receiving all
channel snapshot updates for every channel and only reacting when
it was indicated that the channel was dead.

This change removes this logic and instead provides an API call
for directly removing a channel from an endpoint. This is called
when channels are destroyed. This operation is fast, so blocking
the calling thread for a short period of time doesn't have any
noticeable impact.
2025-10-14 20:01:56 +00:00
George Joseph
6d4ac1f562 taskpool: Fix some references to threadpool that should be taskpool.
Resolves: #1478
2025-10-13 15:34:12 +00:00
Igor Goncharovsky
3486a5d569 func_hangupcause.c: Add access to Reason headers via HANGUPCAUSE()
As soon as SIP call may end with several Reason headers, we
want to make all of them available through the HAGUPCAUSE() function.
This implementation uses the same ao2 hash for cause codes storage
and adds a flag to make difference between last processed sip
message and content of reason headers.

UserNote: Added a new option to HANGUPCAUSE to access additional
information about hangup reason. Reason headers from pjsip
could be read using 'tech_extended' cause type.
2025-10-07 15:26:57 +00:00
Bastian Triller
f7c64ff3ee Fix some doxygen, typos and whitespace 2025-09-22 17:39:09 +00:00
Joshua C. Colp
1dc6fecc21 taskpool: Add taskpool API, switch Stasis to using it.
This change introduces a new API called taskpool. This is a pool
of taskprocessors. It provides the following functionality:

1. Task pushing to a pool of taskprocessors
2. Synchronous tasks
3. Serializers for execution ordering of tasks
4. Growing/shrinking of number of taskprocessors in pool

This functionality already exists through the combination of
threadpool+taskprocessors but through investigating I determined
that this carries substantial overhead for short to medium duration
tasks. The threadpool uses a single queue of work, and for management
of threads it involves additional tasks.

I wrote taskpool to eliminate the extra overhead and management
as much as possible. Instead of a single queue of work each
taskprocessor has its own queue and at push time a selector chooses
the taskprocessor to queue the task to. Each taskprocessor also
has its own thread like normal. This spreads out the tasks immediately
and reduces contention on shared resources.

Using the included efficiency tests the number of tasks that can be
executed per second in a taskpool is 6-12 times more than an equivalent
threadpool+taskprocessor setup.

Stasis has been moved over to using this new API as it is a heavy consumer
of threadpool+taskprocessors and produces a lot of tasks.

UpgradeNote: The threadpool_* options in stasis.conf have now been deprecated
though they continue to be read and used. They have been replaced with taskpool
options that give greater control over the underlying taskpool used for stasis.

DeveloperNote: The taskpool API has been added for common usage of a
pool of taskprocessors. It is suggested to use this API instead of the
threadpool+taskprocessor approach.
2025-09-16 17:21:23 +00:00
Alexei Gradinari
a6142af2a0 sorcery: Prevent duplicate objects and ensure missing objects are created on update
This patch resolves two issues in Sorcery objectset handling with multiple
backends:

1. Prevent duplicate objects:
   When an object exists in more than one backend (e.g., a contact in both
   'astdb' and 'realtime'), the objectset previously returned multiple instances
   of the same logical object. This caused logic failures in components like the
   PJSIP registrar, where duplicate contact entries led to overcounting and
   incorrect deletions, when max_contacts=1 and remove_existing=yes.

   This patch ensures only one instance of an object with a given key is added
   to the objectset, avoiding these duplicate-related side effects.

2. Ensure missing objects are created:
   When using multiple writable backends, a temporary backend failure can lead
   to objects missing permanently from that backend.
   Currently, .update() silently fails if the object is not present,
   and no .create() is attempted.
   This results in inconsistent state across backends (e.g. astdb vs. realtime).

   This patch introduces a new global option in sorcery.conf:
     [general]
     update_or_create_on_update_miss = yes|no

   Default: no (preserves existing behavior).

   When enabled: if .update() fails with no data found, .create() is attempted
   in that backend. This ensures that objects missing due to temporary backend
   outages are re-synchronized once the backend is available again.

   Added a new CLI command:
     sorcery show settings
   Displays global Sorcery settings, including the current value of
   update_or_create_on_update_miss.

   Updated tests to validate both flag enabled/disabled behavior.

Fixes: #1289

UserNote: Users relying on Sorcery multiple writable backends configurations
(e.g., astdb + realtime) may now enable update_or_create_on_update_miss = yes
in sorcery.conf to ensure missing objects are recreated after temporary backend
failures. Default behavior remains unchanged unless explicitly enabled.
2025-08-27 16:56:12 +00:00
George Joseph
de6aaa9623 chan_websocket: Allow additional URI parameters to be added to the outgoing URI.
* Added a new option to the WebSocket dial string to capture the additional
  URI parameters.
* Added a new API ast_uri_verify_encoded() that verifies that a string
  either doesn't need URI encoding or that it has already been encoded.
* Added a new API ast_websocket_client_add_uri_params() to add the params
  to the client websocket session.
* Added XML documentation that will show up with `core show application Dial`
  that shows how to use it.

Resolves: #1352

UserNote: A new WebSocket channel driver option `v` has been added to the
Dial application that allows you to specify additional URI parameters on
outgoing connections. Run `core show application Dial` from the Asterisk CLI
to see how to use it.
2025-08-20 15:33:35 +00:00
Sven Kube
a0b36f8099 ARI: Add command to indicate progress to a channel
Adds an ARI command to send a progress indication to a channel.

DeveloperNote: A new ARI endpoint is available at `/channels/{channelId}/progress` to indicate progress to a channel.
2025-08-18 16:29:44 +00:00
Sperl Viktor
0906282f25 cel: Add STREAM_BEGIN, STREAM_END and DTMF event types.
Fixes: #1280

UserNote: Enabling the tracking of the
STREAM_BEGIN and the STREAM_END event
types in cel.conf will log media files and
music on hold played to each channel.
The STREAM_BEGIN event's extra field will
contain a JSON with the file details (path,
format and language), or the class name, in
case of music on hold is played. The DTMF
event's extra field will contain a JSON with
the digit and the duration in milliseconds.
2025-08-11 13:52:24 +00:00
zhou_jiajian
9d4674d93d cdr: add CANCEL dispostion in CDR
In the original implementation, both CANCEL and NO ANSWER states were
consolidated under the NO ANSWER disposition. This patch introduces a
separate CANCEL disposition, with an optional configuration switch to
enable this new disposition.

Resolves: #1323

UserNote: A new CDR option "canceldispositionenabled" has been added
that when set to true, the NO ANSWER disposition will be split into
two dispositions: CANCEL and NO ANSWER. The default value is 'no'
2025-08-06 15:37:46 +00:00
George Joseph
d1a1945967 options: Change ast_options from ast_flags to ast_flags64.
DeveloperNote: The 32-bit ast_options has no room left to accomodate new
options and so has been converted to an ast_flags64 structure. All internal
references to ast_options have been updated to use the 64-bit flag
manipulation macros.  External module references to the 32-bit ast_options
should continue to work on little-endian systems because the
least-significant bytes of a 64 bit integer will be in the same location as a
32-bit integer.  Because that's not the case on big-endian systems, we've
swapped the bytes in the flags manupulation macros on big-endian systems
so external modules should still work however you are encouraged to test.
2025-07-30 15:59:21 +00:00
Alexei Gradinari
9e3ea1c8ac res_config_odbc: Prevent Realtime fallback on record-not-found (SQL_NO_DATA)
This patch fixes an issue in the ODBC Realtime engine where Asterisk incorrectly
falls back to the next configured backend when the current one returns
SQL_NO_DATA (i.e., no record found).
This is a logical error and performance risk in multi-backend configurations.

Solution:
Introduced CONFIG_RT_NOT_FOUND ((void *)-1) as a special return marker.
ODBC Realtime backend now return CONFIG_RT_NOT_FOUND when no data is found.
Core engine stops iterating on this marker, avoiding unnecessary fallback.

Notes:
Other Realtime backends (PostgreSQL, LDAP, etc.) can be updated similarly.
This patch only covers ODBC.

Fixes: #1305
2025-07-30 15:38:25 +00:00
George Joseph
07fd3af897 Media over Websocket Channel Driver
* Created chan_websocket which can exchange media over both inbound and
outbound websockets which the driver will frame and time.
See http://s.asterisk.net/mow for more information.

* res_http_websocket: Made defines for max message size public and converted
a few nuisance verbose messages to debugs.

* main/channel.c: Changed an obsolete nuisance error to a debug.

* ARI channels: Updated externalMedia to include chan_websocket as a supported
transport.

UserNote: A new channel driver "chan_websocket" is now available. It can
exchange media over both inbound and outbound websockets and will both frame
and re-time the media it receives.
See http://s.asterisk.net/mow for more information.

UserNote: The ARI channels/externalMedia API now includes support for the
WebSocket transport provided by chan_websocket.
2025-07-09 17:42:16 +00:00
mkmer
55f4294e82 utils.h: Add rounding to float conversion to int.
Quote from an audio engineer NR9V:
There is a minor issue of a small amount of crossover distortion though as a result of `ast_slinear_saturated_multiply_float()` not rounding the float. This could result in some quiet but potentially audible distortion artifacts in lower volume parts of the signal. If you have for example a sign wave function with a max amplitude of just a few samples, all samples between -1 and 1 will be truncated to zero, resulting in the waveform no longer being a sine wave and in harmonic distortion.

Resolves: #1176
2025-06-27 15:38:29 +00:00
Tinet-mucw
88f653c12d pbx.c: when set flag AST_SOFTHANGUP_ASYNCGOTO, ast_explicit_goto should return -1.
Under certain circumstances the context/extens/prio are set in the ast_async_goto, for example action Redirect.
In the situation that action Redirect is broken by GotoIf this info is changed.
that will causes confusion in dialplan execution.

Resolves: #1273
2025-06-27 15:37:30 +00:00
George Joseph
87097b3dd1 ARI Outbound Websockets
Asterisk can now establish websocket sessions _to_ your ARI applications
as well as accepting websocket sessions _from_ them.
Full details: http://s.asterisk.net/ari-outbound-ws

Code change summary:
* Added an ast_vector_string_join() function,
* Added ApplicationRegistered and ApplicationUnregistered ARI events.
* Converted res/ari/config.c to use sorcery to process ari.conf.
* Added the "outbound-websocket" ARI config object.
* Refactored res/ari/ari_websockets.c to handle outbound websockets.
* Refactored res/ari/cli.c for the sorcery changeover.
* Updated res/res_stasis.c for the sorcery changeover.
* Updated apps/app_stasis.c to allow initiating per-call outbound websockets.
* Added CLI commands to manage ARI websockets.
* Added the new "outbound-websocket" object to ari.conf.sample.
* Moved the ARI XML documentation out of res_ari.c into res/ari/ari_doc.xml

UserNote: Asterisk can now establish websocket sessions _to_ your ARI applications
as well as accepting websocket sessions _from_ them.
Full details: http://s.asterisk.net/ari-outbound-ws
2025-06-02 16:35:27 +00:00
George Joseph
974489e5a7 res_websocket_client: Create common utilities for websocket clients.
Since multiple Asterisk capabilities now need to create websocket clients
it makes sense to create a common set of utilities rather than making
each of those capabilities implement their own.

* A new configuration file "websocket_client.conf" is used to store common
client parameters in named configuration sections.
* APIs are provided to list and retrieve ast_websocket_client objects created
from the named configurations.
* An API is provided that accepts an ast_websocket_client object, connects
to the remote server with retries and returns an ast_websocket object. TLS is
supported as is basic authentication.
* An observer can be registered to receive notification of loaded or reloaded
client objects.
* An API is provided to compare an existing client object to one just
reloaded and return the fields that were changed. The caller can then decide
what action to take based on which fields changed.

Also as part of thie commit, several sorcery convenience macros were created
to make registering common object fields easier.

UserNote: A new module "res_websocket_client" and config file
"websocket_client.conf" have been added to support several upcoming new
capabilities that need common websocket client configuration.
2025-06-02 15:15:08 +00:00
George Joseph
443fc4d2d5 asterisk.c: Add option to restrict shell access from remote consoles.
UserNote: A new asterisk.conf option 'disable_remote_console_shell' has
been added that, when set, will prevent remote consoles from executing
shell commands using the '!' prefix.

Resolves: #GHSA-c7p6-7mvq-8jq2
2025-05-22 14:39:10 +00:00
George Joseph
f75dc57006 Alternate Channel Storage Backends
Full details: http://s.asterisk.net/dc679ec3

The previous proof-of-concept showed that the cpp_map_name_id alternate
storage backed performed better than all the others so this final PR
adds only that option.  You still need to enable it in menuselect under
the "Alternate Channel Storage Backends" category.

To select which one is used at runtime, set the "channel_storage_backend"
option in asterisk.conf to one of the values described in
asterisk.conf.sample.  The default remains "ao2_legacy".

UpgradeNote: With this release, you can now select an alternate channel
storage backend based on C++ Maps.  Using the new backend may increase
performance and reduce the chances of deadlocks on heavily loaded systems.
For more information, see http://s.asterisk.net/dc679ec3
2025-05-07 16:48:16 +00:00
Naveen Albert
76ab68b7e9 sig_analog: Add Call Waiting Deluxe support.
Adds support for Call Waiting Deluxe options to enhance
the current call waiting feature.

As part of this change, a mechanism is also added that
allows a channel driver to queue an audio file for Dial()
to play, which is necessary for the announcement function.

ASTERISK-30373 #close

Resolves: #271

UserNote: Call Waiting Deluxe can now be enabled for FXS channels
by enabling its corresponding option.
2025-05-05 14:10:12 +00:00
George Joseph
8eaad114f4 lock.h: Add include for string.h when DEBUG_THREADS is defined.
When DEBUG_THREADS is defined, lock.h uses strerror(), which is defined
in the libc string.h file, to print warning messages. If the including
source file doesn't include string.h then strerror() won't be found and
and compile errors will be thrown. Since lock.h depends on this, string.h
is now included from there if DEBUG_THREADS is defined.  This way, including
source files don't have to worry about it.
2025-05-03 16:22:20 +00:00
Albrecht Oster
5f9cd260ac res_pjproject: Fix DTLS client check failing on some platforms
Certain platforms (mainly BSD derivatives) have an additional length
field in `sockaddr_in6` and `sockaddr_in`.
`ast_sockaddr_from_pj_sockaddr()` does not take this field into account
when copying over values from the `pj_sockaddr` into the `ast_sockaddr`.
The resulting `ast_sockaddr` will have an uninitialized value for
`sin6_len`/`sin_len` while the other `ast_sockaddr` (not converted from
a `pj_sockaddr`) to check against in `ast_sockaddr_pj_sockaddr_cmp()`
has the correct length value set.

This has the effect that `ast_sockaddr_cmp()` will always indicate
an address mismatch, because it does a bitwise comparison, and all DTLS
packets are dropped even if addresses and ports match.

`ast_sockaddr_from_pj_sockaddr()` now checks whether the length fields
are available on the current platform and sets the values accordingly.

Resolves: #505
2025-04-21 14:45:56 +00:00
George Joseph
cc92adc5fb Prequisites for ARI Outbound Websockets
stasis:
* Added stasis_app_is_registered().
* Added stasis_app_control_mark_failed().
* Added stasis_app_control_is_failed().
* Fixed res_stasis_device_state so unsubscribe all works properly.
* Modified stasis_app_unregister() to unsubscribe from all event sources.
* Modified stasis_app_exec to return -1 if stasis_app_control_is_failed()
  returns true.

http:
* Added ast_http_create_basic_auth_header().

md5:
* Added define for MD5_DIGEST_LENGTH.

tcptls:
* Added flag to ast_tcptls_session_args to suppress connection log messages
  to give callers more control over logging.

http_websocket:
* Add flag to ast_websocket_client_options to suppress connection log messages
  to give callers more control over logging.
* Added username and password to ast_websocket_client_options to support
  outbound basic authentication.
* Added ast_websocket_result_to_str().
2025-04-21 13:29:27 +00:00
George Joseph
4e07d3d50f ARI: REST over Websocket
This commit adds the ability to make ARI REST requests over the same
websocket used to receive events.

For full details on how to use the new capability, visit...

https://docs.asterisk.org/Configuration/Interfaces/Asterisk-REST-Interface-ARI/ARI-REST-over-WebSocket/

Changes:

* Added utilities to http.c:
  * ast_get_http_method_from_string().
  * ast_http_parse_post_form().
* Added utilities to json.c:
  * ast_json_nvp_array_to_ast_variables().
  * ast_variables_to_json_nvp_array().
* Added definitions for new events to carry REST responses.
* Created res/ari/ari_websocket_requests.c to house the new request handlers.
* Moved non-event specific code out of res/ari/resource_events.c into
  res/ari/ari_websockets.c
* Refactored res/res_ari.c to move non-http code out of ast_ari_callback()
  (which is http specific) and into ast_ari_invoke() so it can be shared
  between both the http and websocket transports.

UpgradeNote: This commit adds the ability to make ARI REST requests over the same
websocket used to receive events.
See https://docs.asterisk.org/Configuration/Interfaces/Asterisk-REST-Interface-ARI/ARI-REST-over-WebSocket/
2025-04-02 12:16:35 +00:00
mkmer
874fde5924 audiohook.c: Add ability to adjust volume with float
Add the capability to audiohook for float type volume adjustments.  This allows for adjustments to volume smaller than 6dB.  With INT adjustments, the first step is 2 which converts to ~6dB (or 1/2 volume / double volume depending on adjustment sign). 3dB is a typical adjustment level which can now be accommodated with an adjustment value of 1.41.

This is accomplished by the following:
  Convert internal variables to type float.
  Always use ast_frame_adjust_volume_float() for adjustments.
  Cast int to float in original functions ast_audiohook_volume_set(), and ast_volume_adjust().
  Cast float to int in ast_audiohook_volume_get()
  Add functions ast_audiohook_volume_get_float, ast_audiohook_volume_set_float, and ast_audiohook_volume_adjust_float.

This update maintains 100% backward compatibility.

Resolves: #1171
2025-03-31 20:33:07 +00:00
Florent CHAUVEAU
c44e7e85ec audiosocket: added support for DTMF frames
Updated the AudioSocket protocol to allow sending DTMF frames.
AST_FRAME_DTMF frames are now forwarded to the server, in addition to
AST_FRAME_AUDIO frames. A new payload type AST_AUDIOSOCKET_KIND_DTMF
with value 0x03 was added to the protocol. The payload is a 1-byte
ascii representing the DTMF digit (0-9,*,#...).

UserNote: The AudioSocket protocol now forwards DTMF frames with
payload type 0x03. The payload is a 1-byte ascii representing the DTMF
digit (0-9,*,#...).
2025-03-28 19:18:09 +00:00