`amf0_data_read()` dispatched on the type byte into `amf0_object_read()`,
`amf0_associative_array_read()` and `amf0_array_read()`, each of which
called back into it for every contained element with nothing tracking
nesting depth. Chunk assembly admits up to `AMF_MAX_SIZE` bytes and a
nested object costs three of them per level, so one message can recurse
far deeper than `SWITCH_THREAD_STACKSIZE` holds.
Thread the depth through the dispatcher every arm funnels back into, so
one check covers any mix of them. A value past the cap is dropped, which
an object or ECMA array takes as its end and a strict array, having
declared an element count, takes as a failure. `amf0_data_read()` keeps
its signature and becomes a wrapper starting at depth 0. A cap of 32 sits
far above real traffic, where a `connect` command object nests two to
four levels.
A REFER with no call behind it is published as a `CALL_SETUP_REQ` event
whose `Request-Target` is `sofia/<profile>/<Refer-To URI>`, and
`mod_conference` hands that string to `switch_ivr_originate()` for
`rfc-4579` conferences. The URI was copied in unchanged, so a `,`, `|`
or `:_:` in it split the dial string into extra peers or legs, each of
which can start with its own `[...]` channel variables.
Answer such a REFER with `400 Bad Refer-To` before anything is
published. Both the serialized Refer-To and its user part are checked;
the user part is published separately as `Request-Target-Extension`,
which an `outcall-templ` expands. A Refer-To without these characters
is handled as before.
Also frees the subscription contact string an accepted REFER of this
kind allocated and never released.
`conference_event_adv_la()` gave every live array member's
`event_channel_cookie` permission on the conference moderator channel,
the same as the live array, chat and info channels. On mod_verto that
permission is what lets a client broadcast to `conference-mod.*` and
run conference commands through
`conference_event_mod_channel_handler()`. Grant and revoke it only for
members with `MFLAG_MOD`, which does not change during membership, so
a participant call leaving does not strip it from a moderator call on
the same WebSocket.
Adds three `test_member` cases covering the participant, moderator and
shared-cookie grants on a new `livearray` test profile.
Run the display name and number through the same
`switch_clean_string()` and `switch_var_clean_string()` pass that
`profile_dup_clean()` applies when the profile is built from the
initial request, so a `${` in either is stored as `%{` whichever
message carried it.
`switch_rtp_add_crypto_key()` allocated each MKI id buffer with
`sizeof(key_material->mki_size)`, a constant 4 bytes, then copied
`mki_size` bytes into it. That length comes from the remote `a=crypto`
attribute and was only checked against a lower bound. The same copy
read `mki_size` bytes starting at the 4-byte `mki_id` field.
Reject an MKI length outside 1..`SRTP_MAX_MKI_LEN`, allocate the id
buffer at that length, and copy no more than the width of `mki_id`,
leaving the remaining bytes zero. MKI lengths of 1 to 4 keep the bytes
they carry today.
`get_rtt_red_seq()` stored one entry per RFC 2198 redundancy header
in the fixed `pt[]` and `len[]` arrays without checking the count
against `MAX_RED_FRAMES`, so a packet with more headers wrote past
them. Reject the packet once the count reaches `MAX_RED_FRAMES`, and
reject a frame index at or above it, which a sequence number wrap
can produce.
`enum_app_function()` and `enum_api()` advanced their write cursor and
decremented the remaining space by `strlen(rp->route) + 1` rather than by
the bytes `switch_snprintf()` reported writing, so once a route no longer
fit the unsigned counter wrapped and the next iteration wrote past the end
of `rbuf` with no effective bound.
Both loops now share a `pack_routes()` helper that writes each route's
separator in front of it. Nothing points back into the buffer, so the
trailing-separator strip and its `rbuf[-1]` write are gone, along with the
write through a `char *` aimed at a string literal. A route that does not
fit whole, or that is empty, is skipped rather than clipped or ending the
loop.
`enum_app_function()` applies the same test when exporting `enum_route_N`,
so `enum_route_count` and the packed count describe the same routes: an
empty value would delete the variable rather than set it, leaving a gap in
the numbering. It also warns when the dial string ends up holding fewer
routes than were resolved, and `cnt`'s conversions are `%u` to match its
type.
`skinny_read_packet()` checked the declared length as `length + 8 >
2048` on a `uint32_t`, which wraps for lengths of `0xFFFFFFF8` and
above, and `skinny_check_data_length()` in the handlers only enforces a
minimum. Compare the length against the constant side instead, and
advance `ptr` on every read so a length field that arrives in pieces is
stored contiguously instead of being overwritten by later bytes.
- The message buffer gets one spare zero byte, so fixed-width string
fields of a full-size message terminate inside the allocation.
- The data and extended data handlers check `data_length` against the
bytes left after their header, with no addition on the wire value.
- Those two handlers and `skinny_handle_xml_alarm()` build the event
body with `%.*s` instead of an unchecked `malloc` copy.
- `skinny_handle_extended_data_message()` takes the body from the
`extended_data` member instead of `data`, so the event body no longer
starts with 20 bytes of header fields.
- `skinny_handle_updatecapabilities()` rejects an empty audio
capability list, as `skinny_handle_capabilities_response()` already
does.
On a profile with `extended-info-parsing` set, an inbound SIP INFO whose
content type is `freeswitch/api-request` puts an FSAPI command in the
request body and gets its output back in the 200 OK. The branch needs no
dialog, and no `mod_sofia` authentication or ACL setting covers an
out-of-dialog INFO. That same param also enables the in-dialog
`session-event` half, so there is no way to keep one and not the other.
The new per-profile `enable-info-api-request` param gates the api-request
branch alone and is off unless set, leaving `session-event` reachable
under `extended-info-parsing` as before. An INFO selecting the branch on a
profile without the new param is answered 403 and logged with the source
and the requested command; a permitted one is logged too, since the source
address appears in no event the API path fires. Both lines print the
body's first line, capped, rather than the whole body.
Use switch_rtp_hdr_t instead of srtp_hdr_t from srtp_priv.h, and srtp_shutdown() instead of srtp_crypto_kernel_shutdown(). Drop the rtp_hdr_t alias and add a compile-time check that switch_rtp_hdr_t is 12 bytes.
`sofia_handle_sip_i_notify()` answered an in-dialog `refer` NOTIFY and then
fell through to the generic handling, which sent a second response and,
on a terminated subscription, destroyed the dialog's handle. A channel kept
up after the REFER outcome (`sip_refer_continue_after_reply=true`) could no
longer send a REFER, re-INVITE or BYE. Return right after the `200 OK`;
`refer` NOTIFYs are no longer forwarded under `proxy-notify-events`.
Co-authored-by: Chris Rienzo <chris@signalwire.com>
The caller profile fields hold the output of `switch_sanitize_number()`,
but the unchanged check compared them against the raw candidate, so a
value the sanitizer alters never matched and the update repeated on every
message. Sanitize once before the comparison, and reuse the result for the
stores and the log.
Cleanups in the same function:
- Stop reading the name and number channel variables up front. Those reads
allocate from the session pool and are discarded whenever a SIP field
supplies the value; the fallbacks below cover the rest. The number's
`sip_to` branch moves there too, keeping the channel variable ahead of
the To user.
- Take the scratch copy the comparison needs from the heap rather than the
pool, so an update that changes nothing costs the session no memory.
- Declare `name` as `const char *` and retarget the display quote strip at
`dup`, which owns the buffer. Removes four casts that handed out a
writable pointer into the parsed message.
`switch_url_encode()` encodes with `double_encode` false, so a `%XX`
already present in `json_text` was emitted unchanged and became
indistinguishable from the escapes the body encoding added itself.
Decoding the body then consumed the values' own escapes as well, and
the document no longer parsed. Values arrive pre-encoded whenever
`encode-values` is on, and can hold percent-hex text regardless of it.
Encode with `switch_url_encode_opt(..., SWITCH_TRUE)` so `%` is encoded
too and the body decodes back to exactly the serialized document.
`mod_xml_cdr` and `mod_format_cdr` already encode their bodies this way.
- Size the escape buffer `* 3 + 1`. `switch_url_encode_opt()` reserves
the terminator from the length it is given, so `* 3` dropped the last
escaped character when every byte needed encoding. The base64 call now
takes that length directly.
- Warn at load when `encode` and `encode-values` are both on, since the
values stay encoded after the body is decoded.
- Correct both encoding config comments; the `encode` one described only
`base64`.
Adds core coverage in `tests/unit/switch_utils.c` for both
`switch_url_encode_opt()` modes, its output bounds, and a JSON body
encoded and decoded once.
* events: avoid O(n^2) header dedup when cloning EF_UNIQ_HEADERS events
switch_event_dup() copies a source event header by header via
switch_event_add_header_string(). When the source carries
EF_UNIQ_HEADERS (SWITCH_EVENT_CHANNEL_DATA / REQUEST_PARAMS / MESSAGE --
e.g. a channel's variable list), the destination inherits the flag, so
switch_event_base_add_header() runs a full switch_event_del_header()
linear scan of the partially-built list on every add to enforce
uniqueness. Cloning an N-header event is therefore O(n^2).
That scan is redundant while cloning: the source already enforced
uniqueness on insert, so copying it cannot introduce duplicates
regardless of the per-add scan. Clear EF_UNIQ_HEADERS on the
destination for the duration of the copy loop, then restore it.
This is a hot path. switch_channel_execute_on() -- invoked on ring,
answer, media, transfer, park, record and playback -- calls
switch_core_get_variables() and switch_channel_get_variables(), each of
which dup()s an EF_UNIQ_HEADERS event. On a production voicemail server
carrying ~191 channel variables per call, switch_event_del_header_val()
accounted for 47-69% of all FreeSWITCH CPU time in on-box perf profiles.
Microbenchmark (tests/unit/switch_event.c, switch_event_dup of an
N-header CHANNEL_DATA event, 4000 iterations, time per dup):
N before after
50 4.80 us 3.19 us
100 11.34 us 5.88 us
191 28.29 us 10.99 us (2.6x)
400 107.05 us 23.27 us (4.6x)
"before" scales ~O(n^2); "after" is linear. Behaviour is unchanged: the
clone has identical headers, values and order, keeps EF_UNIQ_HEADERS,
and still enforces uniqueness on subsequent adds (covered by the test).
Signed-off-by: Calvin Ellison <cellison@youmail.com>
* tests: cover switch_event_dup uniqueness and add a dup benchmark
Adds a dup_uniq_bench case to the switch_event unit test. For an
EF_UNIQ_HEADERS (CHANNEL_DATA) source event it verifies the clone
preserves header count, values and the EF_UNIQ_HEADERS flag, and that
re-setting an existing key does not produce a duplicate in the clone.
It also prints a switch_event_dup timing sweep across header counts,
used to validate the O(n^2) -> O(n) change in switch_event_dup().
Signed-off-by: Calvin Ellison <cellison@youmail.com>
* tests: add dup_faithful_copy regression for switch_event_dup
Covers the EF_UNIQ_HEADERS edge case for the O(n^2)->O(n) dup change: a well-formed EF_UNIQ source stays unique through dup, and a malformed source already holding duplicate names (only possible if headers were added before the flag was set) is copied faithfully rather than silently collapsed to the last value.
Signed-off-by: Calvin Ellison <cellison@youmail.com>
* tests: gate dup_uniq_bench behind #ifdef BENCHMARK
The dup_uniq_bench timing sweep is a benchmark rather than a pass/fail correctness test. Guard the whole test with #ifdef BENCHMARK (matching the existing benchmark in this file) so it stays out of normal test runs; dup_faithful_copy continues to cover correctness of the switch_event_dup change.
Signed-off-by: Calvin Ellison <cellison@youmail.com>
* switch_event: clarify EF_UNIQ_HEADERS dup comment, brace one-line test loops
Address review feedback on the switch_event_dup change:
- src/switch_event.c: the fast-path comment claimed todup's headers are "already unique" unconditionally. That only holds when EF_UNIQ_HEADERS is set (names are deduped on insert); reword to scope the claim to that case and to the verbatim-copy intent.
- tests/unit/switch_event.c: expand one-line loops to braced form per the SignalWire coding guidelines.
Signed-off-by: Calvin Ellison <cellison@youmail.com>
---------
Signed-off-by: Calvin Ellison <cellison@youmail.com>
Co-authored-by: Calvin Ellison <cellison@youmail.com>
A client message can select which chat proto handles it, and the `api` proto
runs the address as a FreeSWITCH API command. That route does not pass through
`verto.fsapi`, so the per-user fsapi permission does not apply to it. The new
per-profile `enable-chat-api-proto` param controls the route and is off unless
set; a message selecting the proto without it is refused and logged.
The proto compare is case-insensitive, matching the chat interface registry,
which is created with `switch_core_hash_init_nocase()`.
Only the `api` proto is gated. A message carrying no proto selector, or one
naming any other chat proto, routes exactly as before.
The param ships commented out in both vanilla verto profiles.
The chat layer lets an inbound SIP MESSAGE select which chat proto handles it,
and the `api` proto runs the address as a FreeSWITCH API command. The new
per-profile `enable-chat-api-proto` param controls that route and is off unless
set. A MESSAGE selecting the proto on a profile without it is answered 403 and
logged with the source and the requested command.
The proto compare is case-insensitive, matching the chat interface registry,
which is created with `switch_core_hash_init_nocase()`.
The param ships commented out in the four vanilla profiles and the mod_sofia
sofia.conf.xml sample.
`sofia_presence_handle_sip_i_message()` splits the chat proto selector off a
truncating copy of the To user. Split only a user that fits the buffer; an
over-long one is handled as a plain address.
`timerfd_gettime()` returns the time remaining until the next periodic tick,
regardless of how many previous ticks have already fired and remain unread.
Replace with `poll()` which correctly checks for pending unread expirations.
`read_rtp_packet()` runs `switch_core_timer_check()` on every empty
read, and that logs an error when `rtp_session->timer` is zeroed, the
normal state for T.38, proxy media, and a disabled timer. Test
`timer.timer_interface` first so those sessions stay quiet; the branch
itself is not reachable without a timer, so packet handling is unchanged.
`switch_silk_decode()` ran its `do`/`while` decode loop while the SDK
kept reporting more internal frames, advancing the output pointer each
pass with no cap. The destination is a fixed-size PCM buffer, so a
stream reporting more internal frames than a conformant packet can
carry let the accumulated write run past its end.
Stop after `MAX_INPUT_FRAMES` internal frames, the most a conformant
SILK packet can hold, so the accumulated PCM stays within the
destination regardless of the bitstream.
Declare the per-pass sample count inside the loop so it resets to zero
each iteration, and advance the output pointer and length only when it
is positive. A pass that writes no samples, including a tolerated FEC
payload error that leaves the count untouched, then contributes nothing
instead of advancing on a stale count from an earlier pass or on a
negative value.
`switch_stun_packet_attribute_get_xor_mapped_address()` read and
XOR-rewrote a 16-byte IPv6 address whenever the `family` byte was 2,
without checking the attribute value was that long. Reject `family == 2`
values shorter than `sizeof(switch_stun_ipv6_t)` and clear the output
address and port. Adds a regression test.
`ws_read_frame()` had two defects in the framing path:
- After header parsing, the remaining payload count
`need = plen - (datalen - header)` could go negative when the
initial read buffered more bytes than the frame's declared
length, even with an in-range `plen`. A negative `need` passed
the signed size guard and reached `ws_raw_read()` as a `size_t`
near its maximum, driving a `memcpy` past `wsh->buffer`. Reject
`need < 0` with a protocol-error close before the read loop.
- The loop filling the frame header called `ws_raw_read()` without
checking its result, so a connection that stopped delivering
header bytes left the loop with no terminating condition,
spinning or hanging the handler thread. Close on a non-advancing
read, matching the payload read loop.
`rtmp_rtmp2rtpH264` read the two leading bytes that select the parse
branch (`data[0]` and `data[1]`) before any length check, so a video
body shorter than 2 bytes read past the buffer. Reject `len < 2` at
entry, before either classifier byte is dereferenced.
In the NAL-unit branch, move the `pdata = data + 5` assignment below
its `len < 5` check so the pointer is never formed past the end of a
short buffer.
Read the 2-byte big-endian SPS and PPS length prefixes byte-wise
(`(pdata[0] << 8) | pdata[1]`) instead of `ntohs(*(uint16_t *)pdata)`.
`pdata` walks a byte buffer at wire-controlled offsets, so the cast was
an unaligned 16-bit load and a strict-aliasing violation; the byte-wise
read is alignment- and endianness-independent and matches the idiom
already used in the NAL-unit branch.
In `rtmp_read_video_frame`, a buffered record is `len + 6` bytes (2-byte
length prefix, 4-byte timestamp, `len`-byte body), but the guard only
required `inuse >= len` before consuming the whole record. Require
`inuse >= len + 6` so the invariant holds locally instead of relying on
the writer emitting each record atomically.