From 1c1999cd2112d64a67a73fc726caa7a493bcfd4e Mon Sep 17 00:00:00 2001 From: HSMM Date: Mon, 9 Nov 2026 13:14:25 +0300 Subject: [PATCH 01/12] Engine: IPv6 dual stack with a per-account IP protocol (#11) --- Sources/CPJSUA/include/CPJSUA.h | 8 +- Sources/CPJSUA/shim.c | 30 +- .../MacroSIPCore/Engine/AccountMapping.swift | 108 +- .../MacroSIPCore/Engine/Engine+Accounts.swift | 96 +- .../MacroSIPCore/Engine/Engine+Network.swift | 32 +- .../Engine/Engine+NetworkOptions.swift | 10 +- Sources/MacroSIPCore/Engine/Engine.swift | 100 +- Sources/MacroSIPCore/Engine/EngineTypes.swift | 7 +- Sources/MacroSIPCore/Engine/IPFamily.swift | 133 +++ .../Engine/NetworkPathMonitor.swift | 80 +- .../MacroSIPCore/Model/AccountConfig.swift | 28 +- Sources/macrosip-cli/main.swift | 3 +- Tests/MacroSIPCoreTests/Engine262Tests.swift | 57 +- Tests/MacroSIPCoreTests/EngineIPv6Tests.swift | 981 ++++++++++++++++++ docs/ENGINE.md | 41 +- docs/GLOSSARY.md | 3 +- docs/adr/0014-ipv6-dual-stack.md | 57 + docs/adr/README.md | 17 + 18 files changed, 1652 insertions(+), 139 deletions(-) create mode 100644 Sources/MacroSIPCore/Engine/IPFamily.swift create mode 100644 Tests/MacroSIPCoreTests/EngineIPv6Tests.swift create mode 100644 docs/adr/0014-ipv6-dual-stack.md diff --git a/Sources/CPJSUA/include/CPJSUA.h b/Sources/CPJSUA/include/CPJSUA.h index 15cb4ee..3ffcaea 100644 --- a/Sources/CPJSUA/include/CPJSUA.h +++ b/Sources/CPJSUA/include/CPJSUA.h @@ -75,10 +75,12 @@ pj_status_t cpjsua_transport_create2(pjsip_transport_type_e type, pjsua_transport_id *out_id); /** TLS listener (also used for outgoing TLS connections of accounts bound to it). + * `type` is PJSIP_TRANSPORT_TLS or PJSIP_TRANSPORT_TLS6. * verify_server != 0: the server certificate must chain to a CA in `ca_file` (PEM) and * match the destination host name (PJSIP sets SNI and checks CN/SAN per connection). * verify_client is always off; no client certificate is presented. */ -pj_status_t cpjsua_tls_transport_create(unsigned port, +pj_status_t cpjsua_tls_transport_create(pjsip_transport_type_e type, + unsigned port, const char *address, int verify_server, const char *ca_file, @@ -322,6 +324,10 @@ int cpjsua_has_resolver(void); /** Local RTP port of the call's first audio stream, 0 if none (tests, diagnostics). */ int cpjsua_call_local_rtp_port(pjsua_call_id call_id); +/** Local RTP address of the call's first audio stream as published in SDP ("::1", + * "192.0.2.10", no brackets, no port) into `buf`; returns its length, 0 if none. */ +int cpjsua_call_local_rtp_addr(pjsua_call_id call_id, char *buf, unsigned len); + /* ----------------------------------------------------- packet source --- */ /** Where a received message came from (rdata->pkt_info, rdata->tp_info). */ diff --git a/Sources/CPJSUA/shim.c b/Sources/CPJSUA/shim.c index 2ea082d..3d8856b 100644 --- a/Sources/CPJSUA/shim.c +++ b/Sources/CPJSUA/shim.c @@ -126,7 +126,8 @@ pj_status_t cpjsua_transport_create2(pjsip_transport_type_e type, return status; } -pj_status_t cpjsua_tls_transport_create(unsigned port, +pj_status_t cpjsua_tls_transport_create(pjsip_transport_type_e type, + unsigned port, const char *address, int verify_server, const char *ca_file, @@ -136,6 +137,8 @@ pj_status_t cpjsua_tls_transport_create(unsigned port, pjsua_transport_id tid = PJSUA_INVALID_ID; pj_status_t status; + if (type != PJSIP_TRANSPORT_TLS && type != PJSIP_TRANSPORT_TLS6) + return PJ_EINVAL; pjsua_transport_config_default(&cfg); cfg.port = port; if (address && *address) { @@ -147,7 +150,7 @@ pj_status_t cpjsua_tls_transport_create(unsigned port, cfg.tls_setting.require_client_cert = PJ_FALSE; if (ca_file && *ca_file) cfg.tls_setting.ca_list_file = cpjsua_str(ca_file); - status = pjsua_transport_create(PJSIP_TRANSPORT_TLS, &cfg, &tid); + status = pjsua_transport_create(type, &cfg, &tid); if (out_id) *out_id = tid; return status; @@ -1137,6 +1140,29 @@ int cpjsua_call_local_rtp_port(pjsua_call_id call_id) return pj_sockaddr_get_port(&tpinfo.sock_info.rtp_addr_name); } +int cpjsua_call_local_rtp_addr(pjsua_call_id call_id, char *buf, unsigned len) +{ + pjsua_call_info ci; + pjmedia_transport_info tpinfo; + int aud; + + if (!buf || len == 0) + return 0; + buf[0] = '\0'; + if (pjsua_call_get_info(call_id, &ci) != PJ_SUCCESS) + return 0; + aud = first_audio_index(&ci); + if (aud < 0) + return 0; + pjmedia_transport_info_init(&tpinfo); + if (pjsua_call_get_med_transport_info(call_id, (unsigned)aud, &tpinfo) != PJ_SUCCESS) + return 0; + if (!pj_sockaddr_has_addr(&tpinfo.sock_info.rtp_addr_name)) + return 0; + pj_sockaddr_print(&tpinfo.sock_info.rtp_addr_name, buf, len, 0); + return (int)pj_ansi_strlen(buf); +} + /* ====================================================== packet source === */ pj_status_t cpjsua_rdata_source(const pjsip_rx_data *rdata, cpjsua_pkt_source *out) diff --git a/Sources/MacroSIPCore/Engine/AccountMapping.swift b/Sources/MacroSIPCore/Engine/AccountMapping.swift index 97e92d1..fbb7829 100644 --- a/Sources/MacroSIPCore/Engine/AccountMapping.swift +++ b/Sources/MacroSIPCore/Engine/AccountMapping.swift @@ -15,28 +15,36 @@ struct PJAccountSettings: Equatable, Sendable { var proxies: [String] var srtp: SRTPMode var srtpSecureSignaling: Int - /// The account's transport; PJSUA_INVALID_ID for a UDP account of a private server while - /// STUN is on, so its Contact and Via do not carry the STUN address (`settings`). + /// The account's transport, of the account's family (`IPFamilyPolicy`); PJSUA_INVALID_ID for a + /// UDP account of a private IPv4 server while STUN is on, so its Contact and Via do not carry the + /// STUN address (`settings`). var transportID: Int32 var allowContactRewrite: Bool var allowViaRewrite: Bool var keepAliveSeconds: Int var iceEnabled: Bool /// STUN for the account's signalling and media (`sip_stun_use`, `media_stun_use`): false - /// for a server in a private network (`PrivateServer`); true keeps pjsua's defaults. + /// for a server in a private network (`PrivateServer`) and for every IPv6 account (STUN and + /// TURN over IPv6 are out of scope); true keeps pjsua's defaults. var sipSTUN: Bool = true var mediaSTUN: Bool = true /// `allow_sdp_nat_rewrite`: without STUN pjsua offers the default route's address in SDP, /// which over a split-tunnel VPN is not the one the server sees; with it the SDP takes the /// address the registrar reported in Via (received), as Contact does. On for private servers. var sdpNATRewrite: Bool = false + /// `ipv6_media_use = PJSUA_IPV6_ENABLED_USE_IPV6_ONLY` (IPv6 accounts): the offer is IPv6 even + /// when only a link-local or loopback IPv6 address exists, which pjsua's PREFER_IPV6 would skip + /// for IPv4. false keeps pjsua's default (PREFER_IPV4; an `IN IP6` offer is still answered with + /// IPv6). Either way an offer is answered in its own family. + var mediaIPv6Only: Bool = false /// RTP base port and range (NetworkSettings.rtpPortStart/rtpPortCount); the first port is /// picked at random inside the range so two PJSIP phones on one host (or a restarted /// engine) do not fight over 4000, 4002, ... var rtpPort: Int var rtpPortRange: Int var randomizeRTPPort: Bool - /// Bind RTP to and advertise this address (nil = all interfaces, default route address). + /// Bind RTP to and advertise this address (nil = all interfaces, default route address). Only + /// an address of the account's family. var bindAddress: String? /// PUBLISH our presence (PIDF/RPID) to the registrar's domain (AccountConfig.publishPresence). var publishEnabled: Bool @@ -53,30 +61,47 @@ struct PJAccountSettings: Equatable, Sendable { var ipChangeReinviteFlags: UInt32 = 0 } -/// SIP transports created at engine start. TLS exists twice: a listener that verifies the -/// server certificate (default) and one that does not (accounts with -/// `verifyTLSCertificate == false`). PJSIP never reuses a connection across listeners. +/// SIP transports created at engine start, per family (docs/ENGINE.md "IPv6"). TLS exists twice: +/// a listener that verifies the server certificate (default) and one that does not (accounts with +/// `verifyTLSCertificate == false`). PJSIP never reuses a connection across listeners. Accounts are +/// bound to the transport of their family; nil = that transport could not be created (or the bind +/// address is of the other family). struct TransportIDs: Equatable, Sendable { var udp: Int32? var tcp: Int32? var tls: Int32? var tlsNoVerify: Int32? + var udp6: Int32? + var tcp6: Int32? + var tls6: Int32? + var tls6NoVerify: Int32? - func id(for account: AccountConfig) -> Int32? { - switch account.transport { - case .udp: return udp - case .tcp: return tcp - case .tls: return account.verifyTLSCertificate ? tls : tlsNoVerify + func id(for account: AccountConfig, family: IPFamily = .ipv4) -> Int32? { + switch (account.transport, family) { + case (.udp, .ipv4): return udp + case (.tcp, .ipv4): return tcp + case (.tls, .ipv4): return account.verifyTLSCertificate ? tls : tlsNoVerify + case (.udp, .ipv6): return udp6 + case (.tcp, .ipv6): return tcp6 + case (.tls, .ipv6): return account.verifyTLSCertificate ? tls6 : tls6NoVerify } } - func id(for kind: TransportKind) -> Int32? { - switch kind { - case .udp: return udp - case .tcp: return tcp - case .tls: return tls + func id(for kind: TransportKind, family: IPFamily = .ipv4) -> Int32? { + switch (kind, family) { + case (.udp, .ipv4): return udp + case (.tcp, .ipv4): return tcp + case (.tls, .ipv4): return tls + case (.udp, .ipv6): return udp6 + case (.tcp, .ipv6): return tcp6 + case (.tls, .ipv6): return tls6 } } + + /// Families that have the account's transport. + func families(for account: AccountConfig) -> Set { + Set(IPFamily.allCases.filter { id(for: account, family: $0) != nil }) + } } /// STUN learns the address a NAT gives us towards the internet, which is what a server on the @@ -84,7 +109,8 @@ struct TransportIDs: Equatable, Sendable { /// reached inside the same network or through a VPN, where that public address is wrong: PJSIP /// learns the real one only from the first answer and registers again, and a server that does /// not rewrite Contact would send incoming calls to the public address. Host names are not -/// resolved here (that would block, and the answer may change with the network); they keep STUN. +/// resolved here (the answer may change with the network); they keep STUN. This is about IPv4 +/// accounts: an IPv6 account (`IPFamilyPolicy`) uses no STUN at all. enum PrivateServer { /// Every signalling hop of the account is a private or local IP literal: the registrar and /// the outbound proxy when one is set, otherwise the domain (INVITE, SUBSCRIBE and PUBLISH @@ -93,17 +119,6 @@ enum PrivateServer { hops(account).allSatisfy(isPrivate(uri:)) } - /// Every hop is a dotted IPv4 literal. pjsua asks for an IPv6 transport for any host with a - /// colon (`pjsua_acc_get_uac_addr`; ::ffff:a.b.c.d too) and the engine creates none, so an - /// account with such a hop must stay bound to its transport (`AccountMapping.settings`). - static func allHopsIPv4(_ account: AccountConfig) -> Bool { - hops(account).allSatisfy { uri in - var v4 = in_addr() - guard let host = SignallingSource.proxy(uri, transport: .udp)?.address else { return false } - return inet_pton(AF_INET, host, &v4) == 1 - } - } - private static func hops(_ account: AccountConfig) -> [String] { let proxy = account.outboundProxy?.trimmingCharacters(in: .whitespaces) ?? "" return [account.registrarURI, proxy.isEmpty ? account.domain : proxy] @@ -145,18 +160,24 @@ enum PrivateServer { } enum AccountMapping { + /// `family` is the account's IP family as `IPFamilyPolicy` decided it: the account is bound to + /// that family's transport (pjsua_init_tpselector: a TRANSPORT selector for UDP, a LISTENER one + /// for TCP/TLS, so the family is fixed by the binding; `ipv6_sip_use` only matters unbound). static func settings( for account: AccountConfig, password: String, network: NetworkSettings, transports: TransportIDs, - bindAddress: String? = nil + bindAddress: String? = nil, + family: IPFamily = .ipv4 ) throws -> PJAccountSettings { - guard let transportID = transports.id(for: account) else { - throw EngineError.transportUnavailable(account.transport) + guard let transportID = transports.id(for: account, family: family) else { + throw EngineError.transportUnavailable(account.transport, ipv6: family == .ipv6) } let proxy = account.outboundProxy?.trimmingCharacters(in: .whitespaces) ?? "" - let stun = !PrivateServer.allHopsPrivate(account) + // IPv6: no STUN (pjsua maps IPv4 only; an IPv6 address needs no mapping without NAT66), + // so the SDP takes the address the registrar reported, as for private servers. + let stun = family == .ipv4 && !PrivateServer.allHopsPrivate(account) // sip_stun_use alone does not change Contact and Via: for an account bound to its UDP // transport pjsua takes them from the transport's published address, which STUN made // the public one (pjsip_tpmgr_find_local_addr2 ignores local_if under a transport @@ -164,11 +185,14 @@ enum AccountMapping { // (get_net_interface) with the transport's port; requests still leave through the one // UDP transport, and large ones stay on UDP (disable_tcp_switch). TCP and TLS listeners // are never published with a STUN address, and without a STUN server there is nothing - // to undo: those accounts stay bound. So do IPv6 hops: unbound, pjsua would want an - // IPv6 transport for them and refuse the account. + // to undo: those accounts stay bound. IPv6 accounts stay bound to their IPv6 transport: + // only the IPv4 UDP transport is published with a STUN address. let stunServer = network.stunServer?.trimmingCharacters(in: .whitespaces) ?? "" - let unbound = !stun && !stunServer.isEmpty && account.transport == .udp - && PrivateServer.allHopsIPv4(account) + let unbound = !stun && !stunServer.isEmpty && account.transport == .udp && family == .ipv4 + // RTP binds to the engine's bind address only when it is of the account's family (pjsua + // would fail to bind an IPv6 address to an IPv4 socket and the other way round). A bind + // address that is not a literal counts as IPv4, as for the transports. + let rtpBind = bindAddress.flatMap { (IPFamilyPolicy.literalFamily($0) ?? .ipv4) == family ? $0 : nil } return PJAccountSettings( idURI: account.uri, regURI: account.registrarURI, @@ -186,14 +210,18 @@ enum AccountMapping { allowContactRewrite: true, allowViaRewrite: true, keepAliveSeconds: max(0, network.keepAliveSeconds), - iceEnabled: network.useICE, + // Not over IPv6: pjsua binds the IPv6 ICE component to "0", which macOS getaddrinfo turns + // into ::ffff:0.0.0.0, so that socket fails (EADDRNOTAVAIL) and the offer would carry IPv4 + // candidates only, then fail on an IPv6 answer (PJ_EAFNOTSUP). Plain RTP works over IPv6. + iceEnabled: network.useICE && family == .ipv4, sipSTUN: stun, mediaSTUN: stun, sdpNATRewrite: !stun, + mediaIPv6Only: family == .ipv6, rtpPort: network.effectiveRTPRange.start, rtpPortRange: rtpPortRange(count: network.effectiveRTPRange.count), randomizeRTPPort: true, - bindAddress: bindAddress, + bindAddress: rtpBind, publishEnabled: account.publishPresence, publishQueueRequest: true, mwiEnabled: account.mwi, @@ -287,6 +315,7 @@ enum AccountMapping { if !s.sipSTUN { cfg.pointee.sip_stun_use = PJSUA_STUN_USE_DISABLED } if !s.mediaSTUN { cfg.pointee.media_stun_use = PJSUA_STUN_USE_DISABLED } cfg.pointee.allow_sdp_nat_rewrite = s.sdpNATRewrite ? 1 : 0 + if s.mediaIPv6Only { cfg.pointee.ipv6_media_use = PJSUA_IPV6_ENABLED_USE_IPV6_ONLY } cfg.pointee.rtp_cfg.port = UInt32(s.rtpPort) cfg.pointee.rtp_cfg.port_range = UInt32(s.rtpPortRange) @@ -335,6 +364,7 @@ enum AccountMapping { sipSTUN: c.sip_stun_use != PJSUA_STUN_USE_DISABLED, mediaSTUN: c.media_stun_use != PJSUA_STUN_USE_DISABLED, sdpNATRewrite: c.allow_sdp_nat_rewrite != 0, + mediaIPv6Only: c.ipv6_media_use == PJSUA_IPV6_ENABLED_USE_IPV6_ONLY, rtpPort: Int(c.rtp_cfg.port), rtpPortRange: Int(c.rtp_cfg.port_range), randomizeRTPPort: c.rtp_cfg.randomize_port != 0, diff --git a/Sources/MacroSIPCore/Engine/Engine+Accounts.swift b/Sources/MacroSIPCore/Engine/Engine+Accounts.swift index a365e01..f8405b0 100644 --- a/Sources/MacroSIPCore/Engine/Engine+Accounts.swift +++ b/Sources/MacroSIPCore/Engine/Engine+Accounts.swift @@ -9,15 +9,17 @@ extension Engine { guard accounts[cfg.id] == nil else { throw EngineError.invalidArgument("account \(cfg.id.raw) is already added") } - let settings = try accountSettings(cfg, password: password) + let family = try decideFamily(cfg) + let settings = try accountSettings(cfg, password: password, family: family) var index = PJ.invalidID try AccountMapping.withPJConfig(settings) { p in // Never register inside pjsua_acc_add: the callbacks need the index mapping first. p.pointee.register_on_acc_add = 0 try PJ.check(pjsua_acc_add(p, cfg.isDefaultOutgoing ? 1 : 0, &index), "pjsua_acc_add") } - accounts[cfg.id] = AccountEntry(index: index, config: cfg, password: password, + accounts[cfg.id] = AccountEntry(index: index, config: cfg, password: password, family: family, wantsRegistration: cfg.registers) + logFamily(cfg, family) bridge.setAccount(index, cfg.id, registrationInterval: cfg.registrationInterval, proxy: SignallingSource.proxy(cfg.outboundProxy, transport: cfg.transport)) bridge.setWantsRegistration(index, cfg.registers) @@ -44,7 +46,8 @@ extension Engine { try requireStarted() guard var entry = accounts[cfg.id] else { throw EngineError.unknownAccount(cfg.id) } let pw = password ?? entry.password - let settings = try accountSettings(cfg, password: pw) + let family = try decideFamily(cfg) + let settings = try accountSettings(cfg, password: pw, family: family) // New settings start a new series of attempts. cancelRegistrationRetry(cfg.id) bridge.resetRetryAttempts(cfg.id) @@ -68,8 +71,11 @@ extension Engine { } let serverChanged = entry.config.registrarURI != cfg.registrarURI || entry.config.outboundProxy != cfg.outboundProxy || entry.config.transport != cfg.transport + || entry.family != family + if entry.family != family || entry.config.ipProtocol != cfg.ipProtocol { logFamily(cfg, family) } entry.config = cfg entry.password = pw + entry.family = family accounts[cfg.id] = entry bridge.setAccount(entry.index, cfg.id, registrationInterval: cfg.registrationInterval, proxy: SignallingSource.proxy(cfg.outboundProxy, transport: cfg.transport)) @@ -124,9 +130,9 @@ extension Engine { // MARK: internals - func accountSettings(_ cfg: AccountConfig, password: String) throws -> PJAccountSettings { + func accountSettings(_ cfg: AccountConfig, password: String, family: IPFamily) throws -> PJAccountSettings { let settings = try AccountMapping.settings(for: cfg, password: password, network: network, - transports: transports, bindAddress: bindAddress) + transports: transports, bindAddress: bindAddress, family: family) // pjsua_acc_add does not validate reg_uri; a bad one would only fail later. try verifyURI(settings.idURI, "account URI") try verifyURI(settings.regURI, "registrar") @@ -134,6 +140,86 @@ extension Engine { return settings } + /// DNS SRV is in effect: pjsua has a resolver and looks up SRV records of hosts without a port. + var srvInEffect: Bool { !dnsServers.isEmpty } + + /// The account's IP family (`IPFamilyPolicy`). Throws `.invalidArgument` when IPv4 only or IPv6 only + /// contradicts the server's IP literal: such an account could never register. + func decideFamily(_ cfg: AccountConfig) throws -> IPFamily { + if let literal = IPFamilyPolicy.conflict(in: cfg) { + let host = IPFamilyPolicy.firstHop(of: cfg).host + throw EngineError.invalidArgument("server \(host) is an \(literal) address but the account is set to " + + "\(literal == .ipv6 ? "IPv4" : "IPv6") only") + } + return IPFamilyPolicy.decide(cfg, available: transports.families(for: cfg), srv: srvInEffect, + resolve: resolveFamilies) + } + + private func logFamily(_ cfg: AccountConfig, _ family: IPFamily) { + let how = cfg.ipProtocol == .auto ? "auto" : "\(cfg.ipProtocol.rawValue) only" + emit(.log(level: 4, "engine: account \(cfg.uri): \(family) (\(how), server \(IPFamilyPolicy.firstHop(of: cfg).host))")) + if family == .ipv6 && network.useICE { + emit(.log(level: 3, "engine: account \(cfg.uri): ICE is not used over IPv6; calls use plain RTP")) + } + } + + /// Decides the family of an Auto account with a host name again (network change, REGISTER retry). + /// When it changed, the account moves to the other family's transport (pjsua_acc_modify without a + /// REGISTER; the caller registers) and its registrar must accept a REGISTER again before its + /// INVITEs are trusted. Returns true when the family changed. + @discardableResult + func refreshAccountFamily(_ id: AccountID, reason: String) -> Bool { + guard isStarted, PJ.registerThread(), var entry = accounts[id], + IPFamilyPolicy.followsResolver(entry.config, srv: srvInEffect), + let family = try? decideFamily(entry.config), family != entry.family else { return false } + do { + let settings = try accountSettings(entry.config, password: entry.password, family: family) + try AccountMapping.withPJConfig(settings) { p in + p.pointee.disable_reg_on_modify = 1 + try PJ.check(pjsua_acc_modify(entry.index, p), "pjsua_acc_modify") + } + } catch { + PJ.warn(error, "account \(entry.config.uri): move to \(family)") + return false + } + emit(.log(level: 3, "engine: account \(entry.config.uri): server now reached over \(family) " + + "(was \(entry.family), \(reason))")) + entry.family = family + accounts[id] = entry + bridge.setRegistrarSource(entry.index, nil) + return true + } + + /// `refreshAccountFamily` for every account. + func refreshAccountFamilies(reason: String) { + for id in Array(accounts.keys) { refreshAccountFamily(id, reason: reason) } + } + + // MARK: test hooks + + func transportIDsForTests() -> TransportIDs { transports } + + func accountFamilyForTests(_ id: AccountID) -> IPFamily? { accounts[id]?.family } + + func setFamilyResolverForTests(_ resolve: @escaping @Sendable (String) -> [IPFamily]) { + resolveFamilies = resolve + } + + /// The account's pjsua_acc_config as pjsua holds it now (pjsua_acc_get_config). + func liveAccountSettingsForTests(_ id: AccountID) -> PJAccountSettings? { + guard isStarted, PJ.registerThread(), let entry = accounts[id], + let pool = pjsua_pool_create("acc-read", 1024, 1024) else { return nil } + defer { pj_pool_release(pool) } + let cfg = UnsafeMutablePointer.allocate(capacity: 1) + cfg.initialize(to: pjsua_acc_config()) + defer { + cfg.deinitialize(count: 1) + cfg.deallocate() + } + guard pjsua_acc_get_config(entry.index, pool, cfg) == PJ.success else { return nil } + return AccountMapping.readBack(cfg) + } + private func verifyURI(_ uri: String, _ what: String) throws { guard pjsua_verify_sip_url(uri) == PJ.success else { throw EngineError.invalidArgument("\(what) \"\(uri)\" is not a valid SIP URI") diff --git a/Sources/MacroSIPCore/Engine/Engine+Network.swift b/Sources/MacroSIPCore/Engine/Engine+Network.swift index 38cbf6b..db82395 100644 --- a/Sources/MacroSIPCore/Engine/Engine+Network.swift +++ b/Sources/MacroSIPCore/Engine/Engine+Network.swift @@ -254,25 +254,32 @@ extension Engine { guard new == .online else { return } let previous = handledPath var path = path - if path.address.isEmpty { - // Satisfied but no default route (the 192.0.2.1 lookup failed: a host without a - // default route, or a moment during a change): keep the address we had and treat - // it as unchanged rather than as a new primary route. - let kept = previous?.address ?? "" - emit(.log(level: 3, "engine: network path without a default route; keeping address \(kept.isEmpty ? "unknown" : kept)")) - path.address = kept - } + if path.address.isEmpty && path.address6.isEmpty { + // Satisfied but no default route (the 192.0.2.1 and 2001:db8::1 lookups failed: a host + // without a default route, or a moment during a change): keep the addresses we had and + // treat them as unchanged rather than as a new primary route. + let kept = [previous?.address ?? "", previous?.address6 ?? ""].filter { !$0.isEmpty } + emit(.log(level: 3, "engine: network path without a default route; keeping address " + + (kept.isEmpty ? "unknown" : kept.joined(separator: " ")))) + } + // Per family, the same: an IPv6-only network has no IPv4 route and most networks no IPv6 one. + if path.address.isEmpty { path.address = previous?.address ?? "" } + if path.address6.isEmpty { path.address6 = previous?.address6 ?? "" } handledPath = path guard !sleeping, !first else { return } if previous.map({ path.routeDiffers(from: $0) }) ?? true || old == .offline || wake { refreshSystemNameservers() } - let primary = previous.map { path.primaryDiffers(from: $0) } ?? true + // A new IPv6 address (a new temporary address, about once a day) matters to accounts bound to + // IPv6, and IPv6 appearing may change what an Auto host name resolves to first; otherwise it + // is no reason for a round (which would end a ringing outgoing call: pjsua's 410). + let ipv6Matters = accounts.values.contains { $0.family == .ipv6 } || (previous?.address6.isEmpty ?? true) + let primary = previous.map { path.primaryDiffers(from: $0, ipv6: ipv6Matters) } ?? true if wake { requestIPChange(IPChangeRequest(reason: "wake", registerFailed: true, primary: primary)) } else if old == .offline { requestIPChange(IPChangeRequest(reason: "network back", registerFailed: false, primary: primary)) - } else if let previous, path.routeDiffers(from: previous) { + } else if let previous, path.routeDiffers(from: previous, ipv6: ipv6Matters) { emit(.log(level: 3, "engine: network route changed: \(previous.summary) -> \(path.summary)")) requestIPChange(IPChangeRequest(reason: "route changed", registerFailed: false, primary: primary)) } @@ -362,6 +369,10 @@ extension Engine { bridge.updateCall(snap, mode: .updateOnly, mutate: { $0.reinviteWanted = round }) } + // A host name may now resolve to the other family first (an IPv6-only network, IPv6 lost): + // move such accounts before pjsua re-registers them (an account whose registration was + // destroyed by the move is registered afresh: cpjsua_acc_prepare_ip_change below). + refreshAccountFamilies(reason: "network change") var pending: Set = [] for (id, entry) in accounts { let state = bridge.registration(of: id) @@ -732,6 +743,7 @@ extension Engine { } emit(.log(level: RegistrationBackoff.logLevel(attempt: attempt + 1), "engine: account \(entry.config.uri): REGISTER retry \(attempt + 1)")) + refreshAccountFamily(id, reason: "REGISTER retry") do { try applyRegistration(id, true, retrying: true) } catch { diff --git a/Sources/MacroSIPCore/Engine/Engine+NetworkOptions.swift b/Sources/MacroSIPCore/Engine/Engine+NetworkOptions.swift index 937a4fe..a099a69 100644 --- a/Sources/MacroSIPCore/Engine/Engine+NetworkOptions.swift +++ b/Sources/MacroSIPCore/Engine/Engine+NetworkOptions.swift @@ -30,7 +30,7 @@ extension Engine { if live.keepAliveSeconds != previous.keepAliveSeconds || live.useICE != previous.useICE { for (id, entry) in accounts { do { - let s = try accountSettings(entry.config, password: entry.password) + let s = try accountSettings(entry.config, password: entry.password, family: entry.family) try AccountMapping.withPJConfig(s) { p in p.pointee.disable_reg_on_modify = 1 try PJ.check(pjsua_acc_modify(entry.index, p), "pjsua_acc_modify") @@ -80,6 +80,14 @@ extension Engine { return Int(cpjsua_call_local_rtp_port(slot)) } + /// Local RTP address of the call as offered in SDP ("::1", "192.0.2.10"), "" if unknown (diagnostics). + public func localRTPAddress(of id: CallID) -> String { + guard let slot = try? liveSlot(id) else { return "" } + var buf = [CChar](repeating: 0, count: 64) + guard cpjsua_call_local_rtp_addr(slot, &buf, UInt32(buf.count)) > 0 else { return "" } + return String(decoding: buf.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self) + } + /// Whether SIP host names go through the DNS resolver (SRV), and its servers (tests). func resolverState() -> (enabled: Bool, servers: [DNSServer]) { guard isStarted, PJ.registerThread() else { return (false, []) } diff --git a/Sources/MacroSIPCore/Engine/Engine.swift b/Sources/MacroSIPCore/Engine/Engine.swift index ac233d8..7967f6b 100644 --- a/Sources/MacroSIPCore/Engine/Engine.swift +++ b/Sources/MacroSIPCore/Engine/Engine.swift @@ -51,6 +51,9 @@ public actor Engine { var index: pjsua_acc_id var config: AccountConfig var password: String + /// The IP family the account is bound to (`IPFamilyPolicy`); decided again on network + /// changes and REGISTER retries when it follows the resolver. + var family: IPFamily = .ipv4 /// Last status given to `publishPresence` (re-applied when the account changes). var presence: PresenceStatus = .available /// Registration requested (cfg.registers or setRegistered): retried after temporary @@ -70,6 +73,9 @@ public actor Engine { var dnsServers: [DNSServer] = [] var transports = TransportIDs() var accounts: [AccountID: AccountEntry] = [:] + /// The families of a host name in the system resolver's order (`IPFamilyResolver.system`; tests + /// inject their own so they do not depend on real DNS). + var resolveFamilies: @Sendable (String) -> [IPFamily] = { IPFamilyResolver.system($0) } var requestedWiring: [Wire: Bool] = [:] /// Level (0...2) last requested for each connection that is requested on (per-call speaker /// and microphone volume live on the call<->sound device connections). @@ -224,8 +230,10 @@ public actor Engine { /// - nullAudio: use PJSIP's null sound device (tests, self-test: no microphone prompt). /// Device selections are remembered but not applied. /// - bindAddress: bind SIP and RTP to this local address and advertise it in Contact/SDP - /// (e.g. "127.0.0.1" for calls on this machine). nil = all interfaces, PJSIP picks - /// the default-route address (which may be a VPN tunnel). + /// (e.g. "127.0.0.1" or "::1" for calls on this machine; brackets are dropped). Only the + /// transports of its family exist then, and accounts of the other family are refused + /// (`transportUnavailable`). nil = all interfaces and both families, PJSIP picks the + /// default-route address (which may be a VPN tunnel). /// - caBundleURL: where `start` writes the macOS system root certificates (PEM) that /// the TLS transport verifies servers against. nil = Application Support/MacroSIP/ca-roots.pem. /// - monitorNetwork: watch the network path (NWPathMonitor). false: the network counts as @@ -236,7 +244,7 @@ public actor Engine { self.monitorNetwork = monitorNetwork self.logLevel = max(0, min(6, logLevel)) self.nullAudio = nullAudio - let addr = bindAddress?.trimmingCharacters(in: .whitespaces) + let addr = bindAddress?.trimmingCharacters(in: CharacterSet(charactersIn: "[] \t")) self.bindAddress = (addr?.isEmpty ?? true) ? nil : addr self.caBundleURL = caBundleURL ?? TLSRoots.defaultURL self.queue = DispatchSerialQueue(label: "macrosip.engine", qos: .userInitiated) @@ -437,21 +445,21 @@ public actor Engine { pjsip_cfg().pointee.endpt.disable_tcp_switch = 1 } - /// UDP is required; TCP and TLS failures are logged and only disable accounts of that kind. - /// TLS exists twice: verifying (system roots + host name) and, for accounts that opted - /// out with `verifyTLSCertificate == false`, non-verifying. - private func createTransports(_ network: NetworkSettings) throws { - var udp = PJ.invalidID - try PJ.check(cpjsua_transport_create2(PJSIP_TRANSPORT_UDP, UInt32(network.localPort), bindAddress, &udp), - "UDP transport on port \(network.localPort)") - transports.udp = udp - - var tcp = PJ.invalidID - let tcpStatus = cpjsua_transport_create2(PJSIP_TRANSPORT_TCP, UInt32(network.localPort), bindAddress, &tcp) - PJ.warn(tcpStatus, "TCP transport on port \(network.localPort)") - if tcpStatus == PJ.success { transports.tcp = tcp } + /// The families the engine creates transports for: the bind address's (a non-literal counts as + /// IPv4, as pjsua resolves it for an IPv4 socket), or both without one. + var transportFamilies: [IPFamily] { + guard let bindAddress else { return [.ipv4, .ipv6] } + return [IPFamilyPolicy.literalFamily(bindAddress) ?? .ipv4] + } - // A missing bundle leaves the verifying transport without CAs: it then rejects every + /// Per family: UDP, TCP and TLS twice (verifying: system roots + host name; and, for accounts + /// that opted out with `verifyTLSCertificate == false`, non-verifying). UDP of the first family + /// (IPv4, or the bind address's) is required; every other failure is logged and only disables + /// accounts of that kind and family. IPv6 transports are never fatal: a Mac may have no IPv6 at + /// all. pjlib sets IPV6_V6ONLY on IPv6 sockets (PJ_SOCK_HAS_IPV6_V6ONLY), so [::]:port and + /// 0.0.0.0:port coexist and both families use the configured local port. + private func createTransports(_ network: NetworkSettings) throws { + // A missing bundle leaves the verifying transports without CAs: they then reject every // server (fails closed) instead of silently trusting them. var caFile: String? do { @@ -463,20 +471,62 @@ public actor Engine { bridge.engineLogger.error("\(text, privacy: .public)") emit(.log(level: 1, "engine: \(text)")) } + let families = transportFamilies + for family in families { + try createTransports(family, network: network, caFile: caFile, required: family == families.first) + } + } + + private func createTransports(_ family: IPFamily, network: NetworkSettings, caFile: String?, required: Bool) throws { + let v6 = family == .ipv6 + let name = v6 ? " over IPv6" : "" + var udp = PJ.invalidID + let udpStatus = cpjsua_transport_create2(v6 ? PJSIP_TRANSPORT_UDP6 : PJSIP_TRANSPORT_UDP, + UInt32(network.localPort), bindAddress, &udp) + if required { + try PJ.check(udpStatus, "UDP\(name) transport on port \(network.localPort)") + } else { + PJ.warn(udpStatus, "UDP\(name) transport on port \(network.localPort)") + } + let udpID: Int32? = udpStatus == PJ.success ? udp : nil + + var tcp = PJ.invalidID + let tcpStatus = cpjsua_transport_create2(v6 ? PJSIP_TRANSPORT_TCP6 : PJSIP_TRANSPORT_TCP, + UInt32(network.localPort), bindAddress, &tcp) + PJ.warn(tcpStatus, "TCP\(name) transport on port \(network.localPort)") + let tcpID: Int32? = tcpStatus == PJ.success ? tcp : nil + + let tlsType = v6 ? PJSIP_TRANSPORT_TLS6 : PJSIP_TRANSPORT_TLS var tls = PJ.invalidID - let tlsStatus = cpjsua_tls_transport_create(0, bindAddress, 1, caFile, &tls) - PJ.warn(tlsStatus, "TLS transport (verifying)") - if tlsStatus == PJ.success { transports.tls = tls } + let tlsStatus = cpjsua_tls_transport_create(tlsType, 0, bindAddress, 1, caFile, &tls) + PJ.warn(tlsStatus, "TLS\(name) transport (verifying)") + let tlsID: Int32? = tlsStatus == PJ.success ? tls : nil var tlsNoVerify = PJ.invalidID - let noVerifyStatus = cpjsua_tls_transport_create(0, bindAddress, 0, nil, &tlsNoVerify) - PJ.warn(noVerifyStatus, "TLS transport (no certificate verification)") - if noVerifyStatus == PJ.success { transports.tlsNoVerify = tlsNoVerify } + let noVerifyStatus = cpjsua_tls_transport_create(tlsType, 0, bindAddress, 0, nil, &tlsNoVerify) + PJ.warn(noVerifyStatus, "TLS\(name) transport (no certificate verification)") + let noVerifyID: Int32? = noVerifyStatus == PJ.success ? tlsNoVerify : nil + + switch family { + case .ipv4: + (transports.udp, transports.tcp, transports.tls, transports.tlsNoVerify) = (udpID, tcpID, tlsID, noVerifyID) + case .ipv6: + (transports.udp6, transports.tcp6, transports.tls6, transports.tls6NoVerify) = (udpID, tcpID, tlsID, noVerifyID) + } + let made = [("UDP", udpID), ("TCP", tcpID), ("TLS", tlsID)].compactMap { kind, id in + id.map { "\(kind) \(cpjsua_transport_port($0))" } + } + emit(.log(level: 4, "engine: \(family) transports: " + (made.isEmpty ? "none" : made.joined(separator: ", ")))) } - /// Local SIP port of a transport, 0 if unknown (diagnostics, CLI). + /// Local SIP port of an IPv4 transport, 0 if unknown (diagnostics, CLI). public func localPort(of kind: TransportKind) -> Int { - guard isStarted, let id = transports.id(for: kind) else { return 0 } + localPort(of: kind, family: .ipv4) + } + + /// Local SIP port of a transport of `family`, 0 if it does not exist. + public func localPort(of kind: TransportKind, family: IPFamily) -> Int { + guard isStarted, let id = transports.id(for: kind, family: family) else { return 0 } PJ.registerThread() return Int(cpjsua_transport_port(id)) } diff --git a/Sources/MacroSIPCore/Engine/EngineTypes.swift b/Sources/MacroSIPCore/Engine/EngineTypes.swift index 0c10496..283f495 100644 --- a/Sources/MacroSIPCore/Engine/EngineTypes.swift +++ b/Sources/MacroSIPCore/Engine/EngineTypes.swift @@ -267,7 +267,9 @@ public enum EngineError: Error, Equatable, Sendable, CustomStringConvertible { case unknownAccount(AccountID) case noSuchCall(CallID) case tooManyCalls(limit: Int) - case transportUnavailable(TransportKind) + /// No transport of this kind (and family: `ipv6`) exists, e.g. the IPv6 transports with an IPv4 + /// bind address, or a TLS listener that could not be created. + case transportUnavailable(TransportKind, ipv6: Bool = false) case invalidArgument(String) case unsupported(String) @@ -279,7 +281,8 @@ public enum EngineError: Error, Equatable, Sendable, CustomStringConvertible { case let .unknownAccount(id): return "Unknown account \(id.raw)" case let .noSuchCall(id): return "No such call \(id)" case let .tooManyCalls(limit): return "Too many calls (limit \(limit))" - case let .transportUnavailable(kind): return "\(kind.rawValue.uppercased()) transport is not available" + case let .transportUnavailable(kind, ipv6): + return "\(kind.rawValue.uppercased())\(ipv6 ? " over IPv6" : "") transport is not available" case let .invalidArgument(what): return "Invalid argument: \(what)" case let .unsupported(what): return "Not supported: \(what)" } diff --git a/Sources/MacroSIPCore/Engine/IPFamily.swift b/Sources/MacroSIPCore/Engine/IPFamily.swift new file mode 100644 index 0000000..7069397 --- /dev/null +++ b/Sources/MacroSIPCore/Engine/IPFamily.swift @@ -0,0 +1,133 @@ +import Darwin +import Foundation + +/// IP family of an account's signalling and media (docs/ENGINE.md "IPv6", ADR 0014). +public enum IPFamily: String, Sendable, CaseIterable, CustomStringConvertible { + case ipv4, ipv6 + + public var description: String { self == .ipv4 ? "IPv4" : "IPv6" } +} + +/// Host and port of one SIP hop as the account spells it: "pbx.example.com", "10.0.0.1:5080", +/// "sip:[2001:db8::1]:5070;lr", "". IPv6 hosts without brackets. +struct SIPHop: Equatable, Sendable { + var host: String + var port: Int? + + static func parse(_ raw: String) -> SIPHop? { + var s = raw.trimmingCharacters(in: .whitespaces) + if let lt = s.firstIndex(of: "<"), let gt = s[lt...].firstIndex(of: ">") { + s = String(s[s.index(after: lt).. IPFamily? { + var a = host.trimmingCharacters(in: CharacterSet(charactersIn: "[] ")) + if let zone = a.firstIndex(of: "%") { a = String(a[.. SIPHop { + let proxy = account.outboundProxy?.trimmingCharacters(in: .whitespaces) ?? "" + return SIPHop.parse(proxy.isEmpty ? account.registrarURI : proxy) ?? SIPHop(host: "", port: nil) + } + + /// The family of the server's IP literal when it contradicts the account's IP protocol (IPv4 only with + /// "[2001:db8::1]", IPv6 only with "192.0.2.1"); nil when there is nothing to contradict. Such an + /// account cannot work: the editor says so and the engine refuses it (`EngineError.invalidArgument`). + public static func conflict(in account: AccountConfig) -> IPFamily? { + let wanted: IPFamily + switch account.ipProtocol { + case .auto: return nil + case .ipv4: wanted = .ipv4 + case .ipv6: wanted = .ipv6 + } + guard let literal = literalFamily(firstHop(of: account).host), literal != wanted else { return nil } + return literal + } + + /// The family for `account` (assumes no `conflict`). `available`: families with a transport for the + /// account's transport kind; `srv`: DNS SRV is in effect; `resolve`: the families of a host name in the + /// system resolver's order. + static func decide(_ account: AccountConfig, available: Set, srv: Bool, + resolve: (String) -> [IPFamily]) -> IPFamily { + let hop = firstHop(of: account) + if let literal = literalFamily(hop.host) { return literal } + switch account.ipProtocol { + case .ipv4: return .ipv4 + case .ipv6: return .ipv6 + case .auto: break + } + if available.count == 1, let only = available.first { return only } + if srv && hop.port == nil { return .ipv4 } + guard !hop.host.isEmpty else { return .ipv4 } + return resolve(hop.host).first { available.isEmpty || available.contains($0) } ?? .ipv4 + } + + /// The decision depends on the resolver's answer, so it may change with the network: Auto, a host + /// name, and not the SRV case. + static func followsResolver(_ account: AccountConfig, srv: Bool) -> Bool { + let hop = firstHop(of: account) + return account.ipProtocol == .auto && !hop.host.isEmpty && literalFamily(hop.host) == nil + && !(srv && hop.port == nil) + } +} + +/// The system resolver's view of a host name. +enum IPFamilyResolver { + /// The address families getaddrinfo returns for `host`, in its order, each once. The hints are + /// pj_getaddrinfo's (AF_UNSPEC, no socket type, no flags), so the first entry is the one PJSIP sends to + /// first. Synchronous, like PJSIP's own lookup without its DNS resolver (sip_resolve.c); [] on failure. + static func system(_ host: String) -> [IPFamily] { + let name = host.trimmingCharacters(in: CharacterSet(charactersIn: "[] ")) + guard !name.isEmpty else { return [] } + var hints = addrinfo() + hints.ai_family = AF_UNSPEC + var result: UnsafeMutablePointer? + guard getaddrinfo(name, nil, &hints, &result) == 0 else { return [] } + defer { freeaddrinfo(result) } + var families: [IPFamily] = [] + var entry = result + while let e = entry { + let family: IPFamily? = e.pointee.ai_family == AF_INET6 ? .ipv6 : e.pointee.ai_family == AF_INET ? .ipv4 : nil + if let family, !families.contains(family) { families.append(family) } + entry = e.pointee.ai_next + } + return families + } +} diff --git a/Sources/MacroSIPCore/Engine/NetworkPathMonitor.swift b/Sources/MacroSIPCore/Engine/NetworkPathMonitor.swift index 7265df2..9b020ab 100644 --- a/Sources/MacroSIPCore/Engine/NetworkPathMonitor.swift +++ b/Sources/MacroSIPCore/Engine/NetworkPathMonitor.swift @@ -3,10 +3,11 @@ import Foundation import Network /// One evaluation of the network path (`NWPathMonitor`), reduced to the primary route: the -/// first available interface (the one the system routes through), the local IPv4 address -/// the default route uses and the default gateway. Secondary interfaces (bridge100 of +/// first available interface (the one the system routes through), the local IPv4 and IPv6 +/// addresses the default routes use and the default gateway. Secondary interfaces (bridge100 of /// Internet Sharing, a split-tunnel utun, a second Wi-Fi/Ethernet) coming and going do not -/// change it; a full-tunnel VPN that takes the default route does. +/// change it; a full-tunnel VPN that takes the default route does, and so does a new IPv6 +/// source address on the same interface (a new temporary address). struct NetworkPath: Sendable, Equatable { /// `NWPath.status == .satisfied`. var satisfied: Bool @@ -15,17 +16,23 @@ struct NetworkPath: Sendable, Equatable { /// Source address of the default route (what pjsua's sockets use towards the PBX), "" when /// there is no route. var address: String + /// Source address of the default IPv6 route (a global address: link-local and loopback do not + /// count), "" when there is none. + var address6: String /// Default gateway, "" when unknown. var gateway: String /// Short text for the log. var summary: String - init(satisfied: Bool, interface: String, address: String, gateway: String, summary: String? = nil) { + init(satisfied: Bool, interface: String, address: String, address6: String = "", gateway: String, + summary: String? = nil) { self.satisfied = satisfied self.interface = interface self.address = address + self.address6 = address6 self.gateway = gateway - self.summary = summary ?? NetworkPath.describe(interface: interface, address: address, gateway: gateway) + self.summary = summary ?? NetworkPath.describe(interface: interface, address: address, address6: address6, + gateway: gateway) } init(_ path: NWPath) { @@ -40,26 +47,31 @@ struct NetworkPath: Sendable, Equatable { } let name = primary?.name ?? "" let address = path.status == .satisfied ? (NetworkPath.defaultRouteSource() ?? "") : "" + let address6 = path.status == .satisfied ? (NetworkPath.defaultRouteSource6() ?? "") : "" let gateway = path.gateways.first.map { "\($0)" } ?? "" - self.init(satisfied: path.status == .satisfied, interface: name, address: address, gateway: gateway, + self.init(satisfied: path.status == .satisfied, interface: name, address: address, address6: address6, + gateway: gateway, summary: NetworkPath.describe(interface: name.isEmpty ? "" : "\(name)/\(type)", - address: address, gateway: gateway)) + address: address, address6: address6, gateway: gateway)) } - /// The local address or interface changed: sockets, Contact and RTP addresses are stale. - func primaryDiffers(from other: NetworkPath) -> Bool { - interface != other.interface || address != other.address + /// A local address or the interface changed: sockets, Contact and RTP addresses are stale. + /// `ipv6: false` leaves the IPv6 address out (no account uses IPv6, so a new temporary address + /// changes nothing for the calls and registrations). + func primaryDiffers(from other: NetworkPath, ipv6: Bool = true) -> Bool { + interface != other.interface || address != other.address || (ipv6 && address6 != other.address6) } /// Anything of the primary route changed (a gateway-only change keeps the address but may /// mean another network behind the same address, i.e. another NAT binding). - func routeDiffers(from other: NetworkPath) -> Bool { - primaryDiffers(from: other) || gateway != other.gateway + func routeDiffers(from other: NetworkPath, ipv6: Bool = true) -> Bool { + primaryDiffers(from: other, ipv6: ipv6) || gateway != other.gateway } - static func describe(interface: String, address: String, gateway: String) -> String { + static func describe(interface: String, address: String, address6: String = "", gateway: String) -> String { (interface.isEmpty ? "no interface" : interface) + (address.isEmpty ? "" : " " + address) + + (address6.isEmpty ? "" : " " + address6) + (gateway.isEmpty ? "" : " via " + gateway) } @@ -91,6 +103,48 @@ struct NetworkPath: Sendable, Equatable { let text = String(decoding: buf.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self) return text == "0.0.0.0" ? nil : text } + + /// The same for IPv6: a UDP socket "connected" to 2001:db8::1 (documentation prefix, nothing is + /// sent). nil without a default IPv6 route or when the kernel would only use a link-local or + /// loopback source (no global IPv6 on this network). With temporary addresses (RFC 8981) this is + /// the preferred temporary address, the one new sockets use. + static func defaultRouteSource6() -> String? { + let fd = socket(AF_INET6, SOCK_DGRAM, 0) + guard fd >= 0 else { return nil } + defer { close(fd) } + var dest = sockaddr_in6() + dest.sin6_len = UInt8(MemoryLayout.size) + dest.sin6_family = sa_family_t(AF_INET6) + dest.sin6_port = in_port_t(UInt16(9).bigEndian) + guard inet_pton(AF_INET6, "2001:db8::1", &dest.sin6_addr) == 1 else { return nil } + let connected = withUnsafePointer(to: &dest) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { + connect(fd, $0, socklen_t(MemoryLayout.size)) == 0 + } + } + guard connected else { return nil } + var local = sockaddr_in6() + var len = socklen_t(MemoryLayout.size) + let named = withUnsafeMutablePointer(to: &local) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { getsockname(fd, $0, &len) == 0 } + } + guard named else { return nil } + var buf = [CChar](repeating: 0, count: Int(INET6_ADDRSTRLEN)) + guard inet_ntop(AF_INET6, &local.sin6_addr, &buf, socklen_t(buf.count)) != nil else { return nil } + let text = String(decoding: buf.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self) + return isUsableIPv6Source(text) ? text : nil + } + + /// A global IPv6 address: not unspecified, loopback or link-local (fe80::/10). + static func isUsableIPv6Source(_ text: String) -> Bool { + var a = in6_addr() + guard inet_pton(AF_INET6, text, &a) == 1 else { return false } + let b = withUnsafeBytes(of: &a) { Array($0) } + if b.allSatisfy({ $0 == 0 }) { return false } // :: + if b[0..<15].allSatisfy({ $0 == 0 }) && b[15] == 1 { return false } // ::1 + if b[0] == 0xfe && b[1] & 0xc0 == 0x80 { return false } // fe80::/10 + return true + } } /// `NWPathMonitor` on its own queue. Updates are delivered in order through `paths` (one diff --git a/Sources/MacroSIPCore/Model/AccountConfig.swift b/Sources/MacroSIPCore/Model/AccountConfig.swift index 3a86020..28734b0 100644 --- a/Sources/MacroSIPCore/Model/AccountConfig.swift +++ b/Sources/MacroSIPCore/Model/AccountConfig.swift @@ -13,6 +13,18 @@ public enum SRTPMode: String, Codable, Sendable, CaseIterable { case disabled, optional, mandatory } +/// Which IP family the account's signalling and media use (account editor › Advanced › IP protocol). +/// `.auto`: an IPv4 or IPv6 literal server picks its own family; a host name follows the order the +/// system resolver returns (docs/ENGINE.md "IPv6"). Unknown values decode as `.auto`. +public enum IPProtocol: String, Codable, Sendable, CaseIterable { + case auto, ipv4, ipv6 + + public init(from decoder: Decoder) throws { + let raw = try decoder.singleValueContainer().decode(String.self) + self = IPProtocol(rawValue: raw) ?? .auto + } +} + /// Everything about a SIP account except the password, which lives in Keychain under `id`. public struct AccountConfig: Codable, Identifiable, Equatable, Sendable { public var id: AccountID @@ -39,6 +51,8 @@ public struct AccountConfig: Codable, Identifiable, Equatable, Sendable { public var mwi: Bool /// Number (or SIP URI) the app dials to listen to voicemail; nil = not configured. public var voicemailNumber: String? + /// IP family of signalling and media; `.auto` decides from the server address. + public var ipProtocol: IPProtocol public init( id: AccountID = AccountID(), @@ -57,7 +71,8 @@ public struct AccountConfig: Codable, Identifiable, Equatable, Sendable { publishPresence: Bool = false, verifyTLSCertificate: Bool = true, mwi: Bool = true, - voicemailNumber: String? = nil + voicemailNumber: String? = nil, + ipProtocol: IPProtocol = .auto ) { self.id = id self.displayName = displayName @@ -76,6 +91,7 @@ public struct AccountConfig: Codable, Identifiable, Equatable, Sendable { self.verifyTLSCertificate = verifyTLSCertificate self.mwi = mwi self.voicemailNumber = voicemailNumber + self.ipProtocol = ipProtocol } /// The engine sends REGISTER for this account. @@ -107,11 +123,12 @@ extension AccountConfig { private enum CodingKeys: String, CodingKey { case id, displayName, username, domain, registrar, outboundProxy, authID, transport, srtp case enabled, registerWithServer, isDefaultOutgoing, registrationInterval, publishPresence, verifyTLSCertificate - case mwi, voicemailNumber + case mwi, voicemailNumber, ipProtocol } - /// Decodes JSON written before `verifyTLSCertificate`, `registerWithServer`, `mwi` and - /// `voicemailNumber` existed (missing: verify on, MWI on, no voicemail number). + /// Decodes JSON written before `verifyTLSCertificate`, `registerWithServer`, `mwi`, + /// `voicemailNumber` and `ipProtocol` existed (missing: verify on, MWI on, no voicemail number, + /// IP protocol Auto). /// Before `registerWithServer`, `enabled == false` meant "do not register"; that becomes an /// enabled, outgoing-only account so nothing silently turns into a disabled one. public init(from decoder: Decoder) throws { @@ -136,7 +153,8 @@ extension AccountConfig { publishPresence: try c.decode(Bool.self, forKey: .publishPresence), verifyTLSCertificate: try c.decodeIfPresent(Bool.self, forKey: .verifyTLSCertificate) ?? true, mwi: (try? c.decodeIfPresent(Bool.self, forKey: .mwi)) ?? true, - voicemailNumber: try? c.decodeIfPresent(String.self, forKey: .voicemailNumber) + voicemailNumber: try? c.decodeIfPresent(String.self, forKey: .voicemailNumber), + ipProtocol: (try? c.decodeIfPresent(IPProtocol.self, forKey: .ipProtocol)) ?? .auto ) } } diff --git a/Sources/macrosip-cli/main.swift b/Sources/macrosip-cli/main.swift index 7650c1d..f648e80 100644 --- a/Sources/macrosip-cli/main.swift +++ b/Sources/macrosip-cli/main.swift @@ -15,7 +15,8 @@ // and the transfer checks are driven there; --target2-cli is the one of --target2 (transfers). // Without both CLI ports the incoming-call and transfer steps are skipped. // --bind binds SIP/RTP to ADDR and advertises it (the self-test uses 127.0.0.1 so a VPN -// default route cannot swallow localhost traffic; "any" = all interfaces, the interactive default). +// default route cannot swallow localhost traffic; "any" = all interfaces and both IP families, the +// interactive default). An IPv6 ADDR ("::1") creates the IPv6 transports only, an IPv4 one the IPv4 ones. // // Interactive commands: type `help`. diff --git a/Tests/MacroSIPCoreTests/Engine262Tests.swift b/Tests/MacroSIPCoreTests/Engine262Tests.swift index f8b3acb..4638738 100644 --- a/Tests/MacroSIPCoreTests/Engine262Tests.swift +++ b/Tests/MacroSIPCoreTests/Engine262Tests.swift @@ -354,9 +354,10 @@ struct Engine262ValueTests { /// STUN is off only when every signalling hop is private: registrar and proxy, or registrar /// and domain without a proxy. In pjsua_acc_config: `sip_stun_use` and `media_stun_use` /// DISABLED and `allow_sdp_nat_rewrite` on for such an account, pjsua's defaults otherwise; a - /// UDP account of a private server with IPv4 hops is not bound to the UDP transport while a - /// STUN server is set (IPv6 hops stay bound: no IPv6 transport exists). allow_contact_rewrite - /// and allow_via_rewrite stay on either way. + /// UDP account of a private IPv4 server is not bound to the UDP transport while a STUN server + /// is set. An IPv6 server (also an IPv4-mapped literal) is bound to the IPv6 twin of its + /// transport, with STUN off (since 26.3.1). allow_contact_rewrite and allow_via_rewrite stay + /// on either way. @Test func privateServerAccountsDoNotUseSTUN() throws { func account(_ domain: String, registrar: String? = nil, proxy: String? = nil, transport: TransportKind = .udp) -> AccountConfig { @@ -370,8 +371,8 @@ struct Engine262ValueTests { account("pbx.office.lan", registrar: "10.10.0.53", proxy: "sip:10.10.0.1;lr"), // all via the proxy account("192.168.1.10", proxy: "192.168.1.1:5060"), account("100.101.102.103"), // a tailnet - account("[fd00::5]"), // IPv6: stays bound - account("[::ffff:10.1.2.3]"), // so does a mapped IPv4 + account("[fd00::5]"), // IPv6: bound to UDP6 + account("[::ffff:10.1.2.3]"), // so is a mapped IPv4 ] let stunAccounts = [ account("pbx.example.com"), @@ -382,16 +383,19 @@ struct Engine262ValueTests { account("pbx.office.lan", registrar: "10.10.0.53"), // calls go to a host name account("localhost"), // names are not resolved ] - let transports = TransportIDs(udp: 0, tcp: 1, tls: 2, tlsNoVerify: 3) + let transports = TransportIDs(udp: 0, tcp: 1, tls: 2, tlsNoVerify: 3, udp6: 4, tcp6: 5, tls6: 6, tls6NoVerify: 7) let noSTUN = NetworkSettings(stunServer: nil) for (accounts, stun) in [(privateAccounts, false), (stunAccounts, true)] { for a in accounts { #expect(PrivateServer.allHopsPrivate(a) == !stun, "\(a.registrarURI) \(a.outboundProxy ?? "-")") let ipv6 = a.domain.hasPrefix("[") - if !stun { #expect(PrivateServer.allHopsIPv4(a) == !ipv6, "\(a.registrarURI)") } - let bound: Int32 = a.transport == .tcp ? 1 : 0 + // The family as the engine decides it; host names here are IPv4 (no lookup in a value test). + let family = IPFamilyPolicy.decide(a, available: [.ipv4, .ipv6], srv: false) { _ in [.ipv4] } + #expect(family == (ipv6 ? .ipv6 : .ipv4), "\(a.registrarURI)") + let bound: Int32 = (a.transport == .tcp ? 1 : 0) + (ipv6 ? 4 : 0) for network in [NetworkSettings.default, noSTUN] { - let s = try AccountMapping.settings(for: a, password: "pw", network: network, transports: transports) + let s = try AccountMapping.settings(for: a, password: "pw", network: network, transports: transports, + family: family) let back = AccountMapping.withPJConfig(s) { AccountMapping.readBack($0) } let unbound = !stun && !ipv6 && a.transport == .udp && network.stunServer != nil for (label, x) in [("settings", s), ("pjsua_acc_config", back)] { @@ -553,10 +557,11 @@ extension EngineTests { /// A server in a private network gets no STUN. The STUN stub maps every socket to /// 203.0.113.5, so the UDP transport is published with that address. An account that reaches - /// the registrar by name ("localhost") keeps STUN: 203.0.113.5 in Via, Contact and SDP, and - /// its RTP sockets ask the stub. The account at 127.0.0.1 sends Via and Contact with - /// 127.0.0.1, registers, and its call neither asks STUN nor offers the mapped address: the - /// SDP has the Contact's address, not the default route's. + /// the registrar by name ("localhost", IPv4 only: on Auto the name would usually resolve to + /// ::1 first and the account would use IPv6, which has no STUN at all) keeps STUN: + /// 203.0.113.5 in Via, Contact and SDP, and its RTP sockets ask the stub. The account at + /// 127.0.0.1 sends Via and Contact with 127.0.0.1, registers, and its call neither asks STUN + /// nor offers the mapped address: the SDP has the Contact's address, not the default route's. @Test func privateServerAccountDoesNotUseSTUN() async throws { let stun = try STUNStub(mapped: "203.0.113.5") defer { stun.stop() } @@ -575,7 +580,7 @@ extension EngineTests { func mediaSTUNRequests() -> Int { stun.sources.filter { (rtp.start..<(rtp.start + rtp.count)).contains(Int($0)) }.count } let named = AccountConfig(displayName: "N", username: "2002", domain: "localhost", - registrar: "localhost:\(sip.port)", enabled: true) + registrar: "localhost:\(sip.port)", enabled: true, ipProtocol: .ipv4) try await engine.addAccount(named, password: "pw") #expect(await waitUntil { await engine.registrationState(of: named.id).isRegistered }) let n = try #require(sip.registers.first { $0.contact.contains("sip:2002@") }) @@ -608,25 +613,27 @@ extension EngineTests { await engine.stop() } - /// An IPv6 private server keeps its account bound to the UDP transport while STUN is on: - /// unbound, pjsua would want an IPv6 transport for it (none exists) and refuse the account. - /// Bound, it is added and its failing REGISTER is retried like any temporary failure. + /// An IPv6 private server with STUN on (26.2: the account stayed bound to the IPv4 UDP transport + /// and was retried forever) is bound to the UDP6 transport since 26.3.1, uses no STUN and + /// registers over IPv6. The engine runs on all interfaces, as in the app. @Test func privateIPv6ServerAccountIsAdded() async throws { let stun = try STUNStub(mapped: "203.0.113.5") defer { stun.stop() } - let engine = await makeEngine() + let sip = try IPv6Stub() + defer { sip.stop() } + let engine = await makeEngine(bindAddress: nil) var net = Self.network net.stunServer = "127.0.0.1:\(stun.port)" try await engine.start(network: net) let account = AccountConfig(displayName: "6", username: "2006", domain: "[::1]", - registrar: "[::1]:5999", enabled: true) + registrar: "[::1]:\(sip.port)", enabled: true, mwi: false) try await engine.addAccount(account, password: "pw") - let retried = await waitUntil { - if case .reconnecting = await engine.registrationState(of: account.id) { return true } - return false - } - let state = await engine.registrationState(of: account.id) - #expect(retried, "state: \(state)") + #expect(await waitUntil { await engine.registrationState(of: account.id).isRegistered }) + let register = try #require(sip.registers.first) + #expect(register.family == .ipv6 && register.via.hasPrefix("SIP/2.0/UDP ["), "\(register.via)") + let live = try #require(await engine.liveAccountSettingsForTests(account.id)) + #expect(live.transportID == (await engine.transportIDsForTests()).udp6) + #expect(!live.sipSTUN && !live.mediaSTUN) try await engine.removeAccount(account.id) await engine.stop() } diff --git a/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift b/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift new file mode 100644 index 0000000..a8c3100 --- /dev/null +++ b/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift @@ -0,0 +1,981 @@ +import Foundation +import os +import Testing +@testable import MacroSIPCore + +// IPv6 dual stack (docs/ENGINE.md "IPv6", ADR 0014): the per-account IP protocol, the family +// decision, IPv6 transports and accounts bound to them, IPv6 media, incoming requests over IPv6. +// Everything runs on loopback ([::1] and 127.0.0.1); nothing leaves the Mac. + +// MARK: - IPv6 SIP stub + +/// A SIP stub on [::1]: one UDP socket and one TCP listener, and with `dualStack` a UDP socket on +/// 127.0.0.1 with the same port number, so an account at "localhost:" reaches it over either +/// family. Answers REGISTER with 200 (Contacts listed), INVITE with 200 and an `IN IP6 ::1` answer, +/// everything else with 200; requests that arrive on a family in `silentFamilies` are recorded and +/// left unanswered. Records every request with the family and transport it came over. Can send +/// INVITE and MESSAGE to the engine from its UDP sockets; their responses are recorded, a 2xx to +/// INVITE is ACKed and the call hung up with BYE. +final class IPv6Stub: Sendable { + struct Request: Sendable { + var method: String + var family: IPFamily + var transport: String // "UDP" or "TCP" + var via: String // top Via value + var contact: String // first Contact value + var cseq: String + var body: String + } + + struct Response: Sendable { + var status: String // "SIP/2.0 200 OK" + var callID: String + var body: String + } + + let port: UInt16 + let tcpPort: UInt16 + let rtpPort: UInt16 + private let udp6: Int32 + private let udp4: Int32? + private let tcp: Int32 + private let rtp6: Int32 + private let stopped = OSAllocatedUnfairLock(initialState: false) + private let silent = OSAllocatedUnfairLock(initialState: Set()) + private let received = OSAllocatedUnfairLock(initialState: [Request]()) + private let answers = OSAllocatedUnfairLock(initialState: [Response]()) + + var requests: [Request] { received.withLock { $0 } } + var responses: [Response] { answers.withLock { $0 } } + /// REGISTER requests with a new CSeq (retransmissions left out), in order. + var registers: [Request] { + var seen: Set = [] + return requests.filter { $0.method == "REGISTER" && seen.insert($0.cseq).inserted } + } + var silentFamilies: Set { + get { silent.withLock { $0 } } + set { silent.withLock { $0 = newValue } } + } + + init(dualStack: Bool = false) throws { + var attempt = 0 + while true { + attempt += 1 + let (fd6, p) = try IPv6Stub.bindSocket(.ipv6, type: SOCK_DGRAM, port: 0) + if dualStack { + guard let (fd4, _) = try? IPv6Stub.bindSocket(.ipv4, type: SOCK_DGRAM, port: p) else { + close(fd6) + if attempt < 20 { continue } + throw EngineError.unsupported("no port free on both families") + } + udp4 = fd4 + } else { + udp4 = nil + } + udp6 = fd6 + port = p + break + } + (tcp, tcpPort) = try IPv6Stub.bindSocket(.ipv6, type: SOCK_STREAM, port: 0) + guard listen(tcp, 8) == 0 else { throw EngineError.unsupported("listen") } + (rtp6, rtpPort) = try IPv6Stub.bindSocket(.ipv6, type: SOCK_DGRAM, port: 0) + let udp6 = udp6, udp4 = udp4 + Thread.detachNewThread { [self] in self.serveUDP(udp6, family: .ipv6) } + if let udp4 { Thread.detachNewThread { [self] in self.serveUDP(udp4, family: .ipv4) } } + Thread.detachNewThread { [self] in self.acceptTCP() } + } + + func stop() { stopped.withLock { $0 = true } } + private var isStopped: Bool { stopped.withLock { $0 } } + + // MARK: sockets + + static func address(_ family: IPFamily, port: UInt16) -> (sockaddr_storage, socklen_t) { + var storage = sockaddr_storage() + switch family { + case .ipv6: + withUnsafeMutablePointer(to: &storage) { + $0.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) { a in + a.pointee.sin6_len = UInt8(MemoryLayout.size) + a.pointee.sin6_family = sa_family_t(AF_INET6) + a.pointee.sin6_port = in_port_t(port.bigEndian) + a.pointee.sin6_addr = in6addr_loopback + } + } + return (storage, socklen_t(MemoryLayout.size)) + case .ipv4: + withUnsafeMutablePointer(to: &storage) { + $0.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { a in + a.pointee.sin_len = UInt8(MemoryLayout.size) + a.pointee.sin_family = sa_family_t(AF_INET) + a.pointee.sin_port = in_port_t(port.bigEndian) + a.pointee.sin_addr.s_addr = inet_addr("127.0.0.1") + } + } + return (storage, socklen_t(MemoryLayout.size)) + } + } + + private static func bindSocket(_ family: IPFamily, type: Int32, port: UInt16) throws -> (Int32, UInt16) { + let fd = socket(family == .ipv6 ? AF_INET6 : AF_INET, type, 0) + guard fd >= 0 else { throw EngineError.unsupported("socket") } + var one: Int32 = 1 + if family == .ipv6 { setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &one, socklen_t(MemoryLayout.size)) } + if type == SOCK_STREAM { setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, socklen_t(MemoryLayout.size)) } + var (addr, len) = address(family, port: port) + let ok = withUnsafeMutablePointer(to: &addr) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(fd, $0, len) == 0 && getsockname(fd, $0, &len) == 0 } + } + guard ok else { close(fd); throw EngineError.unsupported("bind") } + let bound = withUnsafePointer(to: &addr) { p -> UInt16 in + family == .ipv6 + ? p.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) { UInt16(bigEndian: $0.pointee.sin6_port) } + : p.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { UInt16(bigEndian: $0.pointee.sin_port) } + } + var tv = timeval(tv_sec: 0, tv_usec: 100_000) + setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, socklen_t(MemoryLayout.size)) + return (fd, bound) + } + + private static func sendUDP(_ fd: Int32, _ text: String, to dest: sockaddr_storage, _ len: socklen_t) { + var dest = dest + let bytes = Array(text.utf8) + _ = withUnsafePointer(to: &dest) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { sendto(fd, bytes, bytes.count, 0, $0, len) } + } + } + + private func serveUDP(_ fd: Int32, family: IPFamily) { + var buf = [UInt8](repeating: 0, count: 65_536) + while !isStopped { + var from = sockaddr_storage() + var fromLen = socklen_t(MemoryLayout.size) + let n = withUnsafeMutablePointer(to: &from) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { recvfrom(fd, &buf, buf.count, 0, $0, &fromLen) } + } + guard n > 0 else { continue } + let peer = from, peerLen = fromLen + handle(String(decoding: buf[0.. 0 else { continue } + let conn = accept(tcp, nil, nil) + guard conn >= 0 else { continue } + Thread.detachNewThread { [self] in self.serveTCP(conn) } + } + close(tcp) + } + + private func serveTCP(_ fd: Int32) { + var pending: [UInt8] = [] + var buf = [UInt8](repeating: 0, count: 65_536) + while !isStopped { + var pfd = pollfd(fd: fd, events: Int16(POLLIN), revents: 0) + guard poll(&pfd, 1, 100) > 0 else { continue } + let n = read(fd, &buf, buf.count) + guard n > 0 else { break } + pending += buf[0.. String? { + while data.first == 13 || data.first == 10 { data.removeFirst() } // keep-alive CRLFs + let separator: [UInt8] = [13, 10, 13, 10] + guard data.count >= 4, let end = (0...(data.count - 4)).first(where: { Array(data[$0..<($0 + 4)]) == separator }) + else { return nil } + let head = String(decoding: data[0..= total else { return nil } + let message = String(decoding: data[0.. Void) { + let parts = text.components(separatedBy: "\r\n\r\n") + let head = parts.first ?? text + let body = parts.dropFirst().joined(separator: "\r\n\r\n") + let lines = head.components(separatedBy: "\r\n") + guard let first = lines.first else { return } + var echoed: [String] = [], toLine = "", cseq = "", topVia = "", contacts: [String] = [], callID = "" + var fromLine = "", expiresZero = false + for line in lines.dropFirst() { + guard let colon = line.firstIndex(of: ":") else { continue } + let name = line[.."], body: sdp) + default: + reply("200 OK") + } + } + + private func handleResponse(_ status: String, body: String, via: String, from: String, to: String, callID: String, + cseq: String, contact: String, send: (String) -> Void) { + answers.withLock { $0.append(Response(status: status, callID: callID, body: body)) } + let code = Int(status.split(separator: " ").dropFirst().first ?? "") ?? 0 + guard code >= 200, cseq.uppercased().hasSuffix("INVITE") else { return } + let number = cseq.split(separator: " ").first.map(String.init) ?? "1" + let callHeader = "Call-ID: \(callID)" + if code >= 300 { + send("ACK sip:engine SIP/2.0\r\nVia: \(via)\r\nMax-Forwards: 70\r\n\(from)\r\n\(to)\r\n\(callHeader)\r\n" + + "CSeq: \(number) ACK\r\nContent-Length: 0\r\n\r\n") + return + } + var target = "sip:engine" + if let lt = contact.firstIndex(of: "<"), let gt = contact.firstIndex(of: ">") { + target = String(contact[contact.index(after: lt).. String { + let host = family == .ipv6 ? "[::1]" : "127.0.0.1" + let callID = "v6-stub-\(UInt32.random(in: 1...UInt32.max))@stub" + var msg = "\(method) sip:\(user)@\(host):\(port) SIP/2.0\r\n" + msg += "Via: SIP/2.0/UDP \(host):\(self.port);branch=z9hG4bK-v6-\(UInt32.random(in: 1...UInt32.max));rport\r\n" + msg += "Max-Forwards: 70\r\n" + msg += "From: ;tag=v6-from-\(UInt32.random(in: 1...UInt32.max))\r\n" + msg += "To: \r\n" + msg += "Call-ID: \(callID)\r\nCSeq: 1 \(method)\r\n" + if method == "INVITE" { msg += "Contact: \r\n" } + msg += "Content-Type: \(contentType)\r\nContent-Length: \(body.utf8.count)\r\n\r\n" + body + let (dest, len) = IPv6Stub.address(family, port: UInt16(port)) + IPv6Stub.sendUDP(family == .ipv6 ? udp6 : (udp4 ?? udp6), msg, to: dest, len) + return callID + } + + /// An INVITE whose offer has `c=IN IP6 ::1` (or `IN IP4 127.0.0.1` with `ipv4Offer`). + @discardableResult + func sendInvite(toPort port: Int, user: String, family: IPFamily = .ipv6, ipv4Offer: Bool = false) -> String { + let conn = ipv4Offer ? "IN IP4 127.0.0.1" : "IN IP6 ::1" + let sdp = "v=0\r\no=stub 1 1 \(conn)\r\ns=stub\r\nc=\(conn)\r\nt=0 0\r\n" + + "m=audio \(rtpPort) RTP/AVP 0\r\na=rtpmap:0 PCMU/8000\r\na=sendrecv\r\n" + return sendRequest("INVITE", toPort: port, user: user, family: family, contentType: "application/sdp", body: sdp) + } + + @discardableResult + func sendMessage(toPort port: Int, user: String, text: String, family: IPFamily = .ipv6) -> String { + sendRequest("MESSAGE", toPort: port, user: user, family: family, contentType: "text/plain", body: text) + } + + func responses(to callID: String) -> [Response] { responses.filter { $0.callID == callID } } +} + +/// The `c=` value of an SDP body ("IN IP6 ::1"), "" when there is none. +func sdpConnection(_ body: String) -> String { + body.components(separatedBy: "\r\n").first { $0.hasPrefix("c=") }.map { String($0.dropFirst(2)) } ?? "" +} + +/// What getaddrinfo (AF_UNSPEC, as pj_getaddrinfo asks) returns first for `host`. +func systemFirstFamily(_ host: String) -> IPFamily? { + var hints = addrinfo() + hints.ai_family = AF_UNSPEC + var result: UnsafeMutablePointer? + guard getaddrinfo(host, nil, &hints, &result) == 0, let first = result else { return nil } + defer { freeaddrinfo(result) } + switch first.pointee.ai_family { + case AF_INET6: return .ipv6 + case AF_INET: return .ipv4 + default: return nil + } +} + +// MARK: - values (no pjsua) + +@Suite("IPv6 values") +struct IPv6ValueTests { + @Test func ipProtocolDecodesOldJSONAsAuto() throws { + let cfg = AccountConfig(displayName: "A", username: "1", domain: "d", ipProtocol: .ipv6) + let data = try JSONEncoder().encode(cfg) + #expect(String(decoding: data, as: UTF8.self).contains("\"ipProtocol\":\"ipv6\"")) + #expect(try JSONDecoder().decode(AccountConfig.self, from: data) == cfg) + var dict = try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) + dict["ipProtocol"] = nil + let old = try JSONDecoder().decode(AccountConfig.self, from: JSONSerialization.data(withJSONObject: dict)) + #expect(old.ipProtocol == .auto) + dict["ipProtocol"] = "ipv5" + let future = try JSONDecoder().decode(AccountConfig.self, from: JSONSerialization.data(withJSONObject: dict)) + #expect(future.ipProtocol == .auto && future.username == "1") + #expect(AccountConfig(displayName: "N", username: "1", domain: "d").ipProtocol == .auto) + } + + @Test func literalFamilies() { + for h in ["192.0.2.1", "127.0.0.1", "10.0.0.1"] { #expect(IPFamilyPolicy.literalFamily(h) == .ipv4, "\(h)") } + for h in ["::1", "[::1]", "2001:db8::1", "[2001:db8::1]", "[::ffff:10.1.2.3]", "fe80::1%en0"] { + #expect(IPFamilyPolicy.literalFamily(h) == .ipv6, "\(h)") + } + for h in ["localhost", "pbx.example.com", "", "10.0.0", "[pbx]"] { #expect(IPFamilyPolicy.literalFamily(h) == nil, "\(h)") } + } + + /// The first hop is the outbound proxy when one is set, otherwise the registrar (or the domain). + @Test func firstHop() { + func hop(_ a: AccountConfig) -> String { + let h = IPFamilyPolicy.firstHop(of: a) + return "\(h.host)" + (h.port.map { ":\($0)" } ?? "") + } + #expect(hop(AccountConfig(displayName: "", username: "1", domain: "pbx.example.com")) == "pbx.example.com") + #expect(hop(AccountConfig(displayName: "", username: "1", domain: "d", registrar: "[2001:db8::5]:5070")) == "2001:db8::5:5070") + #expect(hop(AccountConfig(displayName: "", username: "1", domain: "[::1]", transport: .tls)) == "::1") + #expect(hop(AccountConfig(displayName: "", username: "1", domain: "[::1]", + outboundProxy: "sip:proxy.example.com:5080;lr")) == "proxy.example.com:5080") + #expect(hop(AccountConfig(displayName: "", username: "1", domain: "d", + outboundProxy: "")) == "192.0.2.7") + } + + /// IPv4 only with an IPv6 literal (and the other way round) contradicts itself: the editor shows it, + /// the engine refuses the account. Auto never conflicts. + @Test func conflicts() { + func a(_ server: String, _ p: IPProtocol, proxy: String? = nil) -> AccountConfig { + AccountConfig(displayName: "", username: "1", domain: server, outboundProxy: proxy, ipProtocol: p) + } + #expect(IPFamilyPolicy.conflict(in: a("[2001:db8::1]", .ipv4)) == .ipv6) + #expect(IPFamilyPolicy.conflict(in: a("192.0.2.1:5060", .ipv6)) == .ipv4) + #expect(IPFamilyPolicy.conflict(in: a("[2001:db8::1]", .ipv6)) == nil) + #expect(IPFamilyPolicy.conflict(in: a("[2001:db8::1]", .auto)) == nil) + #expect(IPFamilyPolicy.conflict(in: a("pbx.example.com", .ipv4)) == nil) + // The proxy is the first hop: it decides. + #expect(IPFamilyPolicy.conflict(in: a("[2001:db8::1]", .ipv4, proxy: "192.0.2.9")) == nil) + #expect(IPFamilyPolicy.conflict(in: a("192.0.2.1", .ipv4, proxy: "[2001:db8::9]")) == .ipv6) + } + + /// The decision with a fake resolver: literals pick their family, IPv4/IPv6 only pick theirs, Auto + /// with a host name takes the first resolved family that has a transport, IPv4 when nothing resolves, + /// IPv4 without asking when DNS SRV is in effect and the host has no port, and no lookup at all when + /// only one family has a transport. + @Test func familyDecision() { + let both: Set = [.ipv4, .ipv6] + let asked = OSAllocatedUnfairLock(initialState: [String]()) + func decide(_ a: AccountConfig, _ answer: [IPFamily], available: Set = both, srv: Bool = false) -> IPFamily { + IPFamilyPolicy.decide(a, available: available, srv: srv) { host in + asked.withLock { $0.append(host) } + return answer + } + } + func a(_ server: String, _ p: IPProtocol = .auto, registrar: String? = nil, proxy: String? = nil) -> AccountConfig { + AccountConfig(displayName: "", username: "1", domain: server, registrar: registrar, outboundProxy: proxy, ipProtocol: p) + } + #expect(decide(a("[2001:db8::1]"), [.ipv4]) == .ipv6) + #expect(decide(a("192.0.2.1"), [.ipv6]) == .ipv4) + #expect(asked.withLock { $0 }.isEmpty) + #expect(decide(a("pbx.example.com", .ipv6), [.ipv4]) == .ipv6) + #expect(decide(a("pbx.example.com", .ipv4), [.ipv6]) == .ipv4) + #expect(asked.withLock { $0 }.isEmpty) + + #expect(decide(a("pbx.example.com"), [.ipv6, .ipv4]) == .ipv6) + #expect(decide(a("pbx.example.com"), [.ipv4, .ipv6]) == .ipv4) + #expect(decide(a("pbx.example.com"), [.ipv6]) == .ipv6) + #expect(decide(a("pbx.example.com"), []) == .ipv4) // offline: IPv4 + #expect(decide(a("pbx.example.com"), [.ipv6, .ipv4], available: [.ipv4, .ipv6]) == .ipv6) + #expect(decide(a("d", registrar: "reg.example.com:5070"), [.ipv6]) == .ipv6) + #expect(asked.withLock { $0 } == ["pbx.example.com", "pbx.example.com", "pbx.example.com", "pbx.example.com", + "pbx.example.com", "reg.example.com"]) + + asked.withLock { $0 = [] } + // No IPv6 transport for this account: IPv4 without asking (and the other way round). + #expect(decide(a("pbx.example.com"), [.ipv6, .ipv4], available: [.ipv4]) == .ipv4) + #expect(decide(a("pbx.example.com"), [.ipv4, .ipv6], available: [.ipv6]) == .ipv6) + // DNS SRV in effect, no port: getaddrinfo cannot follow SRV, so IPv4; with a port the host is asked. + #expect(decide(a("pbx.example.com"), [.ipv6], srv: true) == .ipv4) + #expect(asked.withLock { $0 }.isEmpty) + #expect(decide(a("pbx.example.com:5060"), [.ipv6], srv: true) == .ipv6) + #expect(asked.withLock { $0 } == ["pbx.example.com"]) + // The proxy is the first hop. + #expect(decide(a("[2001:db8::1]", proxy: "sip:edge.example.com;lr"), [.ipv4]) == .ipv4) + + #expect(IPFamilyPolicy.followsResolver(a("pbx.example.com"), srv: false)) + #expect(!IPFamilyPolicy.followsResolver(a("pbx.example.com"), srv: true)) + #expect(IPFamilyPolicy.followsResolver(a("pbx.example.com:5060"), srv: true)) + #expect(!IPFamilyPolicy.followsResolver(a("pbx.example.com", .ipv6), srv: false)) + #expect(!IPFamilyPolicy.followsResolver(a("[::1]"), srv: false)) + } + + /// The system resolver lists the families getaddrinfo returns, in its order, without duplicates. + @Test func systemResolverFollowsGetaddrinfo() { + let families = IPFamilyResolver.system("localhost") + #expect(families.first == systemFirstFamily("localhost")) + #expect(Set(families).count == families.count) + #expect(IPFamilyResolver.system("::1") == [.ipv6]) + #expect(IPFamilyResolver.system("127.0.0.1") == [.ipv4]) + } + + /// An IPv6 account is bound to the IPv6 twin of its transport, offers IPv6 media only and uses no + /// STUN (SDP from the registrar's view); an IPv4 account keeps pjsua's media default and STUN. A bind + /// address of the other family is not given to RTP. + @Test func mappingByFamily() throws { + let ids = TransportIDs(udp: 0, tcp: 1, tls: 2, tlsNoVerify: 3, udp6: 4, tcp6: 5, tls6: 6, tls6NoVerify: 7) + func map(_ a: AccountConfig, _ family: IPFamily, bind: String? = nil) throws -> [PJAccountSettings] { + let s = try AccountMapping.settings(for: a, password: "pw", network: .default, transports: ids, + bindAddress: bind, family: family) + return [s, AccountMapping.withPJConfig(s) { AccountMapping.readBack($0) }] + } + let host = AccountConfig(displayName: "", username: "1", domain: "pbx.example.com") + for x in try map(host, .ipv6, bind: "::1") { + #expect(x.transportID == 4 && x.mediaIPv6Only) + #expect(!x.sipSTUN && !x.mediaSTUN && x.sdpNATRewrite) + #expect(x.bindAddress == "::1") + } + for x in try map(host, .ipv4, bind: "::1") { + #expect(x.transportID == 0 && !x.mediaIPv6Only && x.sipSTUN && x.mediaSTUN && !x.sdpNATRewrite) + #expect(x.bindAddress == nil) // the bind address is IPv6 + } + #expect(try map(host, .ipv6, bind: "127.0.0.1").allSatisfy { $0.bindAddress == nil }) + var tcp = host; tcp.transport = .tcp + #expect(try map(tcp, .ipv6).allSatisfy { $0.transportID == 5 }) + var tls = host; tls.transport = .tls + #expect(try map(tls, .ipv6).allSatisfy { $0.transportID == 6 }) + tls.verifyTLSCertificate = false + #expect(try map(tls, .ipv6).allSatisfy { $0.transportID == 7 }) + // A private IPv6 server is bound to UDP6, with or without a STUN server (no STUN either way). + let priv = AccountConfig(displayName: "", username: "1", domain: "[fd00::5]") + for network in [NetworkSettings.default, NetworkSettings(stunServer: nil)] { + let s = try AccountMapping.settings(for: priv, password: "", network: network, transports: ids, family: .ipv6) + #expect(s.transportID == 4 && !s.sipSTUN && !s.mediaSTUN) + } + // No IPv6 twin: the account cannot be added. + #expect(throws: EngineError.transportUnavailable(.udp, ipv6: true)) { + _ = try AccountMapping.settings(for: host, password: "", network: .default, + transports: TransportIDs(udp: 0), family: .ipv6) + } + #expect(EngineError.transportUnavailable(.tcp, ipv6: true).description.contains("IPv6")) + } + + @Test func transportIDsByFamily() { + let ids = TransportIDs(udp: 0, tcp: 1, tls: 2, tlsNoVerify: 3, udp6: 4, tcp6: nil, tls6: 6, tls6NoVerify: 7) + let a = AccountConfig(displayName: "", username: "1", domain: "d", transport: .tcp) + #expect(ids.id(for: a, family: .ipv4) == 1 && ids.id(for: a, family: .ipv6) == nil) + #expect(ids.families(for: a) == [.ipv4]) + #expect(ids.id(for: .udp, family: .ipv6) == 4 && ids.id(for: .tls, family: .ipv6) == 6) + #expect(ids.families(for: AccountConfig(displayName: "", username: "1", domain: "d")) == [.ipv4, .ipv6]) + } + + /// The registrar-source trust compares IPv6 addresses in any spelling. + @Test func registrarSourceComparesIPv6Forms() { + let registrar = SignallingSource(address: "2001:db8::1", port: 5060, transport: .udp) + #expect(SignallingSource(address: "[2001:DB8:0::1]", port: 5060, transport: .udp).isSamePeer(as: registrar)) + #expect(!SignallingSource(address: "2001:db8::2", port: 5060, transport: .udp).isSamePeer(as: registrar)) + #expect(SignallingSource.proxy("sip:[2001:db8::1]:5070;lr", transport: .udp) + == SignallingSource(address: "2001:db8::1", port: 5070, transport: .udp)) + #expect(registrar.description == "[2001:db8::1]:5060/udp") + } + + /// The primary route includes the IPv6 source address: a new temporary address is a change. + @Test func networkPathComparesIPv6Address() { + let a = NetworkPath(satisfied: true, interface: "en0", address: "192.0.2.10", address6: "2001:db8::10", gateway: "192.0.2.1") + var b = a + b.address6 = "2001:db8::11" + #expect(b.primaryDiffers(from: a) && b.routeDiffers(from: a)) + #expect(!a.primaryDiffers(from: a)) + // Without accounts on IPv6 a new IPv6 address is no change. + #expect(!b.primaryDiffers(from: a, ipv6: false) && !b.routeDiffers(from: a, ipv6: false)) + var c = b + c.address = "192.0.2.11" + #expect(c.primaryDiffers(from: a, ipv6: false)) + #expect(a.summary.contains("2001:db8::10")) + #expect(NetworkPath.isUsableIPv6Source("2001:db8::10")) + #expect(!NetworkPath.isUsableIPv6Source("fe80::1") && !NetworkPath.isUsableIPv6Source("::1") + && !NetworkPath.isUsableIPv6Source("::")) + } +} + +// MARK: - pjsua tests (part of the serialized "Engine (pjsua)" suite) + +extension EngineTests { + /// An account at [::1] that does not register. + func localIPv6Account(_ user: String) -> AccountConfig { + AccountConfig(displayName: "V6 \(user)", username: user, domain: "[::1]", registerWithServer: false, mwi: false) + } + + /// Bind address rules: an IPv6 bind address creates the IPv6 transports only (UDP6 required), an + /// IPv4 one the IPv4 transports only, none both; an account of a family without transports is refused. + @Test func bindAddressDecidesTransportFamilies() async throws { + for bind in ["::1", "[::1]"] { + let engine = await makeEngine(bindAddress: bind) + try await engine.start(network: Self.network) + let ids = await engine.transportIDsForTests() + #expect(ids.udp == nil && ids.tcp == nil && ids.tls == nil && ids.tlsNoVerify == nil, "\(ids)") + #expect(ids.udp6 != nil && ids.tcp6 != nil && ids.tls6 != nil && ids.tls6NoVerify != nil, "\(ids)") + #expect(await engine.localPort(of: .udp) == 0) + #expect(await engine.localPort(of: .udp, family: .ipv6) > 0) + #expect(await engine.localPort(of: .tls, family: .ipv6) > 0) + let v4 = AccountConfig(displayName: "4", username: "1", domain: "127.0.0.1", enabled: false) + await #expect(throws: EngineError.transportUnavailable(.udp)) { try await engine.addAccount(v4, password: "") } + try await engine.addAccount(localIPv6Account("6"), password: "") + await engine.stop() + } + + let v4only = await makeEngine(bindAddress: "127.0.0.1") + try await v4only.start(network: Self.network) + let ids = await v4only.transportIDsForTests() + #expect(ids.udp != nil && ids.udp6 == nil && ids.tcp6 == nil && ids.tls6 == nil && ids.tls6NoVerify == nil, "\(ids)") + await #expect(throws: EngineError.transportUnavailable(.udp, ipv6: true)) { + try await v4only.addAccount(self.localIPv6Account("6"), password: "") + } + // A host name with no IPv6 transport takes IPv4 without a lookup. + let named = AccountConfig(displayName: "N", username: "1", domain: "localhost", enabled: false) + try await v4only.addAccount(named, password: "") + #expect(await v4only.accountFamilyForTests(named.id) == .ipv4) + await v4only.stop() + + let all = await makeEngine(bindAddress: nil) + try await all.start(network: Self.network) + let both = await all.transportIDsForTests() + #expect(both.udp != nil && both.tcp != nil && both.tls != nil && both.tlsNoVerify != nil, "\(both)") + #expect(both.udp6 != nil && both.tcp6 != nil && both.tls6 != nil && both.tls6NoVerify != nil, "\(both)") + await all.stop() + } + + /// Both families use the configured local port (pjlib sets IPV6_V6ONLY, so [::]:P and 0.0.0.0:P + /// coexist). When the IPv6 UDP port is taken, the engine still starts: IPv4 works, IPv6 accounts of + /// that transport are refused. + @Test func ipv6TransportFailureIsNotFatal() async throws { + // A free port P on both families, then [::]:P held by another socket. + var blocker: Int32 = -1 + var port: UInt16 = 0 + for _ in 0..<20 { + let fd = socket(AF_INET6, SOCK_DGRAM, 0) + var one: Int32 = 1 + setsockopt(fd, IPPROTO_IPV6, IPV6_V6ONLY, &one, socklen_t(MemoryLayout.size)) + var addr = sockaddr_in6() + addr.sin6_len = UInt8(MemoryLayout.size) + addr.sin6_family = sa_family_t(AF_INET6) + addr.sin6_addr = in6addr_any + var len = socklen_t(MemoryLayout.size) + let bound = withUnsafeMutablePointer(to: &addr) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(fd, $0, len) == 0 && getsockname(fd, $0, &len) == 0 } + } + let candidate = UInt16(bigEndian: addr.sin6_port) + // The same port must be free for IPv4 UDP and for TCP on both families. + let probes = [(AF_INET, SOCK_DGRAM), (AF_INET, SOCK_STREAM), (AF_INET6, SOCK_STREAM)].allSatisfy { af, type in + let p = socket(af, type, 0) + defer { close(p) } + var storage = sockaddr_storage() + let size: Int + if af == AF_INET6 { + size = MemoryLayout.size + withUnsafeMutablePointer(to: &storage) { $0.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) { + $0.pointee.sin6_len = UInt8(size); $0.pointee.sin6_family = sa_family_t(AF_INET6) + $0.pointee.sin6_port = in_port_t(candidate.bigEndian); $0.pointee.sin6_addr = in6addr_any + } } + setsockopt(p, IPPROTO_IPV6, IPV6_V6ONLY, &one, socklen_t(MemoryLayout.size)) + } else { + size = MemoryLayout.size + withUnsafeMutablePointer(to: &storage) { $0.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { + $0.pointee.sin_len = UInt8(size); $0.pointee.sin_family = sa_family_t(AF_INET) + $0.pointee.sin_port = in_port_t(candidate.bigEndian) + } } + } + return withUnsafePointer(to: &storage) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(p, $0, socklen_t(size)) == 0 } } + } + if bound && probes { blocker = fd; port = candidate; break } + close(fd) + } + #expect(blocker >= 0) + var net = Self.network + net.localPort = port + let engine = await makeEngine(bindAddress: nil) + try await engine.start(network: net) + var ids = await engine.transportIDsForTests() + #expect(ids.udp != nil && ids.udp6 == nil && ids.tcp6 != nil, "\(ids)") + #expect(await engine.localPort(of: .udp) == Int(port)) + #expect(await engine.localPort(of: .tcp, family: .ipv6) == Int(port)) + await #expect(throws: EngineError.transportUnavailable(.udp, ipv6: true)) { + try await engine.addAccount(self.localIPv6Account("6"), password: "") + } + await engine.stop() + + close(blocker) + try await engine.start(network: net) + ids = await engine.transportIDsForTests() + #expect(ids.udp != nil && ids.udp6 != nil, "\(ids)") + #expect(await engine.localPort(of: .udp) == Int(port)) + #expect(await engine.localPort(of: .udp, family: .ipv6) == Int(port)) + await engine.stop() + } + + /// IPv4 only with an IPv6 server address (and the other way round) is refused, not retried forever. + @Test func contradictoryIPProtocolIsRefused() async throws { + let engine = await makeEngine(bindAddress: nil) + try await engine.start(network: Self.network) + let a = AccountConfig(displayName: "X", username: "1", domain: "[::1]", enabled: false, ipProtocol: .ipv4) + await #expect(throws: EngineError.self) { try await engine.addAccount(a, password: "") } + var b = a + b.domain = "127.0.0.1" + b.ipProtocol = .ipv6 + await #expect(throws: EngineError.self) { try await engine.addAccount(b, password: "") } + b.ipProtocol = .auto + try await engine.addAccount(b, password: "") + b.domain = "[::1]" + b.ipProtocol = .ipv4 + await #expect(throws: EngineError.self) { try await engine.updateAccount(b, password: nil) } + await engine.stop() + } + + /// An account at [::1] registers over UDP6: Via and Contact carry [::1], the live pjsua_acc_config + /// has the UDP6 transport, IPv6-only media, no STUN. A MESSAGE from it goes out over UDP6. + @Test func ipv6AccountRegistersOverUDP6() async throws { + let stub = try IPv6Stub() + defer { stub.stop() } + let engine = await makeEngine(bindAddress: "::1") + let log = EventLog() + let consumer = log.consume(engine) + defer { consumer.cancel() } + try await engine.start(network: Self.network) + let port6 = await engine.localPort(of: .udp, family: .ipv6) + let account = AccountConfig(displayName: "R6", username: "1006", domain: "[::1]", + registrar: "[::1]:\(stub.port)", mwi: false) + try await engine.addAccount(account, password: "pw") + #expect(await waitUntil { await engine.registrationState(of: account.id).isRegistered }) + let register = try #require(stub.registers.first) + #expect(register.family == .ipv6 && register.transport == "UDP") + #expect(register.via.hasPrefix("SIP/2.0/UDP [::1]:\(port6)"), "\(register.via)") + #expect(register.contact.contains("sip:1006@[::1]:\(port6)"), "\(register.contact)") + + let ids = await engine.transportIDsForTests() + let live = try #require(await engine.liveAccountSettingsForTests(account.id)) + #expect(live.transportID == ids.udp6) + #expect(live.mediaIPv6Only && !live.sipSTUN && !live.mediaSTUN) + #expect(live.bindAddress == "::1") + #expect(await engine.accountFamilyForTests(account.id) == .ipv6) + + let id = try await engine.sendMessage("hello over IPv6", to: DialString(uri: "sip:300@[::1]:\(stub.port)", display: "300"), + from: account.id) + #expect(await waitUntil { log.messageStatuses(id) == [.accepted(code: 200)] }) + let message = try #require(stub.requests.first { $0.method == "MESSAGE" }) + #expect(message.family == .ipv6 && message.body == "hello over IPv6") + await engine.stop() + } + + /// The same over TCP6: the stub's TCP listener on [::1] receives the REGISTER. + @Test func ipv6AccountRegistersOverTCP6() async throws { + let stub = try IPv6Stub() + defer { stub.stop() } + let engine = await makeEngine(bindAddress: "::1") + try await engine.start(network: Self.network) + let account = AccountConfig(displayName: "T6", username: "1007", domain: "[::1]", + registrar: "[::1]:\(stub.tcpPort)", transport: .tcp, mwi: false) + try await engine.addAccount(account, password: "pw") + #expect(await waitUntil { await engine.registrationState(of: account.id).isRegistered }) + let register = try #require(stub.registers.first) + #expect(register.family == .ipv6 && register.transport == "TCP") + #expect(register.via.hasPrefix("SIP/2.0/TCP [::1]:"), "\(register.via)") + #expect(register.contact.contains("@[::1]:") && register.contact.lowercased().contains("transport=tcp"), + "\(register.contact)") + let ids = await engine.transportIDsForTests() + #expect(await engine.liveAccountSettingsForTests(account.id)?.transportID == ids.tcp6) + await engine.stop() + } + + /// An outgoing call of an IPv6 account offers `c=IN IP6` and its RTP socket is IPv6; a call to + /// ourselves over [::1] reaches the account, is answered with IPv6 and carries RTP both ways. + @Test func ipv6CallOffersIPv6MediaAndCarriesRTP() async throws { + let stub = try IPv6Stub() + defer { stub.stop() } + let engine = await makeEngine(bindAddress: "::1") + let log = EventLog() + let consumer = log.consume(engine) + defer { consumer.cancel() } + try await engine.start(network: Self.network) + let account = localIPv6Account("loop") + try await engine.addAccount(account, password: "") + let port6 = await engine.localPort(of: .udp, family: .ipv6) + + let call = try await engine.makeCall(to: DialString(uri: "sip:300@[::1]:\(stub.port)", display: "300"), from: account.id) + #expect(await waitUntil { await engine.calls().first { $0.id == call }?.state == .connected }) + let invite = try #require(stub.requests.first { $0.method == "INVITE" }) + #expect(invite.family == .ipv6 && sdpConnection(invite.body) == "IN IP6 ::1", "\(invite.body)") + #expect(await engine.localRTPAddress(of: call) == "::1") + try await engine.hangup(call) + #expect(await waitUntil { await engine.calls().isEmpty }) + + let before = log.all.count + let out = try await engine.makeCall(to: DialString(uri: "sip:loop@[::1]:\(port6)", display: "loop"), from: account.id) + func incoming() -> CallInfo? { + log.all.dropFirst(before).lazy.compactMap { if case let .incomingCall(c) = $0 { return c }; return nil }.first + } + #expect(await waitUntil { incoming() != nil }) + let inc = try #require(incoming()) + #expect(inc.accountID == account.id) + try await engine.answer(inc.id) + #expect(await waitUntil { + let calls = await engine.calls() + return calls.count == 2 && calls.allSatisfy { $0.state == .connected && $0.codec != nil } + }) + #expect(await engine.localRTPAddress(of: out) == "::1") + #expect(await engine.localRTPAddress(of: inc.id) == "::1") + #expect(await waitUntil { + let a = try? await engine.mediaStats(out), b = try? await engine.mediaStats(inc.id) + return (a?.rxPackets ?? 0) > 10 && (a?.txPackets ?? 0) > 10 && (b?.rxPackets ?? 0) > 10 + }) + try await engine.hangup(out) + #expect(await waitUntil { await engine.calls().isEmpty }) + await engine.stop() + } + + /// Incoming requests over IPv6 reach the account bound to the IPv6 transport, those over IPv4 the + /// IPv4 one (two accounts with the same user and domain). Every offer is answered in its own family: + /// `IN IP6` to the IPv6 account with IPv6, `IN IP4` to the IPv6 account with IPv4, and `IN IP6` to + /// the IPv4 account with IPv6 (pjsua's default for IPv4 accounts, as before). A MESSAGE over UDP6 + /// reaches the IPv6 account. + @Test func incomingOverIPv6ReachesTheIPv6Account() async throws { + let stub = try IPv6Stub(dualStack: true) + defer { stub.stop() } + let engine = await makeEngine(bindAddress: nil) + let log = EventLog() + let consumer = log.consume(engine) + defer { consumer.cancel() } + try await engine.start(network: Self.network) + let a4 = AccountConfig(displayName: "A4", username: "100", domain: "pbx.test", registerWithServer: false, + mwi: false, ipProtocol: .ipv4) + var a6 = a4 + a6.id = AccountID() + a6.displayName = "A6" + a6.ipProtocol = .ipv6 + try await engine.addAccount(a4, password: "") + try await engine.addAccount(a6, password: "") + let port4 = await engine.localPort(of: .udp) + let port6 = await engine.localPort(of: .udp, family: .ipv6) + func incoming(after count: Int) -> CallInfo? { + log.all.dropFirst(count).lazy.compactMap { if case let .incomingCall(c) = $0 { return c }; return nil }.first + } + + for (family, port, ipv4Offer, expected, answer) in [ + (IPFamily.ipv6, port6, false, a6.id, "IN IP6"), (.ipv4, port4, false, a4.id, "IN IP6"), + (.ipv6, port6, true, a6.id, "IN IP4"), + ] { + let mark = log.all.count + let callID = stub.sendInvite(toPort: port, user: "100", family: family, ipv4Offer: ipv4Offer) + #expect(await waitUntil { incoming(after: mark) != nil }) + let call = try #require(incoming(after: mark)) + #expect(call.accountID == expected, "\(family) offer \(ipv4Offer ? "IP4" : "IP6")") + try await engine.answer(call.id) + #expect(await waitUntil { stub.responses(to: callID).contains { $0.status.hasPrefix("SIP/2.0 200") } }) + let ok = try #require(stub.responses(to: callID).first { $0.status.hasPrefix("SIP/2.0 200") }) + #expect(sdpConnection(ok.body).hasPrefix(answer), "answer \(ok.body)") + #expect(await waitUntil { await engine.calls().isEmpty }) + } + + let messageID = stub.sendMessage(toPort: port6, user: "100", text: "over IPv6") + #expect(await waitUntil { !log.receivedMessages.isEmpty }) + #expect(log.receivedMessages.first?.accountID == a6.id) + #expect(log.receivedMessages.first?.text == "over IPv6") + #expect(await waitUntil { stub.responses(to: messageID).contains { $0.status.hasPrefix("SIP/2.0 200") } }) + await engine.stop() + } + + /// Auto with a host name follows the first address getaddrinfo returns ("localhost": usually ::1); + /// IPv4 only and IPv6 only keep their family. The stub listens on both families with one port. + @Test func autoFollowsSystemResolverForHostNames() async throws { + let expected = try #require(systemFirstFamily("localhost")) + for (choice, family) in [(IPProtocol.auto, expected), (.ipv4, .ipv4), (.ipv6, .ipv6)] { + let stub = try IPv6Stub(dualStack: true) + defer { stub.stop() } + let engine = await makeEngine(bindAddress: nil) + try await engine.start(network: Self.network) + let account = AccountConfig(displayName: "L", username: "1008", domain: "localhost", + registrar: "localhost:\(stub.port)", mwi: false, ipProtocol: choice) + try await engine.addAccount(account, password: "pw") + #expect(await waitUntil { await engine.registrationState(of: account.id).isRegistered }, "\(choice)") + #expect(await engine.accountFamilyForTests(account.id) == family, "\(choice)") + #expect(stub.registers.first?.family == family, "\(choice): \(stub.registers.map(\.family))") + #expect(stub.registers.first?.via.contains("[") == (family == .ipv6), "\(stub.registers.first?.via ?? "")") + await engine.stop() + } + } + + /// The family of an Auto host name is decided again on a network change and before a REGISTER retry; + /// when it changed the account is moved to the other transport and registers there. + @Test func familyIsDecidedAgainOnNetworkChangeAndRetry() async throws { + let stub = try IPv6Stub(dualStack: true) + defer { stub.stop() } + let answer = OSAllocatedUnfairLock(initialState: [IPFamily.ipv4, .ipv6]) + let engine = await makeEngine(bindAddress: nil) + await engine.setTestTimings(transactionTimeoutMs: 2000) + await engine.setFamilyResolverForTests { _ in answer.withLock { $0 } } + try await engine.start(network: Self.network) + let ids = await engine.transportIDsForTests() + let account = AccountConfig(displayName: "L", username: "1009", domain: "localhost", + registrar: "localhost:\(stub.port)", mwi: false) + try await engine.addAccount(account, password: "pw") + #expect(await waitUntil { await engine.registrationState(of: account.id).isRegistered }) + #expect(stub.registers.last?.family == .ipv4) + + // Network change: the resolver now puts IPv6 first. + answer.withLock { $0 = [.ipv6, .ipv4] } + await engine.simulateNetworkChange() + #expect(await waitUntil { stub.registers.last?.family == .ipv6 }) + #expect(await waitUntil { await engine.registrationState(of: account.id).isRegistered }) + #expect(await engine.liveAccountSettingsForTests(account.id)?.transportID == ids.udp6) + + // IPv6 stops answering; the retry after the timeout finds IPv4 first again. + stub.silentFamilies = [.ipv6] + let count = stub.registers.count + try await engine.setRegistered(account.id, true) + #expect(await waitUntil(timeout: 6) { + if case .reconnecting = await engine.registrationState(of: account.id) { return true } + return false + }) + answer.withLock { $0 = [.ipv4, .ipv6] } + #expect(await waitUntil(timeout: 8) { await engine.registrationState(of: account.id).isRegistered }) + #expect(stub.registers.dropFirst(count).last?.family == .ipv4) + #expect(await engine.liveAccountSettingsForTests(account.id)?.transportID == ids.udp) + await engine.stop() + } + + /// A new IPv6 source address (a new temporary address) starts a round only when it matters: IPv6 + /// appearing does, a later new address does not while no account uses IPv6, and does once one does. + @Test func newIPv6AddressStartsRoundOnlyForIPv6Accounts() async throws { + let engine = await makeEngine(bindAddress: nil) + try await engine.start(network: Self.network) + func path(_ v6: String) -> NetworkPath { + NetworkPath(satisfied: true, interface: "en0", address: "192.168.1.20", address6: v6, gateway: "192.168.1.1") + } + func settle() async { _ = await waitUntil { await engine.ipChangeStateForTests().running == nil } } + await engine.applyPathForTests(path("")) // a new primary route + await settle() + var rounds = await engine.ipChangeStateForTests().rounds + await engine.applyPathForTests(path("2001:db8::10")) // IPv6 appeared + await settle() + #expect(await engine.ipChangeStateForTests().rounds == rounds + 1) + rounds += 1 + await engine.applyPathForTests(path("2001:db8::11")) // rotated; no IPv6 account + await settle() + #expect(await engine.ipChangeStateForTests().rounds == rounds) + try await engine.addAccount(localIPv6Account("6"), password: "") + await engine.applyPathForTests(path("2001:db8::12")) + await settle() + #expect(await engine.ipChangeStateForTests().rounds == rounds + 1) + await engine.stop() + } + + /// A network change with the engine on all interfaces restarts the IPv6 listeners too; the IPv6 + /// account registers again over UDP6. + @Test func networkChangeRestartsIPv6Listeners() async throws { + let stub = try IPv6Stub() + defer { stub.stop() } + let engine = await makeEngine(bindAddress: nil) + let log = EventLog() + let consumer = log.consume(engine) + defer { consumer.cancel() } + try await engine.start(network: Self.network) + let account = AccountConfig(displayName: "R6", username: "1010", domain: "[::1]", + registrar: "[::1]:\(stub.port)", mwi: false) + try await engine.addAccount(account, password: "pw") + #expect(await waitUntil { await engine.registrationState(of: account.id).isRegistered }) + let ids = await engine.transportIDsForTests() + let count = stub.registers.count + await engine.simulateNetworkChange() + #expect(await waitUntil { stub.registers.count > count }) + #expect(await waitUntil { await engine.ipChangeStateForTests().running == nil }) + #expect(stub.registers.last?.family == .ipv6) + let restarted = log.all.compactMap { e -> String? in + if case let .log(_, t) = e, t.contains("listener"), t.contains("restarted") { return t } + return nil + } + for id in [ids.udp6, ids.tcp6, ids.tls6, ids.tls6NoVerify].compactMap({ $0 }) { + #expect(restarted.contains { $0.contains("listener \(id) restarted (ok)") }, "\(restarted)") + } + #expect(await engine.registrationState(of: account.id).isRegistered) + await engine.stop() + } + + /// ICE is not used over IPv6 (docs/ENGINE.md "IPv6": PJSIP 2.17 cannot open the IPv6 ICE socket on + /// macOS, and an offer with IPv4 candidates only fails on an IPv6 answer). With ICE on, an IPv6 + /// account offers plain IPv6 media without candidates and the call connects; an IPv4 account on + /// the same engine still offers ICE candidates. + @Test func iceIsNotUsedOverIPv6() async throws { + let stub = try IPv6Stub() + defer { stub.stop() } + let engine = await makeEngine(bindAddress: "::1") + var net = Self.network + net.useICE = true + try await engine.start(network: net) + let account = localIPv6Account("ice") + try await engine.addAccount(account, password: "") + let live = try #require(await engine.liveAccountSettingsForTests(account.id)) + #expect(!live.iceEnabled && live.mediaIPv6Only) + let call = try await engine.makeCall(to: DialString(uri: "sip:300@[::1]:\(stub.port)", display: "300"), from: account.id) + #expect(await waitUntil { await engine.calls().first { $0.id == call }?.state == .connected }) + let offer = try #require(stub.requests.first { $0.method == "INVITE" }).body + #expect(sdpConnection(offer) == "IN IP6 ::1", "\(offer)") + #expect(!offer.contains("a=candidate:"), "\(offer)") + try await engine.hangup(call) + #expect(await waitUntil { await engine.calls().isEmpty }) + let mapped = try AccountMapping.settings(for: AccountConfig(displayName: "", username: "1", domain: "pbx.example.com"), + password: "", network: net, transports: TransportIDs(udp: 0), family: .ipv4) + #expect(mapped.iceEnabled) + await engine.stop() + } +} diff --git a/docs/ENGINE.md b/docs/ENGINE.md index de5917f..a6d25be 100644 --- a/docs/ENGINE.md +++ b/docs/ENGINE.md @@ -14,6 +14,8 @@ The engine is the only code that talks to PJSIP. The UI never imports `CPJSUA`. public struct AccountID: Hashable, Codable { let raw: UUID } public enum TransportKind: String, Codable { case udp, tcp, tls } public enum SRTPMode: String, Codable { case disabled, optional, mandatory } +public enum IPProtocol: String, Codable { case auto, ipv4, ipv6 } // per account; unknown values decode as .auto (see "IPv6") +public enum IPFamily: String { case ipv4, ipv6 } // what the engine decided for an account public struct AccountConfig: Codable, Identifiable, Equatable { public var id: AccountID @@ -32,6 +34,7 @@ public struct AccountConfig: Codable, Identifiable, Equatable { public var publishPresence: Bool public var mwi: Bool // true: subscribe to the voicemail indicator (RFC 3842); see "Voicemail indicator" public var voicemailNumber: String? // what the UI dials to listen to voicemail; nil = not set + public var ipProtocol: IPProtocol // .auto; missing in older files = .auto (see "IPv6") // password is NOT here; it lives in Keychain under id } @@ -186,6 +189,9 @@ public actor Engine { public func networkState() -> NetworkState public func applyNetworkSettings(_ s: NetworkSettings) throws -> NetworkApplyResult public func localRTPPort(of id: CallID) -> Int // diagnostics + public func localRTPAddress(of id: CallID) -> String // diagnostics ("::1", "192.0.2.10") + public func localPort(of kind: TransportKind) -> Int // IPv4 transport, 0 = none + public func localPort(of kind: TransportKind, family: IPFamily) -> Int // per family (see "IPv6") public func handleWake() // NSWorkspace.didWakeNotification public func handleSleep() // NSWorkspace.willSleepNotification public func simulateNetworkChange() // test hook (self-test) @@ -252,7 +258,7 @@ Code: `Sources/MacroSIPCore/Engine/` (Engine, EngineBridge, EngineTypes, Account - **Executor and threads.** `Engine.unownedExecutor` is a `DispatchSerialQueue("macrosip.engine")`. GCD may run it on different pool threads, so every entry point calls `cpjsua_thread_register()` (C11 `_Thread_local pj_thread_desc`, no-op once registered, re-registers after a pjsua restart). - **Callback bridge.** pjsua callbacks are C function pointers without context, so they are global Swift functions that reach the engine through `EngineBridge.shared` (a `Sendable` class over `OSAllocatedUnfairLock`; no `nonisolated(unsafe)`). A callback reads PJSIP data, updates the registry, yields the event and, when the engine must act (conference wiring, ringtone, hang-up after transfer), schedules `Task { await engine.… }`. Follow-up work is idempotent (reconcile current state), so its ordering does not matter. - **Events.** Single consumer. They are yielded from PJSIP threads and the actor, so the UI iterates on `@MainActor`. `CallID` is `(raw: pjsua slot, serial)`: slots are reused, serials never are, and a stale `CallID` throws `.noSuchCall`. Upsert UI rows on `.incomingCall`/`.callChanged` (the first `.callChanged` of an outgoing call can arrive before `makeCall` returns) and remove them on `.callEnded`. A fifth incoming call gets 486 and appears only as `.callEnded(... .disconnected(code: 486 ...))`. Incoming calls stay `.incoming` while ringing (pjsua state EARLY after the automatic 180). `.callEnded` repeats the last codec/SRTP state and `duration` is the connected time (0 if never answered). `CallState.held` means local hold (`isOnHold`); remote hold stays `.connected`. -- **Deviations / additions.** `CallID` gained `serial`. `CallDirection` is the call-log enum from `Model/CallLogEntry.swift` (it also has `missed`, never produced by the engine). `Engine.init` takes `nullAudio` and `bindAddress` (bind SIP and RTP to one address; needed for localhost calls when the default route is a VPN). Additive API: `mediaStats(_:)`, `localPort(of:)`, `setRingtone(_:)` (built-in melody or WAV; see "Ringtone and ringback"), `previewRingtone(_:volume:)`, `silenceRingtone()`, `inputLevel()`. `EngineError` has more cases than `.pjsip`. Conference, recording and presence members were stubs (`.unsupported`) until milestone 5; see below. +- **Deviations / additions.** `CallID` gained `serial`. `CallDirection` is the call-log enum from `Model/CallLogEntry.swift` (it also has `missed`, never produced by the engine). `Engine.init` takes `nullAudio` and `bindAddress` (bind SIP and RTP to one address; needed for localhost calls when the default route is a VPN; an IPv6 address too since 26.3.1, see "IPv6"). Additive API: `mediaStats(_:)`, `localPort(of:)`, `setRingtone(_:)` (built-in melody or WAV; see "Ringtone and ringback"), `previewRingtone(_:volume:)`, `silenceRingtone()`, `inputLevel()`. `EngineError` has more cases than `.pjsip`. Conference, recording and presence members were stubs (`.unsupported`) until milestone 5; see below. - **PJSIP specifics.** Calls are audio-only with `txt_cnt = 0`; the pjsua default offers an RFC 4103 text m-line that breaks un-hold. RTP ports come from `NetworkSettings.rtpPortStart`/`rtpPortCount` (default 4000-4999), the first pair randomized inside the window. VAD is off. Codec priorities start at 254 because PJSIP demotes 255 and creates a tie; unlisted codecs get 0 (disabled). After a successful transfer (final 2xx NOTIFY) the engine hangs up the transferred leg. `updateAccount` uses `disable_reg_on_modify` and re-registers explicitly. The old binding is not un-REGISTERed when the registrar changes; it expires on the server. - **Review fixes (milestone 2.1).** - TLS: two listeners. The default one verifies the server: the macOS system roots are exported at `start` to `Application Support/MacroSIP/ca-roots.pem` (path injectable) for OpenSSL, and PJSIP sets SNI and checks CN/SAN against the request's destination host. Accounts with `AccountConfig.verifyTLSCertificate == false` (decodes as `true` from older JSON) use the second, non-verifying listener and get a `.log` warning. If the export fails, verification fails closed. @@ -283,8 +289,8 @@ Code: `Engine+Conference.swift` (merge/split and the conference bridge wiring), - **Manual checks** (`macrosip-cli` interactive): `merge`, `split`, `rec [stereo]`, `stoprec`, `sub `, `unsub `, `status `, `acc publish on|off`. ## Implementation notes (milestone 4) -- **"Unsuitable transport selected" on every authorised INVITE (fixed).** Symptom on the owner's account: each INVITE and re-INVITE logged `Temporary failure in sending Request msg INVITE/cseq=N (tdta...), will try next server: Unsuitable transport selected (PJSIP_ETPNOTSUITABLE)` and the next attempt went out. Cause: RFC 3261 18.1.1 in PJSIP (`stateless_send_resolver_callback`, sip_util.c): a request of 1300 bytes or more (`PJSIP_UDP_SIZE_THRESHOLD`) to a UDP destination gets TCP copies of the resolved addresses put in front ("exceeds UDP size threshold (1300), sending with TCP", level 5). Our accounts are bound to their transport (`transport_id`, i.e. a `PJSIP_TPSELECTOR_TRANSPORT` selector on the UDP transport), so `pjsip_tpmgr_acquire_transport2` refuses the TCP entry (sip_transport.c:2540, selector type UDP != TCP), the transaction logs the temporary failure and sends the UDP entry. It is not a resolver or STUN problem: it happens with an IP literal too and was reproduced with an IP target. An INVITE crosses 1300 bytes once it carries a digest `Authorization` header: the first INVITE is answered 401, the authorised retry (cseq N+1) and every re-INVITE (pre-authorised from the cache, `PJSIP_AUTH_AUTO_SEND_NEXT`) are 1370-1400 bytes even on localhost; public addresses from STUN, SRTP crypto lines and longer host names add more. Unregistered localhost calls to pjsua are about 1090 bytes, which is why the first self-test never showed it. Fix: `Engine.start` sets `pjsip_cfg()->endpt.disable_tcp_switch = PJ_TRUE` (Engine.swift, `initPJSUA`). With accounts pinned to a transport the switch could never succeed, so nothing else changes; the request still goes over UDP (it may be IP-fragmented, as before). Since 26.2 it is load-bearing: a UDP account of a private server is not bound while STUN is on ("No STUN for private servers"), and without the flag its requests of 1300 bytes or more would really go over TCP. Proof: self-test step "registered account" (below) failed with exactly the owner's line before the fix; at `SELFTEST_LOG_LEVEL=5` the "exceeds UDP size threshold" and ETPNOTSUITABLE lines are gone after it. -- **Ruled out / remaining.** (1) Resolver: `pj_getaddrinfo` already drops duplicates across socket types; an A-only host name with a port (`127.0.0.1.nip.io:5080`) resolves to one address and sends at once. A host name that also has an AAAA record (`localhost` -> `[::1]`, `127.0.0.1`) still logs the same line once per request: the IPv6 entry comes first and the IPv4 UDP transport the account is bound to does not fit. Harmless (the IPv4 entry follows immediately); the engine creates IPv4 transports only, and pjsua's `ipv6_sip_use` preference (IPv4 first) is ignored when `transport_id` is set. Revisit if an IPv6 transport is added. (2) `transport_id` itself is not the trigger: the selector only made the TCP copy fail; unbinding UDP accounts would have sent large requests over TCP to servers that may not listen on TCP (connection timeouts). Accounts are bound to their transport, except UDP accounts of private IPv4 servers while STUN is on (26.2), which `disable_tcp_switch` keeps on UDP. (3) STUN / `allow_contact_rewrite` / `allow_via_rewrite`: "IP address change detected" only rewrites Contact and the Via sent-by and re-REGISTERs (`acc_check_nat_addr`, pjsua_acc.c); the account keeps the same transport object. Checked with STUN on (`stun.l.google.com:19302`, mapped public address in Contact/SDP): INVITE 1466 and re-INVITE 1523 bytes go straight out over UDP. +- **"Unsuitable transport selected" on every authorised INVITE (fixed).** Symptom on the owner's account: each INVITE and re-INVITE logged `Temporary failure in sending Request msg INVITE/cseq=N (tdta...), will try next server: Unsuitable transport selected (PJSIP_ETPNOTSUITABLE)` and the next attempt went out. Cause: RFC 3261 18.1.1 in PJSIP (`stateless_send_resolver_callback`, sip_util.c): a request of 1300 bytes or more (`PJSIP_UDP_SIZE_THRESHOLD`) to a UDP destination gets TCP copies of the resolved addresses put in front ("exceeds UDP size threshold (1300), sending with TCP", level 5). Our accounts are bound to their transport (`transport_id`, i.e. a `PJSIP_TPSELECTOR_TRANSPORT` selector on the UDP transport), so `pjsip_tpmgr_acquire_transport2` refuses the TCP entry (sip_transport.c:2540, selector type UDP != TCP), the transaction logs the temporary failure and sends the UDP entry. It is not a resolver or STUN problem: it happens with an IP literal too and was reproduced with an IP target. An INVITE crosses 1300 bytes once it carries a digest `Authorization` header: the first INVITE is answered 401, the authorised retry (cseq N+1) and every re-INVITE (pre-authorised from the cache, `PJSIP_AUTH_AUTO_SEND_NEXT`) are 1370-1400 bytes even on localhost; public addresses from STUN, SRTP crypto lines and longer host names add more. Unregistered localhost calls to pjsua are about 1090 bytes, which is why the first self-test never showed it. Fix: `Engine.start` sets `pjsip_cfg()->endpt.disable_tcp_switch = PJ_TRUE` (Engine.swift, `initPJSUA`). With accounts pinned to a transport the switch could never succeed, so nothing else changes; the request still goes over UDP (it may be IP-fragmented, as before). Since 26.2 it is load-bearing: a UDP account of a private IPv4 server is not bound while STUN is on ("No STUN for private servers"), and without the flag its requests of 1300 bytes or more would really go over TCP. Proof: self-test step "registered account" (below) failed with exactly the owner's line before the fix; at `SELFTEST_LOG_LEVEL=5` the "exceeds UDP size threshold" and ETPNOTSUITABLE lines are gone after it. +- **Ruled out / remaining.** (1) Resolver: `pj_getaddrinfo` already drops duplicates across socket types; an A-only host name with a port (`127.0.0.1.nip.io:5080`) resolves to one address and sends at once. A host name that also has an AAAA record (`localhost` -> `[::1]`, `127.0.0.1`) still logs the same line once per request: the IPv6 entry comes first and the IPv4 UDP transport the account is bound to does not fit. Harmless (the IPv4 entry follows immediately); pjsua's `ipv6_sip_use` preference is ignored when `transport_id` is set. Since 26.3.1 an Auto account takes the family `getaddrinfo` returns first and is bound to that family's transport (see "IPv6"), so the line appears only for an account set to the other family (IPv4 only with `localhost`). (2) `transport_id` itself is not the trigger: the selector only made the TCP copy fail; unbinding UDP accounts would have sent large requests over TCP to servers that may not listen on TCP (connection timeouts). Accounts are bound to their transport, except UDP accounts of private IPv4 servers while STUN is on (26.2), which `disable_tcp_switch` keeps on UDP. (3) STUN / `allow_contact_rewrite` / `allow_via_rewrite`: "IP address change detected" only rewrites Contact and the Via sent-by and re-REGISTERs (`acc_check_nat_addr`, pjsua_acc.c); the account keeps the same transport object. Checked with STUN on (`stun.l.google.com:19302`, mapped public address in Contact/SDP): INVITE 1466 and re-INVITE 1523 bytes go straight out over UDP. - **Selftest additions** (`SelfTestCalls.swift`, `SIPStub.swift`; the script starts both pjsua phones with `--id sip:phone1@...` / `sip:phone2@...` and telnet CLIs 5088 / 5089). Incoming call: pjsua #1 dials the engine through its CLI (`call new sip:selftest@127.0.0.1:`), `.incomingCall` must carry number `phone1`, `answer`, 2 s of two-way RTP, `hangup` from the engine, pjsua's `call list` must show 0 active calls (it got the BYE); a second call is `reject(code: 486)`ed (`.callEnded` 486, duration 0, pjsua idle). Blind transfer: call pjsua #1, `blindTransfer` to pjsua #2; final NOTIFY 2xx, our leg is hung up, pjsua #1's `call list` shows a confirmed call to `phone2` and pjsua #2's one from `phone1`. Attended transfer: call #1, hold, call #2, `attendedTransfer(call1, replacing: call2)`; final NOTIFY 2xx, both legs end (the second with pjsua #2's BYE after it accepted the INVITE with Replaces, no extra pjsua flag needed), the phones are in a confirmed call with each other. pjsua has no option to drop telephone-event from its SDP, so DTMF over INFO and the registered account use `SIPStub`, a UDP server in macrosip-cli that challenges REGISTER and INVITE with a res_pjsip-style digest 401 (qop=auth, long nonce, opaque), accepts any `Authorization`, answers PCMU-only SDP without telephone-event and records INFO bodies and INVITE sizes. DTMF: `sendDTMF("5#")` must arrive as two INFOs (`Signal=5`, `Signal=#`). Registered account `sip:100@127.0.0.1:`: REGISTER 401 -> 200, call, hold, resume, hang up; all three authorised INVITEs must be above 1300 bytes and no `.log` line may contain ETPNOTSUITABLE or "will try next server". The script takes `SELFTEST_LOG=` (full output) and `SELFTEST_LOG_LEVEL=`. - **Hold/resume while a re-INVITE is in flight.** PJSIP refuses a second re-INVITE while an INVITE transaction (ours or the remote's) or a media change is pending (`pjsip_inv_reinvite` -> `PJ_EINVALIDOP`, logged by pjsua as "Unable to create re-INVITE"; `PJSIP_EBUSY` / `PJSIP_ESESSIONSTATE` are treated alike). `setHold` on a confirmed call no longer throws then: like a REGISTER in flight, the request is remembered per call in `Engine.pendingHolds` (latest request wins, a `.log` level 4 says "hold/resume waits for the re-INVITE in progress") and `isOnHold` shows it at once. It is sent from `handleMediaStateChanged` / `handleCallStateChanged` (after the pending transaction's media update or a call state change) and by a 250 ms retry timer as a fallback; every request is sent as asked, so hold -> resume -> hold ends held. It is dropped when the call ends, when `merge` resumes the leg, on `stop()`, or after 40 s / a non-busy error (logged; `localHold` then follows the real media state). `.callChanged` follows the media state, so the last one reflects the final state. Errors other than "busy", and busy on a call that is not confirmed, still throw. Test `quickHoldResumeIsDeferredNotLost` (loopback: hold+resume back to back ends connected with RTP; resume+hold ends held, RTP stalls) and self-test step "hold + resume back to back" (against pjsua, RTP from the phone afterwards); the registered-account step also resumes without waiting. - **macrosip-cli:** `--bind any` now also works in interactive mode (all interfaces, the default). @@ -336,9 +342,9 @@ Goal: a network drop, a Wi-Fi -> Ethernet/LTE switch, an IP change or sleep/wake **Ordering.** Path updates go through one `AsyncStream` per `NWPathMonitor` and are applied by one consumer task in order (a Task per update could apply an unsatisfied/satisfied pair at wake reversed and leave the engine offline). Follow-up work from PJSIP callbacks (`EngineBridge.hop`) also runs through one ordered queue (one consumer task per started engine), so for example two final responses of the same call, or a REGISTER result and the end of a network change, are handled in the order PJSIP reported them. -**Path monitoring.** `NWPathMonitor` on its own queue (`macrosip.network`). `.satisfied` = online. A path is reduced to its primary route (`NetworkPath`): the first available interface (the one the system routes through), the source address of the default route (a UDP socket "connected" to 192.0.2.1 and read back with getsockname: the address pjsua's sockets use towards a server on the default route) and the first gateway. Secondary interfaces (bridge100 of Internet Sharing, a split-tunnel utun, a second Wi-Fi) coming and going change nothing; a full-tunnel VPN that takes the default route changes the interface and the address. The first update after `start` and every update while a wake is pending are applied at once; later ones are debounced by 2.5 s (the last one wins). Online -> offline: `.network(.offline)`, calls get `isReconnecting`. Offline -> online: `.network(.online)` and a round; a changed primary route while online: a round. A new local address on the same interface and gateway that produces no path update is not noticed (keep-alives, `allow_contact_rewrite` and the next REGISTER refresh deal with it). If no update arrives within 2 s after start, `.network(.online)` is emitted anyway. A satisfied path without a default route (the 192.0.2.1 lookup fails) keeps the previous address and counts as unchanged (logged). `Engine(monitorNetwork: false)` runs no NWPathMonitor: the network counts as online from `start` (a fixed path is reported at once) and only paths injected by tests change it; the engine tests use it so they do not depend on the host's network. +**Path monitoring.** `NWPathMonitor` on its own queue (`macrosip.network`). `.satisfied` = online. A path is reduced to its primary route (`NetworkPath`): the first available interface (the one the system routes through), the source address of the default route (a UDP socket "connected" to 192.0.2.1 and read back with getsockname: the address pjsua's sockets use towards a server on the default route), the same for the default IPv6 route (2001:db8::1; a global address only, see "IPv6") and the first gateway. Secondary interfaces (bridge100 of Internet Sharing, a split-tunnel utun, a second Wi-Fi) coming and going change nothing; a full-tunnel VPN that takes the default route changes the interface and the address. The first update after `start` and every update while a wake is pending are applied at once; later ones are debounced by 2.5 s (the last one wins). Online -> offline: `.network(.offline)`, calls get `isReconnecting`. Offline -> online: `.network(.online)` and a round; a changed primary route while online: a round. A new local address on the same interface and gateway that produces no path update is not noticed (keep-alives, `allow_contact_rewrite` and the next REGISTER refresh deal with it). If no update arrives within 2 s after start, `.network(.online)` is emitted anyway. A satisfied path without a default route (the 192.0.2.1 lookup fails) keeps the previous address and counts as unchanged (logged); the same per family, so an IPv6-only network keeps the last IPv4 address and an IPv4-only one the last IPv6 address (the line is logged only when both are missing). `Engine(monitorNetwork: false)` runs no NWPathMonitor: the network counts as online from `start` (a fixed path is reported at once) and only paths injected by tests change it; the engine tests use it so they do not depend on the host's network. -**Rounds (`requestIPChange` / `performIPChange`).** One round = one `pjsua_handle_ip_change`. Rounds never overlap: a request while a round runs is queued (the latest reason, flags merged) and started when the round completes. A request is "primary" when the interface or the local address changed (and for `simulateNetworkChange`); otherwise (gateway-only change, network back with the same address, wake with the same address) it is postponed while an outgoing call is still unanswered and runs when no outgoing call rings any more (checked every second, at most 90 s): pjsua hangs up an account's unconfirmed outgoing calls with 410 after that account's re-REGISTER (`pjsua_acc_handle_call_on_ip_change`; test `ringingCallOfReRegisteringAccountEndsOnAddressChange`), which is accepted only when the address really changed (such a call cannot complete then anyway). Steps: (1) every confirmed call gets `reinviteWanted = round` (`isReconnecting`). (2) `cpjsua_acc_prepare_ip_change` per account decides whether pjsua re-REGISTERs it: pjsua's `handle_ip_change_on_acc` re-registers an account without a registration session only when its last REGISTER status was 200 or a temporary failure, and would therefore also REGISTER an account the user switched off (last code 200 after the un-REGISTER) and skip a working outgoing-only account's calls. The shim sets that internal status to 200 for accounts that should be registered (not while asleep; `.failed` ones only on wake) and to 0 for the rest, which pjsua then skips ("Permanent registration failure, IP change handling will stop for acc N" in PJSIP's log is this skip). A REGISTER that still arrives for an account that is off is undone. (3) `keep_inv_after_tsx_timeout` is switched on by the engine before pjsua sees it (pjsua then does not schedule its own timer that would switch it off one transaction timeout later, while re-INVITEs may still run) and off again when no round runs and no call waits for its re-INVITE, and after `pjsua_destroy`: a re-INVITE that times out does not end the call inside PJSIP; the engine decides. (4) `pjsua_handle_ip_change`: `shutdown_transport` (all TCP/TLS connections), `restart_listener` only when the engine is bound to all interfaces (a restart rebinds to 0.0.0.0 and recomputes the published address; with `bindAddress` set, as in the tests and the self-test, it would undo the binding), `restart_lis_delay` 100 ms. Account config: `ip_change_cfg.shutdown_tp = true`, `hangup_calls = false`, `reinvite_flags = PJSUA_CALL_REINIT_MEDIA | PJSUA_CALL_UPDATE_CONTACT | PJSUA_CALL_UPDATE_VIA`. pjsua re-REGISTERs (new Contact through `allow_contact_rewrite`) and after the 2xx re-INVITEs that account's confirmed calls. (5) On `PJSUA_IP_CHANGE_OP_COMPLETED` of this round (or after one transaction timeout + 5 s without it, so a late report cannot close the next round) the engine re-INVITEs every call of step 1 that pjsua did not (`PJSUA_IP_CHANGE_OP_ACC_REINVITE_CALLS` reports those), except calls whose account's re-REGISTER is still unanswered (pjsua re-INVITEs them after the answer; two re-INVITEs would reinitialise the media twice). Same flags, local hold kept (no UNHOLD flag, pjsua offers the hold SDP), audio only. Then a queued request runs. +**Rounds (`requestIPChange` / `performIPChange`).** One round = one `pjsua_handle_ip_change`. Rounds never overlap: a request while a round runs is queued (the latest reason, flags merged) and started when the round completes. A request is "primary" when the interface or the local address changed (and for `simulateNetworkChange`); otherwise (gateway-only change, network back with the same address, wake with the same address) it is postponed while an outgoing call is still unanswered and runs when no outgoing call rings any more (checked every second, at most 90 s): pjsua hangs up an account's unconfirmed outgoing calls with 410 after that account's re-REGISTER (`pjsua_acc_handle_call_on_ip_change`; test `ringingCallOfReRegisteringAccountEndsOnAddressChange`), which is accepted only when the address really changed (such a call cannot complete then anyway). Steps: (1) every confirmed call gets `reinviteWanted = round` (`isReconnecting`). (2) Auto accounts with a host name decide their IP family again and move to the other family's transport when it changed (`refreshAccountFamilies`, see "IPv6"); then `cpjsua_acc_prepare_ip_change` per account decides whether pjsua re-REGISTERs it: pjsua's `handle_ip_change_on_acc` re-registers an account without a registration session only when its last REGISTER status was 200 or a temporary failure, and would therefore also REGISTER an account the user switched off (last code 200 after the un-REGISTER) and skip a working outgoing-only account's calls. The shim sets that internal status to 200 for accounts that should be registered (not while asleep; `.failed` ones only on wake) and to 0 for the rest, which pjsua then skips ("Permanent registration failure, IP change handling will stop for acc N" in PJSIP's log is this skip). A REGISTER that still arrives for an account that is off is undone. (3) `keep_inv_after_tsx_timeout` is switched on by the engine before pjsua sees it (pjsua then does not schedule its own timer that would switch it off one transaction timeout later, while re-INVITEs may still run) and off again when no round runs and no call waits for its re-INVITE, and after `pjsua_destroy`: a re-INVITE that times out does not end the call inside PJSIP; the engine decides. (4) `pjsua_handle_ip_change`: `shutdown_transport` (all TCP/TLS connections), `restart_listener` only when the engine is bound to all interfaces (a restart rebinds to 0.0.0.0 and recomputes the published address; with `bindAddress` set, as in the tests and the self-test, it would undo the binding), `restart_lis_delay` 100 ms. Account config: `ip_change_cfg.shutdown_tp = true`, `hangup_calls = false`, `reinvite_flags = PJSUA_CALL_REINIT_MEDIA | PJSUA_CALL_UPDATE_CONTACT | PJSUA_CALL_UPDATE_VIA`. pjsua re-REGISTERs (new Contact through `allow_contact_rewrite`) and after the 2xx re-INVITEs that account's confirmed calls. (5) On `PJSUA_IP_CHANGE_OP_COMPLETED` of this round (or after one transaction timeout + 5 s without it, so a late report cannot close the next round) the engine re-INVITEs every call of step 1 that pjsua did not (`PJSUA_IP_CHANGE_OP_ACC_REINVITE_CALLS` reports those), except calls whose account's re-REGISTER is still unanswered (pjsua re-INVITEs them after the answer; two re-INVITEs would reinitialise the media twice). Same flags, local hold kept (no UNHOLD flag, pjsua offers the hold SDP), audio only. Then a queued request runs. **The engine's re-INVITE.** `reinviteInFlight = round` is set before `pjsua_call_reinvite2` is called (on loopback the answer can arrive before it returns) and put back if the call fails synchronously. A transaction in flight (hold, the remote's re-INVITE, an older round's re-INVITE) is waited for in 250 ms steps for up to one transaction timeout. Retry and busy tasks are kept per call and cancelled when a new round starts. @@ -348,7 +354,7 @@ Goal: a network drop, a Wi-Fi -> Ethernet/LTE switch, an IP change or sleep/wake **Media watchdog** (1 s tick, `ContinuousClock`, so wall-clock jumps do not count): per confirmed call the RTP packet count and the number of RTCP reports received (`rtcp.tx.update_cnt`). Clocks pause while the media is not active (local or remote hold), the network is offline or the Mac sleeps; a counter that goes back (new stream after a re-INVITE) restarts them and disarms the watchdog until RTCP arrives on the new stream. Armed only after at least one RTCP report on the stream (a peer without RTCP is never ended by it). No RTP and no RTCP for 60 s while online: an in-dialog OPTIONS probe; 408 or 481 -> the call ends as connection lost (PJSIP ends the dialog on these itself; the bridge maps that end the same way); any other answer (200, 405, 501) -> the call stays and the next probe is one period later. Offline calls are never ended by the engine. -**REGISTER retry with backoff.** pjsua's own retry is off (`reg_retry_interval = 0`, `drop_calls_on_reg_fail = false`). `RegistrationMapping.isTemporary`: 408, 480, 500, 502, 503, 504, no code, or a local failure (status other than PJ_SUCCESS: transport error, DNS failure, `PJSIP_ETPNOTAVAIL`, a refresh that could not be sent) -> temporary; 401/403/404/407/423 and every other 4xx-6xx -> `.failed`, no retry. Also permanent: TLS certificate and TLS configuration errors (the reason contains the text of `PJSIP_TLS_ECERTVERIF`, `ECACERT`, `ECERTFILE`, `EKEYFILE`, `EINVMETHOD`, `ECIPHER`, or "certificate"), and a host name that does not resolve (`PJ_ERESOLVE`, `PJLIB_UTIL_EDNS_NXDOMAIN`) after the network has been online for 10 s (a typo in the server name; right after a change DNS may not work yet, so then it is retried). A temporary failure of an account that should be registered emits `.reconnecting(attempt: n, nextRetryIn: d, lastError:)` with d = 2, 4, 8, 16, 32, then 60 s (`RegistrationBackoff`), and a timer sends the REGISTER again after d. While a retry runs the state stays `.reconnecting` (no `.registering` in between). Success resets the count. A request that met `PJSIP_EBUSY` (a REGISTER in flight) is remembered and repeated when that transaction ends, except when its result is a temporary failure: then only the backoff retry sends the next REGISTER (26.0.1 sent both, so every retry met EBUSY and a REGISTER left after each transaction timeout without backoff). A REGISTER that cannot even be sent (without a network DNS and sendto fail inside `pjsua_acc_set_registration`; pjsua reports it through `on_reg_state2` before returning the error) is such a temporary failure too: `addAccount`, `updateAccount` and `setRegistered` do not throw or roll back for it (deviation from milestone 2.1's "addAccount rolls back if the registration cannot start", which still holds for other errors), the account stays and is retried, so the app can start offline. A retry that falls due while offline or asleep is not sent (the network coming back or wake re-registers through a round); during a round it waits for it. `setRegistered(true)`, `updateAccount` and wake start a fresh series; switching off cancels it. TCP/TLS: `on_transport_state` DISCONNECTED/SHUTDOWN of the transport an account's registration uses (pjsua's own registration bookkeeping, read in the callback before pjsua releases it) counts as a temporary failure ("TLS connection to ... disconnected") -> the same backoff; ignored during a round (it closes them on purpose). Keep-alives are unchanged. +**REGISTER retry with backoff.** pjsua's own retry is off (`reg_retry_interval = 0`, `drop_calls_on_reg_fail = false`). `RegistrationMapping.isTemporary`: 408, 480, 500, 502, 503, 504, no code, or a local failure (status other than PJ_SUCCESS: transport error, DNS failure, `PJSIP_ETPNOTAVAIL`, a refresh that could not be sent) -> temporary; 401/403/404/407/423 and every other 4xx-6xx -> `.failed`, no retry. Also permanent: TLS certificate and TLS configuration errors (the reason contains the text of `PJSIP_TLS_ECERTVERIF`, `ECACERT`, `ECERTFILE`, `EKEYFILE`, `EINVMETHOD`, `ECIPHER`, or "certificate"), and a host name that does not resolve (`PJ_ERESOLVE`, `PJLIB_UTIL_EDNS_NXDOMAIN`) after the network has been online for 10 s (a typo in the server name; right after a change DNS may not work yet, so then it is retried). A temporary failure of an account that should be registered emits `.reconnecting(attempt: n, nextRetryIn: d, lastError:)` with d = 2, 4, 8, 16, 32, then 60 s (`RegistrationBackoff`), and a timer sends the REGISTER again after d (an Auto account with a host name first decides its IP family again, see "IPv6"). While a retry runs the state stays `.reconnecting` (no `.registering` in between). Success resets the count. A request that met `PJSIP_EBUSY` (a REGISTER in flight) is remembered and repeated when that transaction ends, except when its result is a temporary failure: then only the backoff retry sends the next REGISTER (26.0.1 sent both, so every retry met EBUSY and a REGISTER left after each transaction timeout without backoff). A REGISTER that cannot even be sent (without a network DNS and sendto fail inside `pjsua_acc_set_registration`; pjsua reports it through `on_reg_state2` before returning the error) is such a temporary failure too: `addAccount`, `updateAccount` and `setRegistered` do not throw or roll back for it (deviation from milestone 2.1's "addAccount rolls back if the registration cannot start", which still holds for other errors), the account stays and is retried, so the app can start offline. A retry that falls due while offline or asleep is not sent (the network coming back or wake re-registers through a round); during a round it waits for it. `setRegistered(true)`, `updateAccount` and wake start a fresh series; switching off cancels it. TCP/TLS: `on_transport_state` DISCONNECTED/SHUTDOWN of the transport an account's registration uses (pjsua's own registration bookkeeping, read in the callback before pjsua releases it) counts as a temporary failure ("TLS connection to ... disconnected") -> the same backoff; ignored during a round (it closes them on purpose). Keep-alives are unchanged. **A 2xx that leaves out our Contact.** A 2xx to a REGISTER lists the bindings the server holds. Behind NAT with Asterisk's `rewrite_contact=yes`, PJSIP's Contact rewrite (`PJSUA_CONTACT_REWRITE_NO_UNREG`) sends the new Contact and the old one at expires=0 in one request; the server rewrites both to the source address, adds and removes the same binding, and answers 200 with no Contact. Until the next refresh, up to the registration interval, no incoming call arrives. `pjOnRegState2` checks the answer (`cpjsua_regc_lists_our_contact`, other devices on the extension do not count) and sends the REGISTER again, now with one Contact; the account shows as registered only after that. A server that leaves it out again is believed from then on (`BindingRepair`), so it gets one extra REGISTER and not one per refresh. @@ -365,10 +371,27 @@ Code: `Model/NetworkSettings.swift` (fields, decoding, `isValidRTPRange`, `effec - **RTP port window** (`rtpPortStart`, `rtpPortCount`). Per account: `rtp_cfg.port = start`, `rtp_cfg.port_range = max(1, count - 2)`, `randomize_port = 1`. pjsua picks RTP ports at even offsets in `port...port+range` and RTCP = RTP + 1, so every port used lies in `start...start+count-1`; range 0 would mean "no limit", hence at least 1 (a two-port window uses only the start port). Each call needs one pair, so a window of N ports carries N/2 calls (a loopback call two). Valid: start 1024-65535, count >= 2, last port <= 65535 (`NetworkSettings.isValidRTPRange`, for the UI); the engine clamps anything else (`effectiveRTPRange`: start into 1024...65534, count into what fits, at least 2) rather than failing `start`. - **rport** (`useRport`). pjsua 2.17 has no per-account `use_rport`; it is the endpoint flag `pjsip_cfg()->endpt.disable_rport`, read whenever a request's Via is built. Global and kept across `pjsua_destroy`, so `start` sets it both ways. Live: the next request (REGISTER refresh, INVITE) follows the new value. `allow_contact_rewrite`/`allow_via_rewrite` stay on; without rport they still use `received`. -- **DNS SRV** (`dnsSRV`, `nameserver`). Off (default): no resolver, host names go through the system (`getaddrinfo`, A/AAAA). On: `pjsua_config.nameserver` gets the servers, so pjsua creates the SIP resolver (`pjsip_endpt_create_resolver`); a registrar, outbound proxy or request URI host without an explicit port and not an IP is then resolved with SRV first (`_sip._udp.`, `_sip._tcp.` or `_sips._tcp.` + host, from the account's transport), then A of the SRV target, falling back to A of the host when there is no SRV record (RFC 3263 section 4.2; PJSIP does not do NAPTR, the transport always comes from the account). Explicit ports skip SRV. `nameserver`: "10.0.0.1", "10.0.0.1:5353", "[2001:db8::1]:53" or a bare IPv6, several separated by commas, semicolons or blanks, at most 4; entries that cannot be read and scoped (link-local) IPv6 addresses are skipped. `pjsua_config` only knows port 53, so when a server has another port `cpjsua_set_nameservers` sets the list again with ports (`pj_dns_resolver_set_ns`) right after `pjsua_init`. Empty or nil: the system resolvers, from SystemConfiguration (`State:/Network/Global/DNS` `ServerAddresses`, what macOS itself uses), else the `nameserver` lines of `/etc/resolv.conf` (what `res_ninit` reads). With system resolvers, a network change (route change, back online, wake) re-reads them and updates the resolver if they differ. SRV on but no server known: a level 2 `.log` line and plain lookups. `start` logs "engine: DNS SRV via 10.0.0.1:53, ...". +- **DNS SRV** (`dnsSRV`, `nameserver`). Off (default): no resolver, host names go through the system (`getaddrinfo`, A/AAAA). On: `pjsua_config.nameserver` gets the servers, so pjsua creates the SIP resolver (`pjsip_endpt_create_resolver`); a registrar, outbound proxy or request URI host without an explicit port and not an IP is then resolved with SRV first (`_sip._udp.`, `_sip._tcp.` or `_sips._tcp.` + host, from the account's transport), then A of the SRV target, falling back to A of the host when there is no SRV record (RFC 3263 section 4.2; PJSIP does not do NAPTR, the transport always comes from the account). Explicit ports skip SRV. With SRV in effect, an Auto account whose server is a host name without a port uses IPv4 (see "IPv6"). `nameserver`: "10.0.0.1", "10.0.0.1:5353", "[2001:db8::1]:53" or a bare IPv6, several separated by commas, semicolons or blanks, at most 4; entries that cannot be read and scoped (link-local) IPv6 addresses are skipped. `pjsua_config` only knows port 53, so when a server has another port `cpjsua_set_nameservers` sets the list again with ports (`pj_dns_resolver_set_ns`) right after `pjsua_init`. Empty or nil: the system resolvers, from SystemConfiguration (`State:/Network/Global/DNS` `ServerAddresses`, what macOS itself uses), else the `nameserver` lines of `/etc/resolv.conf` (what `res_ninit` reads). With system resolvers, a network change (route change, back online, wake) re-reads them and updates the resolver if they differ. SRV on but no server known: a level 2 `.log` line and plain lookups. `start` logs "engine: DNS SRV via 10.0.0.1:53, ...". - **What applies live** (`applyNetworkSettings(_:) -> NetworkApplyResult`, rule in `NetworkSettings.needsRestart(from:)`). Live: `useRport` (endpoint flag), `keepAliveSeconds` and `useICE` (every account is `pjsua_acc_modify`d with `disable_reg_on_modify`, no re-REGISTER; ICE applies to the next call). Needs a restart (`.needsRestart`; the engine keeps running with the old values, the live parts are applied anyway): the RTP window, `dnsSRV`, `nameserver` (only while `dnsSRV` is on), `localPort`, `stunServer`, `echoCancellation`. The app then does `stop()` + `start(network:)` with the stored settings when the user agrees (Settings › Network "Restart now"). Before `start` it returns `.applied` and changes nothing (`start` takes its own settings). The RTP window could technically follow `pjsua_acc_modify` for new calls, but is kept with DNS as "restart" so the UI rule stays simple. -- **Tests.** `Engine262Tests.swift`: value tests (old JSON decodes with the defaults, round trip, RTP range validation/clamping and the `port_range` mapping, restart rules, nameserver parsing and `resolv.conf`); `rtpPortsStayInConfiguredWindow` (loopback call with window 42000+10: both legs' local RTP ports inside and different; `keepAliveSeconds` change -> `.applied`, window change -> `.needsRestart`; a new start with 43100+4 uses that window); `rportFollowsSetting` (`NetworkStub` records the top Via of each REGISTER: no `rport` when started with `useRport = false`, `;rport` on the next REGISTER after a live switch, the endpoint flag back on after `stop`); `dnsSRVResolvesRegistrar` (an in-process DNS stub, `DNSStub`, answers `_sip._udp.example.test` SRV -> pbx.example.test: and its A record 127.0.0.1; with `nameserver = "127.0.0.1:"` an account on domain `example.test` registers at the stub after an SRV query; without SRV no resolver exists; a nameserver change -> `.needsRestart`); `privateServerAddresses` and `privateServerAccountsDoNotUseSTUN` (ranges, URIs, hop combinations, the STUN fields and `transport_id` read back from `pjsua_acc_config` with and without a STUN server); `privateServerAccountDoesNotUseSTUN` (an in-process STUN stub, `STUNStub`, maps every socket to 203.0.113.5 and the engine is bound to all interfaces, so the UDP transport is published as 203.0.113.5: an account at `localhost` keeps that address in Via, Contact and SDP and its RTP sockets ask STUN; the account at 127.0.0.1 sends 127.0.0.1 in Via and Contact, registers, and its call asks no STUN and offers 127.0.0.1 in SDP, the Contact's address; it binds all interfaces because a bind address is published for SIP and RTP alike and would hide every difference); `privateIPv6ServerAccountIsAdded` (registrar `[::1]:5999` with STUN on: the account is added, stays bound and is retried, `.reconnecting`). -- **No STUN for private servers** (`stunServer` is global; `PrivateServer.allHopsPrivate`). An account whose every signalling hop is a private or local IP literal does not use STUN: `sip_stun_use` and `media_stun_use` are `PJSUA_STUN_USE_DISABLED`. Hops: the registrar, and the outbound proxy when one is set, otherwise the domain (INVITE, SUBSCRIBE and PUBLISH go there). Private: 10/8, 172.16/12, 192.168/16, 100.64/10 (RFC 6598 shared space: carrier NAT, Tailscale; never routed on the internet), 127/8, 169.254/16, ::1, fc00::/7, fe80::/10 (and IPv4-mapped forms). Host names are not resolved and keep STUN, and so does an account with one public or named hop. Why: such a server is reached on the LAN or over a VPN, where the STUN-mapped public address is wrong; the first REGISTER carried it in Contact and Via, PJSIP learnt the real address only from the 401's `received`/`rport` and registered again ("IP address change detected ... Updating registration (using method 2)"), and a server that does not rewrite Contact would send incoming calls to the public address. The flag alone does not change Contact and Via: for an account bound to the UDP transport pjsua takes both from the transport's published address, which STUN set at start (`pjsua_acc_get_uac_addr` -> `pjsip_tpmgr_find_local_addr2`, which ignores `local_if` under a `PJSIP_TPSELECTOR_TRANSPORT` selector, sip_transport.c). So while a STUN server is set, a UDP account of a private server whose hops are all dotted IPv4 literals is not bound to the transport (`transport_id = PJSUA_INVALID_ID`): pjsua then takes the local address of the route to the server (`get_net_interface`) with the transport's port, and requests still go out through the one UDP transport (large ones stay on UDP through `disable_tcp_switch`, so the milestone 4 reason against unbinding no longer holds). An IPv6 hop (also `[::ffff:a.b.c.d]`) keeps the account bound, with STUN still off: for any host with a colon `pjsua_acc_get_uac_addr` asks for an IPv6 transport, which the engine does not create, and the account would be refused instead of retried. TCP/TLS listeners are never published with a STUN address and stay bound, as does every account when no STUN server is set. Media: a call asks no STUN from its RTP sockets, and `allow_sdp_nat_rewrite` is on, so the SDP takes the address the registrar reported in the REGISTER answer's Via (`received`, else our sent-by), which is what Contact ends up with too; without it pjsua offers the default route's address (`pj_gethostip`), which over a split-tunnel VPN is another interface than the one towards the server, and a PBX without symmetric RTP would send its audio there. Remaining: until the first REGISTER answer, and for an account that does not register, the SDP still has the default route's address. `allow_contact_rewrite`/`allow_via_rewrite` stay on: a server behind a VPN hub can still see another source address than the Mac's own (VPN NAT), and the rewrite after the first answer repairs the Contact then. Accepted follow-ups: an unbound account has `tp_type` UNSPECIFIED and so gets the transport-match score for incoming TCP/TLS requests too (pjsua_acc.c:523 and 3595), which can attribute an incoming TLS INVITE to a private UDP account instead of a TLS provider account with the same To host (the fix would be an `on_acc_find_for_incoming` that prefers the account whose transport matches); after `updateAccount` moves an account from a public to a private server, `destroy_regc` clears `acc->contact` but not `acc->via_addr`, so the first REGISTER's Via keeps the old address until the first answer (harmless with rport). +- **Tests.** `Engine262Tests.swift`: value tests (old JSON decodes with the defaults, round trip, RTP range validation/clamping and the `port_range` mapping, restart rules, nameserver parsing and `resolv.conf`); `rtpPortsStayInConfiguredWindow` (loopback call with window 42000+10: both legs' local RTP ports inside and different; `keepAliveSeconds` change -> `.applied`, window change -> `.needsRestart`; a new start with 43100+4 uses that window); `rportFollowsSetting` (`NetworkStub` records the top Via of each REGISTER: no `rport` when started with `useRport = false`, `;rport` on the next REGISTER after a live switch, the endpoint flag back on after `stop`); `dnsSRVResolvesRegistrar` (an in-process DNS stub, `DNSStub`, answers `_sip._udp.example.test` SRV -> pbx.example.test: and its A record 127.0.0.1; with `nameserver = "127.0.0.1:"` an account on domain `example.test` registers at the stub after an SRV query; without SRV no resolver exists; a nameserver change -> `.needsRestart`); `privateServerAddresses` and `privateServerAccountsDoNotUseSTUN` (ranges, URIs, hop combinations, the STUN fields and `transport_id` read back from `pjsua_acc_config` with and without a STUN server); `privateServerAccountDoesNotUseSTUN` (an in-process STUN stub, `STUNStub`, maps every socket to 203.0.113.5 and the engine is bound to all interfaces, so the UDP transport is published as 203.0.113.5: an account at `localhost` (IPv4 only since 26.3.1: on Auto the name resolves to ::1 first and IPv6 accounts have no STUN) keeps that address in Via, Contact and SDP and its RTP sockets ask STUN; the account at 127.0.0.1 sends 127.0.0.1 in Via and Contact, registers, and its call asks no STUN and offers 127.0.0.1 in SDP, the Contact's address; it binds all interfaces because a bind address is published for SIP and RTP alike and would hide every difference); `privateIPv6ServerAccountIsAdded` (registrar on an IPv6 stub at `[::1]` with STUN on and the engine on all interfaces: bound to the UDP6 transport, no STUN, registers over IPv6; in 26.2 it stayed on the IPv4 transport and was retried forever). +- **No STUN for private servers** (`stunServer` is global; `PrivateServer.allHopsPrivate`). An account whose every signalling hop is a private or local IP literal does not use STUN: `sip_stun_use` and `media_stun_use` are `PJSUA_STUN_USE_DISABLED`. Hops: the registrar, and the outbound proxy when one is set, otherwise the domain (INVITE, SUBSCRIBE and PUBLISH go there). Private: 10/8, 172.16/12, 192.168/16, 100.64/10 (RFC 6598 shared space: carrier NAT, Tailscale; never routed on the internet), 127/8, 169.254/16, ::1, fc00::/7, fe80::/10 (and IPv4-mapped forms). Host names are not resolved and keep STUN, and so does an account with one public or named hop. Why: such a server is reached on the LAN or over a VPN, where the STUN-mapped public address is wrong; the first REGISTER carried it in Contact and Via, PJSIP learnt the real address only from the 401's `received`/`rport` and registered again ("IP address change detected ... Updating registration (using method 2)"), and a server that does not rewrite Contact would send incoming calls to the public address. The flag alone does not change Contact and Via: for an account bound to the UDP transport pjsua takes both from the transport's published address, which STUN set at start (`pjsua_acc_get_uac_addr` -> `pjsip_tpmgr_find_local_addr2`, which ignores `local_if` under a `PJSIP_TPSELECTOR_TRANSPORT` selector, sip_transport.c). So while a STUN server is set, a UDP account of a private IPv4 server is not bound to the transport (`transport_id = PJSUA_INVALID_ID`): pjsua then takes the local address of the route to the server (`get_net_interface`) with the transport's port, and requests still go out through the one UDP transport (large ones stay on UDP through `disable_tcp_switch`, so the milestone 4 reason against unbinding no longer holds). An IPv6 server (also `[::ffff:a.b.c.d]`) makes the account an IPv6 account since 26.3.1: bound to the IPv6 twin of its transport, STUN off for every server (see "IPv6"); before, it stayed bound to the IPv4 transport and could never register. TCP/TLS listeners are never published with a STUN address and stay bound, as does every account when no STUN server is set. Media: a call asks no STUN from its RTP sockets, and `allow_sdp_nat_rewrite` is on, so the SDP takes the address the registrar reported in the REGISTER answer's Via (`received`, else our sent-by), which is what Contact ends up with too; without it pjsua offers the default route's address (`pj_gethostip`), which over a split-tunnel VPN is another interface than the one towards the server, and a PBX without symmetric RTP would send its audio there. Remaining: until the first REGISTER answer, and for an account that does not register, the SDP still has the default route's address. `allow_contact_rewrite`/`allow_via_rewrite` stay on: a server behind a VPN hub can still see another source address than the Mac's own (VPN NAT), and the rewrite after the first answer repairs the Contact then. Accepted follow-ups: an unbound account has `tp_type` UNSPECIFIED and so gets the transport-match score for incoming TCP/TLS requests too (pjsua_acc.c:523 and 3595), which can attribute an incoming TLS INVITE to a private UDP account instead of a TLS provider account with the same To host (the fix would be an `on_acc_find_for_incoming` that prefers the account whose transport matches); after `updateAccount` moves an account from a public to a private server, `destroy_regc` clears `acc->contact` but not `acc->via_addr`, so the first REGISTER's Via keeps the old address until the first answer (harmless with rport). + +## IPv6 +Dual stack since 26.3.1 ([#11](https://github.com/HSMM/MacroSIP/issues/11), ADR 0014). Code: `IPFamily.swift` (`IPFamily`, `IPFamilyPolicy`, `IPFamilyResolver`, `SIPHop`), `transportFamilies` and `createTransports` in `Engine.swift`, `decideFamily` and `refreshAccountFamily` in `Engine+Accounts.swift`, `TransportIDs` and `AccountMapping.settings(... family:)`, `NetworkPath.address6`; C helpers `cpjsua_tls_transport_create(type, ...)` and `cpjsua_call_local_rtp_addr`. Setting: `AccountConfig.ipProtocol` (account editor › Advanced › Connection › IP protocol: Auto, IPv4 only, IPv6 only). + +- **Transports.** Every transport has an IPv6 twin: UDP6, TCP6, TLS6 verifying and TLS6 non-verifying (`TransportIDs.udp6`, `tcp6`, `tls6`, `tls6NoVerify`). pjlib sets `IPV6_V6ONLY` on every IPv6 socket (`PJ_SOCK_HAS_IPV6_V6ONLY` is 1 in our build, `pj_sock_socket`), so `[::]:P` and `0.0.0.0:P` coexist and both families listen on the configured `localPort` (TLS on a random port, as before; with port 0 each family gets its own random port). The IPv4 UDP transport is required as before; the IPv6 ones are best effort: a failure is logged ("UDP over IPv6 transport on port P: ...") and only the accounts that would need that transport are refused (`EngineError.transportUnavailable(kind, ipv6: true)`). Without a global IPv6 address pjsua publishes the UDP6 transport with a link-local or loopback address (`pj_gethostip`), which only a server on the same link or on loopback can use. `localPort(of:family:)` reports the ports; `localPort(of:)` stays IPv4. +- **Bind address** (`Engine(bindAddress:)`, `macrosip-cli --bind`; brackets are dropped, "[::1]" is "::1"). An address of one family creates that family's transports only, and its UDP is the required one; accounts of the other family are refused with `transportUnavailable`. No bind address: both families on all interfaces. RTP binds to the bind address only for accounts of its family (`AccountMapping`), which with a bind address are the only ones. A bind address that is not an IP literal counts as IPv4 (pjsua resolves it for an IPv4 socket). +- **Accounts stay bound.** `pjsua_init_tpselector` turns `transport_id` into a TRANSPORT selector (UDP) or a LISTENER selector (TCP/TLS), which fixes the family; `ipv6_sip_use` (`PJSIP_TPSELECTOR_IP_VER`) only applies to unbound accounts. Unbinding would change Contact and Via under STUN and lose the choice between the verifying and the non-verifying TLS listener, so every account is bound to the transport of its family. pjsua then takes Contact and Via from that transport (`pjsua_acc_get_uac_addr` adds the IPv6 flag for an account whose `tp_type` is IPv6), and an incoming request over UDP6, TCP6 or TLS6 scores the transport match only for the accounts bound to that transport type (`pjsua_acc_find_for_incoming`). The unbound exception of "No STUN for private servers" is IPv4 only. +- **Which family** (`IPFamilyPolicy.decide`). The server is the first hop: the outbound proxy when one is set, otherwise the registrar (or the domain). An IP literal picks its own family; IPv4 only and IPv6 only with a host name use that family. Auto with a host name: when only one family has a transport for the account's kind (a bind address, a failed IPv6 transport), that family without a lookup; with DNS SRV in effect (pjsua has a resolver) and no explicit port, IPv4, because `getaddrinfo` cannot follow SRV records (pjsua resolves the SRV targets itself, A and AAAA, and skips entries of the other family; choose IPv6 only for a server whose SRV targets have AAAA records only); otherwise the first family that `getaddrinfo(host, AF_UNSPEC)` returns (`IPFamilyResolver.system`, with `pj_getaddrinfo`'s hints: no socket type, no flags, so it is the first address PJSIP itself sends to) and that has a transport. Nothing resolved (offline): IPv4, decided again later. The lookup is synchronous on the engine queue, like PJSIP's own lookup when it sends a request without its DNS resolver (sip_resolve.c) and pjsua's lookup for a TCP/TLS Contact in `pjsua_acc_get_uac_addr`; tests inject a resolver (`setFamilyResolverForTests`). A host name that lacks the chosen family (IPv6 only, no AAAA) fails to register with a DNS error like any unknown host. +- **Contradictions.** IPv4 only with an IPv6 literal server (or IPv6 only with an IPv4 literal) can never register: `addAccount` and `updateAccount` throw `.invalidArgument("server 2001:db8::1 is an IPv6 address but the account is set to IPv4 only")`, and the account editor shows "The server's address is an IPv6 address. Choose Auto or IPv6 only." under Connection with Save and Test off (`IPFamilyPolicy.conflict`, also used by the editor). An IPv4-mapped literal (`[::ffff:a.b.c.d]`) is an IPv6 literal. +- **Decided again** (`refreshAccountFamily`) for Auto accounts with a host name (not the SRV case) at the start of every network-change round (before `cpjsua_acc_prepare_ip_change`) and before every REGISTER retry. When the family changed, the account is `pjsua_acc_modify`d onto the other family's transport without a REGISTER (`disable_reg_on_modify`); pjsua destroys its registration session, the round or the retry registers it afresh with a new Contact, and the registrar's requests are trusted again only after it accepted that REGISTER (`setRegistrarSource(nil)`). A call in progress keeps its dialog; the round re-INVITEs it like any call, and it may not survive a change of family (a move from an IPv4 network to an IPv6-only one cannot keep an IPv4 call anyway). A changed IP protocol goes through `updateAccount` (`pjsua_acc_modify`), without a restart. +- **Media.** IPv6 accounts set `ipv6_media_use = PJSUA_IPV6_ENABLED_USE_IPV6_ONLY`: `get_media_ip_version` (pjsua_media.c) counts `::1`, link-local and a missing global address as "available" but not "usable", so PREFER_IPV6 would offer IPv4 on loopback and on a Mac without a global IPv6 address. The offer is `c=IN IP6` with IPv6 RTP sockets. An incoming offer is answered in its own family: an `IN IP4` offer to an IPv6 account gets an IPv4 answer and IPv4 RTP (with an IPv6 bind address that socket cannot be bound and the call fails). IPv4 accounts keep pjsua's default (PREFER_IPV4): IPv4 offers, and an `IN IP6` offer is answered with IPv6, as before. `localRTPAddress(of:)` reports the RTP address (diagnostics, tests). +- **No STUN over IPv6.** IPv6 accounts have `sip_stun_use` and `media_stun_use` disabled (STUN and TURN over IPv6 are out of scope; pjsua maps IPv4 only) and `allow_sdp_nat_rewrite` on, so after the first REGISTER answer the SDP carries the address the registrar saw (with temporary addresses, the one actually used) instead of `pj_gethostip`'s pick. +- **No ICE over IPv6** (deviation from the plan). With ICE on, pjsua gives an IPv6 call an IPv6 ICE component bound to the string "0" (`IN6_ADDR_ANY` in `create_ice_media_transport`), which macOS `getaddrinfo` turns into `::ffff:0.0.0.0`; binding a V6ONLY socket to that fails ("Failed creating STUN transport #1 for comp 1: Can't assign requested address"), so the offer carried IPv4 host candidates and `c=IN IP4` only, and an IPv6 answer then failed the call (`pjmedia_stream_info_from_sdp`: PJ_EAFNOTSUP). IPv6 accounts therefore have ICE off (`iceEnabled = useICE && family == .ipv4`) and use plain RTP; a level 3 line says so when ICE is on. The fix belongs in PJSIP (bind the IPv6 component to "::"), which needs a patched pjsua_media.c and a rebuild; not done. +- **Incoming.** Requests over UDP6, TCP6 and TLS6 reach the account bound to that transport: an IPv4 and an IPv6 account with the same user and domain each get the calls and messages of their own family. `SignallingSource` compares IPv6 addresses in any spelling (`[2001:DB8:0::1]` is `2001:db8::1`), so the registrar-source trust (answer-after) works over IPv6. +- **Network changes.** `NetworkPath.address6` is the source address of the default IPv6 route (a UDP socket connected to 2001:db8::1, nothing sent; link-local and loopback do not count) and part of the primary route, so a new global IPv6 address, for example a new preferred temporary address, starts a round when NWPathMonitor reports an update (see "Network resilience") while an account is bound to IPv6, and so does IPv6 appearing (an Auto host name may resolve to IPv6 first now). Without IPv6 accounts a new IPv6 address alone starts no round: it changes nothing for them, and a round would end a ringing outgoing call (pjsua's 410). `pjsua_handle_ip_change` with `restart_listener` restarts every listener, the IPv6 ones included (all `tpdata`), and recomputes their published addresses. +- **Tests.** `EngineIPv6Tests.swift` with `IPv6Stub` (UDP and TCP on `[::1]`, optionally UDP on 127.0.0.1 with the same port; answers REGISTER and INVITE with `IN IP6 ::1`, records family, transport, Via, Contact and bodies; sends INVITE with an IPv6 or IPv4 offer and MESSAGE). Values: old JSON decodes as Auto (unknown values too), literals, first hop, contradictions, the decision with a fake resolver (literals, fixed families, resolver order, offline, availability, SRV), `IPFamilyResolver.system` against `getaddrinfo`, mapping by family and its read-back from `pjsua_acc_config` (transport id, `ipv6_media_use`, STUN, bind address), transport ids, IPv6 registrar-source comparison, `NetworkPath.address6`. pjsua: `bindAddressDecidesTransportFamilies`; `ipv6TransportFailureIsNotFatal` (`[::]:P` held by another socket: the engine starts with IPv4 UDP and TCP6 on P and refuses IPv6 UDP accounts; released, both UDP transports use P); `contradictoryIPProtocolIsRefused`; `ipv6AccountRegistersOverUDP6` (Via and Contact `[::1]`, the live config, a MESSAGE out over UDP6); `ipv6AccountRegistersOverTCP6`; `ipv6CallOffersIPv6MediaAndCarriesRTP` (`c=IN IP6 ::1`, RTP address `::1`, a loopback call over `[::1]` with RTP both ways); `incomingOverIPv6ReachesTheIPv6Account` (account by family, answers per offer family, MESSAGE); `autoFollowsSystemResolverForHostNames` ("localhost": Auto follows getaddrinfo's first family, IPv4 only and IPv6 only keep theirs); `familyIsDecidedAgainOnNetworkChangeAndRetry`; `newIPv6AddressStartsRoundOnlyForIPv6Accounts` (IPv6 appearing starts a round, a new address without IPv6 accounts does not, with one it does); `networkChangeRestartsIPv6Listeners`; `iceIsNotUsedOverIPv6`. In `Engine262Tests.swift`, `privateIPv6ServerAccountIsAdded` now registers over UDP6 with STUN on, and `privateServerAccountDoesNotUseSTUN` sets IPv4 only for its "localhost" account. +- **Only a real network can verify:** a real IPv6 PBX over UDP, TCP and TLS (a certificate for an AAAA name), a dual-stack server by host name, an IPv6-only network, router-advertised and temporary addresses (whether NWPathMonitor reports a new temporary address at all, and the Contact after a rotation), moving between IPv4-only, dual-stack and IPv6-only networks with calls in progress, SRV targets with AAAA records only, IPv6 firewalls without NAT, and RTP through them. ## Deny incoming calls Code: `CallOptions.denyIncoming`/`knownNumbers`/`denial(fromURI:privacy:)`/`isAnonymous`/`knownNumberKey` (`EngineTypes.swift`), the first check in `pjOnIncomingCall` and `rejectIncoming` (`EngineBridge.swift`), `cpjsua_rdata_header` (Privacy). diff --git a/docs/GLOSSARY.md b/docs/GLOSSARY.md index 1806900..b1ea371 100644 --- a/docs/GLOSSARY.md +++ b/docs/GLOSSARY.md @@ -5,6 +5,7 @@ Shared vocabulary for MacroSIP. Code identifiers follow these names. - **Account** — one SIP identity (user, domain, registrar, credentials, transport). Several accounts may be enabled and registered at once. One account is the **default outgoing account**. - **Registration** — the account's REGISTER state with the server: `unregistered`, `registering`, `registered`, `failed(reason)`. - **Transport** — how SIP signalling travels: UDP, TCP or TLS. **SRTP** encrypts media and is independent of the signalling transport; modes are `disabled`, `optional`, `mandatory`. +- **IP protocol** — per account, whether signalling and media use IPv4 or IPv6: `auto` (an IP address picks its own family, a host name follows the order the system resolver returns), `ipv4` (IPv4 only), `ipv6` (IPv6 only). The family the engine decided is the account's **IP family**; each transport exists for both families (UDP6, TCP6, TLS6 are the IPv6 twins). - **Call** — one SIP dialog with a remote party. States: `incoming`, `outgoing` (ringing on the far end), `early`, `connected`, `held`, `disconnected`. Exactly one connected call is **active** (sending and receiving audio); others are held. - **Remote party** — the display name and SIP URI of the other side of a call. - **Dial string** — what the user typed; it is resolved to a SIP URI using the outgoing account's domain. @@ -27,6 +28,6 @@ Shared vocabulary for MacroSIP. Code identifiers follow these names. - **Call quality (MOS)** — the real-time estimate of a call's audio quality from RTCP statistics (loss, jitter, round-trip time); MOS is the mean opinion score, 1 to 5. A low value shows the "poor connection" notice. - **Headset follow** — the automatic switch of the audio devices to a headset when it is connected, and back when it is removed. - **Reconnecting** — the state of an account or call while the app restores registration after a network drop, an IP change or sleep. Accounts show "retry in N s"; calls keep their timer and show "Reconnecting… N s". -- **Advanced (account editor)** — the collapsible section of the account editor with the rarely changed fields: display name, auth username, domain, proxy, transport, SRTP, registration expiry, certificate verification and the register, default and presence switches. +- **Advanced (account editor)** — the collapsible section of the account editor with the rarely changed fields: display name, auth username, domain, proxy, transport, IP protocol, SRTP, registration expiry, certificate verification and the register, default and presence switches. - **Product** — one build, `MacroSIP`, bundle id `com.hsmm.macrosip` (ADR 0003). - **Engine** — the Swift layer in `MacroSIPCore` that owns the single pjsua instance and exposes accounts, calls and events to the UI. diff --git a/docs/adr/0014-ipv6-dual-stack.md b/docs/adr/0014-ipv6-dual-stack.md new file mode 100644 index 0000000..4ad5e1a --- /dev/null +++ b/docs/adr/0014-ipv6-dual-stack.md @@ -0,0 +1,57 @@ +# ADR 0014 — IPv6 dual stack + +Date: 2026-11-09. Status: accepted. Issue [#11](https://github.com/HSMM/MacroSIP/issues/11), release 26.3.1. + +## Context +PJSIP is built with `PJ_HAS_IPV6 1` (ADR 0002), but up to 26.3.0 the engine created IPv4 transports +only and bound every account to one of them (`transport_id`). An account whose registrar or proxy is +an IPv6 literal could therefore never register and was retried forever, a host name with only an AAAA +record could not be reached, and media was IPv4 only. Users want servers reachable over IPv6: a PBX +by IPv6 literal, a host name with AAAA records, a dual-stack server on an IPv6-capable network. + +Binding fixes the family: `pjsua_init_tpselector` turns `transport_id` into a TRANSPORT selector +(UDP) or a LISTENER selector (TCP/TLS), and pjsua's own IP version preference (`ipv6_sip_use`) only +applies to unbound accounts. Unbinding is not an option: it changes Contact and Via under STUN and +loses the choice between the verifying and the non-verifying TLS listener (milestone 2.1, 26.2). + +## Decision +- **Full dual stack.** Every SIP transport gets an IPv6 twin (UDP6, TCP6, TLS6 verifying and + non-verifying) on the same configured port (pjlib sets `IPV6_V6ONLY`, so both families can hold + it). Each account is bound to the transport of its family. IPv6 transports are never fatal: a Mac + may have no IPv6; accounts that need a missing transport are refused with `transportUnavailable`. + A bind address of one family creates only that family's transports. +- **Per-account setting** "IP protocol" in the account editor's Advanced group: Auto (default), + IPv4 only, IPv6 only (`AccountConfig.ipProtocol`; older files decode as Auto). +- **Auto** looks at the first hop (outbound proxy, else registrar): an IP literal picks its own + family; a host name follows the first address the system resolver returns (`getaddrinfo` with + `AF_UNSPEC`, the call PJSIP itself makes when it sends), "as the system decides". With DNS SRV in + effect and no explicit port the name cannot be asked that way, so Auto uses IPv4 there; a host + name that does not resolve (offline) also gives IPv4. The decision is made again at every network + change and before every REGISTER retry, and an account whose family changed is moved to the other + transport before it registers. The lookup runs synchronously on the engine queue, as PJSIP's own + lookup does when it sends without its DNS resolver. +- **Contradictions are refused.** IPv4 only with an IPv6 literal server, or IPv6 only with an IPv4 + literal, can never work: the editor says so and keeps Save off, and the engine throws + `invalidArgument`. +- **Media follows the account.** IPv6 accounts offer IPv6 only (`PJSUA_IPV6_ENABLED_USE_IPV6_ONLY`, + because pjsua's IPv6 preference falls back to IPv4 without a global IPv6 address); IPv4 accounts + keep pjsua's default. Every offer is answered in its own family. +- **No STUN over IPv6.** IPv6 accounts use neither SIP nor media STUN, and the SDP takes the address + the registrar saw (`allow_sdp_nat_rewrite`), as for private IPv4 servers since 26.2. +- **No ICE over IPv6, for now.** The plan was IPv6 ICE candidates. PJSIP 2.17 binds the IPv6 ICE + component to the string "0", which macOS `getaddrinfo` turns into `::ffff:0.0.0.0`; that socket + cannot be bound, the offer carries IPv4 candidates only and a call fails on an IPv6 answer. IPv6 + accounts therefore have ICE off and use plain RTP. Enabling it needs a PJSIP patch (bind "::"), + which is a separate decision because it means patching and rebuilding PJSIP. +- **Out of scope:** NAT64 and 464XLAT for IPv4 servers on IPv6-only networks, STUN and TURN over + IPv6, servers on link-local addresses (`fe80::…%en0`). + +## Consequences +An account at `[2001:db8::1]` or at an AAAA-only host name registers and calls over IPv6, with +`c=IN IP6` and IPv6 RTP; existing IPv4 accounts behave as before. A host name with A and AAAA records +may move to IPv6 after the update when macOS orders the IPv6 address first (as `localhost` does); +"IPv4 only" keeps the old behaviour. The engine opens four more listening sockets. With a host name +whose order changes between networks, the account may change family at a network change; a call in +progress on the old family may not survive that. IPv6 accounts lose ICE until PJSIP is patched. +Everything is verified on loopback only (`[::1]` with in-process stubs); behaviour on a real IPv6 +PBX and network is left to users and listed as not verified (docs/ENGINE.md "IPv6"). diff --git a/docs/adr/README.md b/docs/adr/README.md index 9ffa46c..739c9e4 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -2,3 +2,20 @@ One file per decision, numbered, never edited after acceptance except to add a "Superseded by" line. Format: Context, Decision, Consequences. + +| ADR | Decision | +|---|---| +| [0001](0001-platform-and-ui-stack.md) | macOS 14+, Swift/SwiftUI, SwiftPM without Xcode | +| [0002](0002-pjsip-build.md) | PJSIP 2.17 built statically by a script | +| [0003](0003-product-scope.md) | Product scope | +| [0004](0004-storage.md) | JSON files plus Keychain, no MicroSIP import in v1 | +| [0005](0005-accounts-and-calls.md) | Simultaneous accounts, in-window calls, floating incoming window | +| [0006](0006-quality-and-testing.md) | Tests, verification and the pjsua second phone | +| [0007](0007-license-and-distribution.md) | GPLv2+, public repository, ad-hoc signing | +| [0008](0008-development-workflow.md) | Development workflow | +| [0009](0009-ui-decisions.md) | UI decisions from the mockup review | +| [0010](0010-versioning.md) | Version numbers | +| [0011](0011-localization-files.md) | Localization with .strings files | +| [0012](0012-universal-build.md) | Universal build; OpenSSL and Opus from pinned sources | +| [0013](0013-in-app-updates-sparkle.md) | In-app updates with Sparkle | +| [0014](0014-ipv6-dual-stack.md) | IPv6 dual stack: IPv6 twins of every transport, per-account IP protocol | From c6388de273d87b5333be0b505fb0d546886a802f Mon Sep 17 00:00:00 2001 From: HSMM Date: Mon, 9 Nov 2026 13:14:31 +0300 Subject: [PATCH 02/12] Account editor: IP protocol in Advanced, refused when it contradicts the server address --- Sources/MacroSIPApp/Model/Strings.swift | 13 +++++++ Sources/MacroSIPApp/Platform/AppInfo.swift | 3 +- .../Resources/en.lproj/Localizable.strings | 7 ++++ .../Resources/ru.lproj/Localizable.strings | 7 ++++ .../Views/Settings/AccountEditorSheet.swift | 37 +++++++++++++++++-- docs/design/SCREENS.md | 9 ++++- 6 files changed, 69 insertions(+), 7 deletions(-) diff --git a/Sources/MacroSIPApp/Model/Strings.swift b/Sources/MacroSIPApp/Model/Strings.swift index 4196fd8..2c91198 100644 --- a/Sources/MacroSIPApp/Model/Strings.swift +++ b/Sources/MacroSIPApp/Model/Strings.swift @@ -486,6 +486,19 @@ enum L { static var accountVerifyCertificateHelp: String { loc("account.field.verifyCertificate.help", "Turn off only for a server with a self-signed certificate.") } + static var accountIPProtocol: String { loc("account.field.ipProtocol", "IP protocol") } + static var accountIPProtocolHelp: String { + loc("account.field.ipProtocol.help", "Auto picks IPv4 or IPv6 from the server address.") + } + static var ipProtocolAuto: String { loc("account.ipProtocol.auto", "Auto") } + static var ipProtocolIPv4: String { loc("account.ipProtocol.ipv4", "IPv4 only") } + static var ipProtocolIPv6: String { loc("account.ipProtocol.ipv6", "IPv6 only") } + static var accountErrorIPv6Server: String { + loc("account.error.ipv6Server", "The server's address is an IPv6 address. Choose Auto or IPv6 only.") + } + static var accountErrorIPv4Server: String { + loc("account.error.ipv4Server", "The server's address is an IPv4 address. Choose Auto or IPv4 only.") + } // MARK: messages (SIP MESSAGE, screen 14) static var messagesNew: String { loc("messages.new", "New Message") } diff --git a/Sources/MacroSIPApp/Platform/AppInfo.swift b/Sources/MacroSIPApp/Platform/AppInfo.swift index 5b45baf..35ccb4d 100644 --- a/Sources/MacroSIPApp/Platform/AppInfo.swift +++ b/Sources/MacroSIPApp/Platform/AppInfo.swift @@ -55,7 +55,8 @@ extension AppModel { lines.append("Accounts (\(accounts.count)); passwords are in the Keychain and not listed") for a in accounts { let state = registration[a.id].map { String(describing: $0) } ?? "unknown" - var parts = ["\(a.username)@\(a.domain)", "transport=\(a.transport.rawValue)", "srtp=\(a.srtp.rawValue)", + var parts = ["\(a.username)@\(a.domain)", "transport=\(a.transport.rawValue)", "ip=\(a.ipProtocol.rawValue)", + "srtp=\(a.srtp.rawValue)", "enabled=\(a.enabled)", "register=\(a.registerWithServer)", "interval=\(a.registrationInterval)s", "presence=\(a.publishPresence)", "default=\(a.isDefaultOutgoing)", "tlsVerify=\(a.verifyTLSCertificate)"] if let r = a.registrar { parts.append("registrar=\(r)") } diff --git a/Sources/MacroSIPApp/Resources/en.lproj/Localizable.strings b/Sources/MacroSIPApp/Resources/en.lproj/Localizable.strings index 83270da..c1891d6 100644 --- a/Sources/MacroSIPApp/Resources/en.lproj/Localizable.strings +++ b/Sources/MacroSIPApp/Resources/en.lproj/Localizable.strings @@ -336,6 +336,13 @@ "account.field.publishPresence.help" = "Lets contacts who watch you see Available, Away or Do Not Disturb."; "account.field.verifyCertificate" = "Verify server certificate"; "account.field.verifyCertificate.help" = "Turn off only for a server with a self-signed certificate."; +"account.field.ipProtocol" = "IP protocol"; +"account.field.ipProtocol.help" = "Auto picks IPv4 or IPv6 from the server address."; +"account.ipProtocol.auto" = "Auto"; +"account.ipProtocol.ipv4" = "IPv4 only"; +"account.ipProtocol.ipv6" = "IPv6 only"; +"account.error.ipv6Server" = "The server's address is an IPv6 address. Choose Auto or IPv6 only."; +"account.error.ipv4Server" = "The server's address is an IPv4 address. Choose Auto or IPv4 only."; "unit.khz" = "%@ kHz"; "unit.kbps" = "%@ kbit/s"; "unit.percent" = "%@ %%"; diff --git a/Sources/MacroSIPApp/Resources/ru.lproj/Localizable.strings b/Sources/MacroSIPApp/Resources/ru.lproj/Localizable.strings index b948273..71ce85a 100644 --- a/Sources/MacroSIPApp/Resources/ru.lproj/Localizable.strings +++ b/Sources/MacroSIPApp/Resources/ru.lproj/Localizable.strings @@ -336,6 +336,13 @@ "account.field.publishPresence.help" = "Контакты, которые следят за вами, увидят «Доступен», «Отошёл» или «Не беспокоить»."; "account.field.verifyCertificate" = "Проверять сертификат сервера"; "account.field.verifyCertificate.help" = "Отключайте, только если у сервера самоподписанный сертификат."; +"account.field.ipProtocol" = "Протокол IP"; +"account.field.ipProtocol.help" = "«Авто» выбирает IPv4 или IPv6 по адресу сервера."; +"account.ipProtocol.auto" = "Авто"; +"account.ipProtocol.ipv4" = "Только IPv4"; +"account.ipProtocol.ipv6" = "Только IPv6"; +"account.error.ipv6Server" = "Адрес сервера — IPv6. Выберите «Авто» или «Только IPv6»."; +"account.error.ipv4Server" = "Адрес сервера — IPv4. Выберите «Авто» или «Только IPv4»."; "unit.khz" = "%@ кГц"; "unit.kbps" = "%@ кбит/с"; "unit.percent" = "%@ %%"; diff --git a/Sources/MacroSIPApp/Views/Settings/AccountEditorSheet.swift b/Sources/MacroSIPApp/Views/Settings/AccountEditorSheet.swift index ca34115..2cffb23 100644 --- a/Sources/MacroSIPApp/Views/Settings/AccountEditorSheet.swift +++ b/Sources/MacroSIPApp/Views/Settings/AccountEditorSheet.swift @@ -17,6 +17,7 @@ struct AccountEditorSheet: View { @Local private var domain = "" @Local private var proxy = "" @Local private var transport: TransportKind = .udp + @Local private var ipProtocol: IPProtocol = .auto @Local private var srtp: SRTPMode = .disabled @Local private var expiry = 300 @Local private var enabled = true @@ -48,10 +49,23 @@ struct AccountEditorSheet: View { private var serverValid: Bool { Self.isValidHost(server.trimmingCharacters(in: .whitespaces)) } private var expiryValid: Bool { (60...3600).contains(expiry) } - private var canTest: Bool { serverValid && !username.trimmingCharacters(in: .whitespaces).isEmpty && !password.isEmpty } + /// IPv4 only with an IPv6 server address, or the other way round (`IPFamilyPolicy.conflict`): the engine + /// would refuse the account, so Save and Test are off and the Connection group says why. + private var ipConflict: IPFamily? { serverValid ? IPFamilyPolicy.conflict(in: makeConfig()) : nil } + private var canTest: Bool { + serverValid && !username.trimmingCharacters(in: .whitespaces).isEmpty && !password.isEmpty && ipConflict == nil + } private var canSave: Bool { serverValid && !username.trimmingCharacters(in: .whitespaces).isEmpty && Self.passwordSufficient(password, registers: register) - && !name.trimmingCharacters(in: .whitespaces).isEmpty && expiryValid && !saving + && !name.trimmingCharacters(in: .whitespaces).isEmpty && expiryValid && ipConflict == nil && !saving + } + private var connectionError: String? { + if !expiryValid { return L.accountErrorExpiry } + switch ipConflict { + case .ipv6?: return L.accountErrorIPv6Server + case .ipv4?: return L.accountErrorIPv4Server + case nil: return nil + } } /// An account that registers needs a password; one that does not may have none. @@ -105,6 +119,9 @@ struct AccountEditorSheet: View { .onChange(of: expiryValid) { _, valid in if !valid { advancedOpen = true } // Save is off because of a field in the Advanced section: show it } + .onChange(of: ipConflict) { _, conflict in + if conflict != nil { advancedOpen = true } + } .alert(L.accountDeleteTitle(existing?.displayName ?? name), isPresented: $confirmDelete) { Button(L.commonCancel, role: .cancel) {} Button(L.commonDelete, role: .destructive) { @@ -133,13 +150,22 @@ struct AccountEditorSheet: View { TextField(L.accountProxyPlaceholder, text: $proxy).textFieldStyle(.roundedBorder).frame(width: 210) } } - FormGroup(header: L.accountGroupConnection, footer: expiryValid ? nil : L.accountErrorExpiry) { + FormGroup(header: L.accountGroupConnection, footer: connectionError) { row(L.accountTransport) { SegmentedTabs(items: TransportKind.allCases.map { .init(value: $0, title: $0.rawValue.uppercased()) }, selection: $transport) .frame(width: 170) } FormDivider() + row(L.accountIPProtocol, help: L.accountIPProtocolHelp) { + Picker("", selection: $ipProtocol) { + Text(L.ipProtocolAuto).tag(IPProtocol.auto) + Text(L.ipProtocolIPv4).tag(IPProtocol.ipv4) + Text(L.ipProtocolIPv6).tag(IPProtocol.ipv6) + } + .labelsHidden().frame(width: 130) + } + FormDivider() row(L.accountSRTP) { Picker("", selection: $srtp) { Text(L.srtpDisabled).tag(SRTPMode.disabled) @@ -199,7 +225,8 @@ struct AccountEditorSheet: View { static func advancedDiffersFromDefault(_ a: AccountConfig, callerName: String, accountCount: Int) -> Bool { let d = AccountConfig(displayName: "", username: "", domain: "") return !callerName.isEmpty || a.authID != nil || a.registrar != nil || a.outboundProxy != nil - || a.transport != d.transport || a.srtp != d.srtp || a.registrationInterval != d.registrationInterval + || a.transport != d.transport || a.ipProtocol != d.ipProtocol || a.srtp != d.srtp + || a.registrationInterval != d.registrationInterval || a.registerWithServer != d.registerWithServer || a.publishPresence != d.publishPresence || (a.transport == .tls && a.verifyTLSCertificate != d.verifyTLSCertificate) || (a.isDefaultOutgoing && accountCount > 1) @@ -304,6 +331,7 @@ struct AccountEditorSheet: View { password = model.vault.password(for: a.id) ?? "" proxy = a.outboundProxy ?? "" transport = a.transport + ipProtocol = a.ipProtocol srtp = a.srtp expiry = a.registrationInterval enabled = a.enabled || model.accountNeedsPassword(a.id) // imported: typing the password and saving switches it on @@ -332,6 +360,7 @@ struct AccountEditorSheet: View { let au = authUsername.trimmingCharacters(in: .whitespaces) cfg.authID = au.isEmpty ? nil : au cfg.transport = transport + cfg.ipProtocol = ipProtocol cfg.srtp = srtp cfg.enabled = enabled cfg.registerWithServer = register diff --git a/docs/design/SCREENS.md b/docs/design/SCREENS.md index b80669c..e995dfa 100644 --- a/docs/design/SCREENS.md +++ b/docs/design/SCREENS.md @@ -1173,10 +1173,10 @@ Only the basics are visible; everything else sits in a collapsible "Advanced" se |---|---|---| | 1 | Title | "Edit Account", 13 pt bold. | | 2 | Basics group | Account name, SIP server, Username, Password, Enabled. | -| 3 | Advanced (disclosure, label 13 pt semibold, collapsed by default) | Groups: Profile (Display name); Server (Auth username, Domain, Outgoing proxy); Connection (Transport, Media encryption (SRTP), Registration expiry, Verify server certificate with TLS); switches (Register with server, Default for outgoing calls, Publish my presence). | +| 3 | Advanced (disclosure, label 13 pt semibold, collapsed by default) | Groups: Profile (Display name); Server (Auth username, Domain, Outgoing proxy); Connection (Transport, IP protocol, Media encryption (SRTP), Registration expiry, Verify server certificate with TLS); switches (Register with server, Default for outgoing calls, Publish my presence). | | 4 | Button row | Delete Account…, Test, status text, Cancel, Save. | -**Advanced section:** closed for a new account and for an account whose advanced fields are all at their defaults (no display name, no auth username, domain equals the server, no proxy, UDP, SRTP disabled, expiry 300 s, Register on, not the default among several accounts, presence publishing off, certificate verification on). It opens by itself, so the user can see why an account behaves as it does, when any of them differs. The user's own open or close is remembered until the app quits and applies to the next editor. The sheet is 430 pt high while it is closed and 640 pt (470 pt in the main window) when open; the content scrolls. Validation and Test work whether it is open or not. +**Advanced section:** closed for a new account and for an account whose advanced fields are all at their defaults (no display name, no auth username, domain equals the server, no proxy, UDP, IP protocol Auto, SRTP disabled, expiry 300 s, Register on, not the default among several accounts, presence publishing off, certificate verification on). It opens by itself, so the user can see why an account behaves as it does, when any of them differs. The user's own open or close is remembered until the app quits and applies to the next editor. The sheet is 430 pt high while it is closed and 640 pt (470 pt in the main window) when open; the content scrolls. Validation and Test work whether it is open or not. ### Elements @@ -1193,6 +1193,7 @@ Rows of the basics group are listed first; the others are inside Advanced. | Domain (secondary "If empty, the SIP server is used.") | text field, placeholder shows "pbx.example.com" | Used to build SIP URIs. | No | empty | | Outgoing proxy | text field, placeholder "Optional, e.g. sip:proxy.example.com;lr" | Route set for requests. | No | empty | | Transport | segmented control: UDP, TCP, TLS | One value. | Yes | TLS in the mockup (default for new accounts: see Open items) | +| IP protocol (secondary "Auto picks IPv4 or IPv6 from the server address.") | popup, 130 pt | Auto, IPv4 only, IPv6 only (26.3.1). Auto: an IPv4 or IPv6 address picks its own protocol, a host name follows the order macOS returns. IPv4 only with an IPv6 server address (or the other way round) shows "The server's address is an IPv6 address. Choose Auto or IPv6 only." (or the IPv4 form) in the Connection group's footer, opens Advanced and keeps Save and Test off. The server here is the outgoing proxy when one is set. | Yes | Auto | | Media encryption (SRTP) | popup | Disabled, Optional, Mandatory (glossary modes). | Yes | Mandatory in the mockup | | Registration expiry | number field, 56 pt, stepper, unit "seconds" | Expiry in seconds. | Yes | 300 | | Voicemail number (secondary "Dialled from the menu bar and the status bar.") | text field, placeholder "*97" | Number or SIP URI the app dials for the voicemail items (menu bar, status bar badge). Group "Voicemail" in Advanced. | No | empty | @@ -1752,6 +1753,10 @@ Strings marked "(proposed)" are not in the mockups; they are needed by the spec | | UDP, TCP, TLS | `account.transport.udp`, `.tcp`, `.tls` | | | | Media encryption (SRTP) | `account.field.srtp` | | | | Disabled, Optional, Mandatory | `account.srtp.disabled`, `.optional`, `.mandatory` | Glossary modes. | +| | IP protocol | `account.field.ipProtocol` | 26.3.1. | +| | Auto picks IPv4 or IPv6 from the server address. | `account.field.ipProtocol.help` | | +| | Auto, IPv4 only, IPv6 only | `account.ipProtocol.auto`, `.ipv4`, `.ipv6` | | +| | The server's address is an IPv6 address. Choose Auto or IPv6 only. | `account.error.ipv6Server` | Validation; `account.error.ipv4Server` is the IPv4 form. | | | Registration expiry | `account.field.expiry` | | | | Register with server | `account.field.register` | | | | Off keeps the account for outgoing calls only. | `account.field.register.help` | | From 9f7ec145e97b56d5a9df4dff7330b34ead705587 Mon Sep 17 00:00:00 2001 From: HSMM Date: Mon, 9 Nov 2026 13:14:31 +0300 Subject: [PATCH 03/12] 26.3.1: version, roadmap and READMEs for IPv6 --- README.md | 1 + README.ru.md | 1 + Sources/MacroSIPCore/Product.swift | 2 +- docs/ROADMAP.md | 2 ++ 4 files changed, 5 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 513e336..4549f0f 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,7 @@ Messages: the conversation list, and a conversation open: - Several SIP accounts registered at once; UDP, TCP and TLS with certificate verification; SRTP; STUN and ICE; outgoing-only accounts; each account switched on or off in the account pop-up; search and a status summary when there are many. Passwords are kept in the Keychain. - An account on a server addressed by a private IP address (10.x, 172.16-31.x, 192.168.x, 100.64-127.x, on the LAN or over a VPN) does not use STUN, so the first REGISTER carries the Mac's own address. +- IPv6 next to IPv4: SIP over UDP, TCP and TLS and the audio over IPv6, for a server given by an IPv6 address or by a host name with IPv6 (AAAA) records. Per account, IP protocol Auto (an IP address picks its own protocol, a host name follows the order macOS returns), IPv4 only or IPv6 only. Over IPv6 there is no STUN and no ICE (plain RTP). - After a network drop, an IP change or sleep the accounts register again at once, with backoff while the network is down; a running call survives an IP change. The status bar and the call window show "No network" and "Reconnecting…". - Network pane: RTP port range, rport, DNS SRV with a custom nameserver. - Codecs: Opus (with FEC and DTX), G.722, G.711 and, off until you turn them on, G.722.1, GSM, iLBC and Speex. diff --git a/README.ru.md b/README.ru.md index 257dc2a..c6c00e7 100644 --- a/README.ru.md +++ b/README.ru.md @@ -93,6 +93,7 @@ Electron и Qt. Одно небольшое окно, значок в строк - Несколько SIP-аккаунтов с одновременной регистрацией; UDP, TCP и TLS с проверкой сертификата; SRTP; STUN и ICE; аккаунты «только исходящие»; каждый аккаунт включается и выключается в меню аккаунтов; поиск и сводка состояния, когда аккаунтов много. Пароли хранятся в связке ключей. - Аккаунт на сервере с частным IP-адресом (10.x, 172.16–31.x, 192.168.x, 100.64–127.x, в локальной сети или через VPN) не использует STUN: первый REGISTER несёт собственный адрес Mac. +- IPv6 наряду с IPv4: SIP по UDP, TCP и TLS и звук по IPv6 для сервера, заданного IPv6-адресом или именем хоста с IPv6-записями (AAAA). У каждого аккаунта протокол IP: «Авто» (IP-адрес сам задаёт протокол, для имени хоста — порядок, который выдаёт macOS), «Только IPv4» или «Только IPv6». По IPv6 нет STUN и ICE (обычный RTP). - После обрыва сети, смены IP или сна аккаунты сразу регистрируются заново, пока сети нет, попытки повторяются с нарастающей паузой; идущий разговор переживает смену IP. В строке состояния и в окне звонка видны «Нет сети» и «Переподключение…». - Раздел «Сеть»: диапазон портов RTP, rport, DNS SRV с собственным сервером имён. - Кодеки: Opus (с FEC и DTX), G.722, G.711 и, выключенные до включения вами, G.722.1, GSM, iLBC и Speex. diff --git a/Sources/MacroSIPCore/Product.swift b/Sources/MacroSIPCore/Product.swift index 365faa0..485e068 100644 --- a/Sources/MacroSIPCore/Product.swift +++ b/Sources/MacroSIPCore/Product.swift @@ -14,5 +14,5 @@ public enum Product { return fallbackVersion }() - public static let fallbackVersion = "26.3.0" + public static let fallbackVersion = "26.3.1" } diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 0b5ff35..ffe8f88 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -77,6 +77,8 @@ App: - Messages are off until switched on in Settings › General ([#8](https://github.com/HSMM/MacroSIP/issues/8)): with the switch off there is no Messages tab, no Send Message item, no notification and no sound, and incoming `MESSAGE` requests are dropped with a log line. - The ringtone chosen in Settings › Audio reaches the engine ([#7](https://github.com/HSMM/MacroSIP/issues/7)): Classic, Digital and Soft are three different melodies, a custom AIFF, M4A or MP3 file is converted to WAV once and reused, a file that cannot be read keeps the previous choice and says why, and the preview plays the real choice at the chosen volume. +`26.3.1` (not released yet): IPv6 ([#11](https://github.com/HSMM/MacroSIP/issues/11)). SIP over UDP, TCP and TLS and the audio over IPv6 next to IPv4, for a server given by an IPv6 address or by a host name with AAAA records; an account at `[2001:db8::1]` no longer retries forever. Account editor › Advanced › IP protocol: Auto (an IP address picks its own protocol, a host name follows the order macOS returns; decided again after a network change), IPv4 only, IPv6 only. IPv6 accounts use no STUN and no ICE (plain RTP: PJSIP 2.17 cannot open its IPv6 ICE socket on macOS). Tested on loopback only; a real IPv6 PBX and network are not verified. + ## Later - Developer ID signing and notarization, so the first launch needs no workaround (when the signing identity is available). From c1b9c7465b568cdb73497084b48cdd3b737d8bf7 Mon Sep 17 00:00:00 2001 From: HSMM Date: Mon, 9 Nov 2026 14:08:55 +0300 Subject: [PATCH 04/12] Tests: find the Testing framework with newer Command Line Tools --- docs/DEVELOPMENT.md | 2 +- scripts/test.sh | 25 ++++++++++++++++++++++--- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index d69cdd3..c8a4ebd 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -23,7 +23,7 @@ Built on an Apple Silicon Mac; the x86_64 half is cross-compiled (ADR 0012). - Every `pjsua_*` call that can fail returns `pj_status_t`; check it and surface the error text via `pj_strerror`. - Passwords live only in Keychain. Everything else is JSON in `~/Library/Application Support/MacroSIP/`. - Strings: see "Localization" below. English is the base; Russian is maintained alongside; a new string is not done until both languages have it. -- Run tests with `scripts/test.sh`, never bare `swift test` (it cannot find the Testing macro plugin under Command Line Tools). A milestone is done only after: `swift build` clean, tests green, `scripts/selftest-call.sh` passes, and a real call verified (pjsua CLI as the second phone, or the owner's SIP account). +- Run tests with `scripts/test.sh`, never bare `swift test` (it cannot find the Testing macro plugin under Command Line Tools, and with Command Line Tools 26.4 / Swift 6.3 not even the Testing module: when a probe compile cannot import it, the script adds the toolchain's `Library/Developer/Frameworks` and `Library/Developer/usr/lib` as search paths and rpaths; Xcode toolchains, as on CI, are left as they are). A milestone is done only after: `swift build` clean, tests green, `scripts/selftest-call.sh` passes, and a real call verified (pjsua CLI as the second phone, or the owner's SIP account). - Commit after each working milestone and push to `main`. - SwiftUI `@State` does not compile under Command Line Tools (its macro plugin ships only with Xcode). Use the `@Local` wrapper from `Sources/MacroSIPApp/Views/Components/Local.swift`; it is a drop-in for `@State`. - Opus and OpenSSL are built from pinned sources by `scripts/build-pjsip.sh` and linked as universal static archives from `third_party/deps/universal/lib` (Package.swift), so the .app has no dylib dependencies outside the system; never switch them to `.linkedLibrary` or to Homebrew. No Homebrew packages are needed to build. diff --git a/scripts/test.sh b/scripts/test.sh index a646f38..4506628 100755 --- a/scripts/test.sh +++ b/scripts/test.sh @@ -1,9 +1,28 @@ #!/usr/bin/env bash # Run the Swift Testing suites. Usage: scripts/test.sh [extra swift test args] # Command Line Tools ship the Testing framework but SwiftPM does not find its -# macro plugin on its own, so the plugin path is passed explicitly. +# macro plugin on its own, so the plugin path is passed explicitly. Newer Command +# Line Tools (26.4, Swift 6.3) do not find the Testing module either: when a probe +# compile cannot import it and the toolchain has Testing.framework, the framework +# and its interop library are passed too (search paths and rpaths). Xcode +# toolchains keep the framework elsewhere and are left as they are. set -euo pipefail cd "$(dirname "$0")/.." -PLUGINS="$(xcrun --find swiftc | sed 's|/usr/bin/swiftc$||')/usr/lib/swift/host/plugins/testing" +TOOLCHAIN="$(xcrun --find swiftc | sed 's|/usr/bin/swiftc$||')" +PLUGINS="$TOOLCHAIN/usr/lib/swift/host/plugins/testing" +EXTRA=() +FRAMEWORKS="$TOOLCHAIN/Library/Developer/Frameworks" +if [ -d "$FRAMEWORKS/Testing.framework" ]; then + PROBE="$(mktemp -d)" + echo 'import Testing' > "$PROBE/probe.swift" + if ! xcrun swiftc -typecheck "$PROBE/probe.swift" >/dev/null 2>&1; then + echo "==> Testing module not found by default; using $FRAMEWORKS" + EXTRA=(-Xswiftc -F -Xswiftc "$FRAMEWORKS" -Xlinker -F -Xlinker "$FRAMEWORKS" + -Xlinker -rpath -Xlinker "$FRAMEWORKS") + INTEROP="$TOOLCHAIN/Library/Developer/usr/lib" + if [ -d "$INTEROP" ]; then EXTRA+=(-Xlinker -rpath -Xlinker "$INTEROP"); fi + fi + rm -rf "${PROBE:?}" +fi echo "==> swift test" -swift test -Xswiftc -plugin-path -Xswiftc "$PLUGINS" ${@+"$@"} +swift test -Xswiftc -plugin-path -Xswiftc "$PLUGINS" ${EXTRA[@]+"${EXTRA[@]}"} ${@+"$@"} From d9c13815df2df92f8ba5a694277225311bca6c9d Mon Sep 17 00:00:00 2001 From: HSMM Date: Mon, 9 Nov 2026 14:15:47 +0300 Subject: [PATCH 05/12] PJSIP: patch the IPv6 ICE bind address so ICE works over IPv6 --- .github/workflows/ci.yml | 2 +- .github/workflows/release.yml | 2 +- README.md | 2 +- README.ru.md | 2 +- .../MacroSIPCore/Engine/AccountMapping.swift | 7 ++-- .../MacroSIPCore/Engine/Engine+Accounts.swift | 3 -- Tests/MacroSIPCoreTests/EngineIPv6Tests.swift | 34 ++++++++++++------- docs/DEVELOPMENT.md | 4 +-- docs/ENGINE.md | 4 +-- docs/ROADMAP.md | 2 +- docs/adr/0014-ipv6-dual-stack.md | 17 ++++++---- scripts/README-build.md | 25 +++++++++++--- scripts/build-pjsip.sh | 25 ++++++++++++-- .../0001-ipv6-ice-bind-any.patch | 33 ++++++++++++++++++ 14 files changed, 120 insertions(+), 42 deletions(-) create mode 100644 scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3f48fc1..6313a1a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,7 +42,7 @@ jobs: path: | third_party/pjsip third_party/deps - key: pjsip-universal-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/build-pjsip.sh', 'third_party/pjsip/config_site.h') }} + key: pjsip-universal-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/build-pjsip.sh', 'third_party/pjsip/config_site.h', 'scripts/pjsip-patches/**') }} - name: Build PJSIP, OpenSSL and Opus (arm64 + x86_64, universal) run: | diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3770987..8335785 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -58,7 +58,7 @@ jobs: path: | third_party/pjsip third_party/deps - key: pjsip-universal-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/build-pjsip.sh', 'third_party/pjsip/config_site.h') }} + key: pjsip-universal-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/build-pjsip.sh', 'third_party/pjsip/config_site.h', 'scripts/pjsip-patches/**') }} - name: Build PJSIP, OpenSSL and Opus (arm64 + x86_64, universal) run: | diff --git a/README.md b/README.md index 4549f0f..79fb2d6 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,7 @@ Messages: the conversation list, and a conversation open: - Several SIP accounts registered at once; UDP, TCP and TLS with certificate verification; SRTP; STUN and ICE; outgoing-only accounts; each account switched on or off in the account pop-up; search and a status summary when there are many. Passwords are kept in the Keychain. - An account on a server addressed by a private IP address (10.x, 172.16-31.x, 192.168.x, 100.64-127.x, on the LAN or over a VPN) does not use STUN, so the first REGISTER carries the Mac's own address. -- IPv6 next to IPv4: SIP over UDP, TCP and TLS and the audio over IPv6, for a server given by an IPv6 address or by a host name with IPv6 (AAAA) records. Per account, IP protocol Auto (an IP address picks its own protocol, a host name follows the order macOS returns), IPv4 only or IPv6 only. Over IPv6 there is no STUN and no ICE (plain RTP). +- IPv6 next to IPv4: SIP over UDP, TCP and TLS and the audio over IPv6, for a server given by an IPv6 address or by a host name with IPv6 (AAAA) records. Per account, IP protocol Auto (an IP address picks its own protocol, a host name follows the order macOS returns), IPv4 only or IPv6 only. Over IPv6 there is no STUN; ICE works over IPv6 too. - After a network drop, an IP change or sleep the accounts register again at once, with backoff while the network is down; a running call survives an IP change. The status bar and the call window show "No network" and "Reconnecting…". - Network pane: RTP port range, rport, DNS SRV with a custom nameserver. - Codecs: Opus (with FEC and DTX), G.722, G.711 and, off until you turn them on, G.722.1, GSM, iLBC and Speex. diff --git a/README.ru.md b/README.ru.md index c6c00e7..8881354 100644 --- a/README.ru.md +++ b/README.ru.md @@ -93,7 +93,7 @@ Electron и Qt. Одно небольшое окно, значок в строк - Несколько SIP-аккаунтов с одновременной регистрацией; UDP, TCP и TLS с проверкой сертификата; SRTP; STUN и ICE; аккаунты «только исходящие»; каждый аккаунт включается и выключается в меню аккаунтов; поиск и сводка состояния, когда аккаунтов много. Пароли хранятся в связке ключей. - Аккаунт на сервере с частным IP-адресом (10.x, 172.16–31.x, 192.168.x, 100.64–127.x, в локальной сети или через VPN) не использует STUN: первый REGISTER несёт собственный адрес Mac. -- IPv6 наряду с IPv4: SIP по UDP, TCP и TLS и звук по IPv6 для сервера, заданного IPv6-адресом или именем хоста с IPv6-записями (AAAA). У каждого аккаунта протокол IP: «Авто» (IP-адрес сам задаёт протокол, для имени хоста — порядок, который выдаёт macOS), «Только IPv4» или «Только IPv6». По IPv6 нет STUN и ICE (обычный RTP). +- IPv6 наряду с IPv4: SIP по UDP, TCP и TLS и звук по IPv6 для сервера, заданного IPv6-адресом или именем хоста с IPv6-записями (AAAA). У каждого аккаунта протокол IP: «Авто» (IP-адрес сам задаёт протокол, для имени хоста — порядок, который выдаёт macOS), «Только IPv4» или «Только IPv6». По IPv6 нет STUN; ICE работает и по IPv6. - После обрыва сети, смены IP или сна аккаунты сразу регистрируются заново, пока сети нет, попытки повторяются с нарастающей паузой; идущий разговор переживает смену IP. В строке состояния и в окне звонка видны «Нет сети» и «Переподключение…». - Раздел «Сеть»: диапазон портов RTP, rport, DNS SRV с собственным сервером имён. - Кодеки: Opus (с FEC и DTX), G.722, G.711 и, выключенные до включения вами, G.722.1, GSM, iLBC и Speex. diff --git a/Sources/MacroSIPCore/Engine/AccountMapping.swift b/Sources/MacroSIPCore/Engine/AccountMapping.swift index fbb7829..f8e0258 100644 --- a/Sources/MacroSIPCore/Engine/AccountMapping.swift +++ b/Sources/MacroSIPCore/Engine/AccountMapping.swift @@ -210,10 +210,9 @@ enum AccountMapping { allowContactRewrite: true, allowViaRewrite: true, keepAliveSeconds: max(0, network.keepAliveSeconds), - // Not over IPv6: pjsua binds the IPv6 ICE component to "0", which macOS getaddrinfo turns - // into ::ffff:0.0.0.0, so that socket fails (EADDRNOTAVAIL) and the offer would carry IPv4 - // candidates only, then fail on an IPv6 answer (PJ_EAFNOTSUP). Plain RTP works over IPv6. - iceEnabled: network.useICE && family == .ipv4, + // Over IPv6 too: our PJSIP patch binds the IPv6 ICE component to "::" (pjsua's "0" became + // ::ffff:0.0.0.0 on macOS and could not be bound; scripts/pjsip-patches). + iceEnabled: network.useICE, sipSTUN: stun, mediaSTUN: stun, sdpNATRewrite: !stun, diff --git a/Sources/MacroSIPCore/Engine/Engine+Accounts.swift b/Sources/MacroSIPCore/Engine/Engine+Accounts.swift index f8405b0..6f037a4 100644 --- a/Sources/MacroSIPCore/Engine/Engine+Accounts.swift +++ b/Sources/MacroSIPCore/Engine/Engine+Accounts.swift @@ -158,9 +158,6 @@ extension Engine { private func logFamily(_ cfg: AccountConfig, _ family: IPFamily) { let how = cfg.ipProtocol == .auto ? "auto" : "\(cfg.ipProtocol.rawValue) only" emit(.log(level: 4, "engine: account \(cfg.uri): \(family) (\(how), server \(IPFamilyPolicy.firstHop(of: cfg).host))")) - if family == .ipv6 && network.useICE { - emit(.log(level: 3, "engine: account \(cfg.uri): ICE is not used over IPv6; calls use plain RTP")) - } } /// Decides the family of an Auto account with a host name again (network change, REGISTER retry). diff --git a/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift b/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift index a8c3100..83ff020 100644 --- a/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift +++ b/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift @@ -951,31 +951,39 @@ extension EngineTests { await engine.stop() } - /// ICE is not used over IPv6 (docs/ENGINE.md "IPv6": PJSIP 2.17 cannot open the IPv6 ICE socket on - /// macOS, and an offer with IPv4 candidates only fails on an IPv6 answer). With ICE on, an IPv6 - /// account offers plain IPv6 media without candidates and the call connects; an IPv4 account on - /// the same engine still offers ICE candidates. - @Test func iceIsNotUsedOverIPv6() async throws { + /// With ICE on (PJSIP patched: scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch), an IPv6 call + /// gathers IPv6 host candidates: the offer is `c=IN IP6` with an IPv6 default candidate, lists IPv6 + /// `typ host` candidates (and IPv4 ones from pjsua's second component), and the call to a peer + /// without ICE connects with RTP over IPv6. Without the patch the IPv6 ICE socket could not be + /// bound ("::ffff:0.0.0.0") and the offer had IPv4 candidates only. pjnath leaves out ::1 (and + /// link-local addresses other than the default one), so the IPv6 candidate is the Mac's default + /// IPv6 address: link-local or global, never loopback. + @Test func iceGathersIPv6CandidatesOverIPv6() async throws { let stub = try IPv6Stub() defer { stub.stop() } - let engine = await makeEngine(bindAddress: "::1") + let engine = await makeEngine(bindAddress: nil) var net = Self.network net.useICE = true try await engine.start(network: net) let account = localIPv6Account("ice") try await engine.addAccount(account, password: "") let live = try #require(await engine.liveAccountSettingsForTests(account.id)) - #expect(!live.iceEnabled && live.mediaIPv6Only) + #expect(live.iceEnabled && live.mediaIPv6Only) let call = try await engine.makeCall(to: DialString(uri: "sip:300@[::1]:\(stub.port)", display: "300"), from: account.id) - #expect(await waitUntil { await engine.calls().first { $0.id == call }?.state == .connected }) + #expect(await waitUntil(timeout: 8) { await engine.calls().first { $0.id == call }?.state == .connected }) let offer = try #require(stub.requests.first { $0.method == "INVITE" }).body - #expect(sdpConnection(offer) == "IN IP6 ::1", "\(offer)") - #expect(!offer.contains("a=candidate:"), "\(offer)") + let connection = sdpConnection(offer) + #expect(connection.hasPrefix("IN IP6 "), "\(offer)") + let hosts = offer.components(separatedBy: "\r\n").filter { $0.hasPrefix("a=candidate:") }.compactMap { line -> String? in + let f = line.split(separator: " ") + return f.count > 7 && f[7] == "host" ? String(f[4]) : nil + } + #expect(hosts.contains { $0.contains(":") }, "IPv6 host candidates: \(hosts)") + #expect(hosts.contains(String(connection.dropFirst("IN IP6 ".count))), "default \(connection), hosts \(hosts)") + #expect(await waitUntil { ((try? await engine.mediaStats(call))?.txPackets ?? 0) > 10 }) + #expect(await engine.localRTPAddress(of: call).contains(":")) try await engine.hangup(call) #expect(await waitUntil { await engine.calls().isEmpty }) - let mapped = try AccountMapping.settings(for: AccountConfig(displayName: "", username: "1", domain: "pbx.example.com"), - password: "", network: net, transports: TransportIDs(udp: 0), family: .ipv4) - #expect(mapped.iceEnabled) await engine.stop() } } diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index c8a4ebd..c548651 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -15,7 +15,7 @@ Built on an Apple Silicon Mac; the x86_64 half is cross-compiled (ADR 0012). - `Sources/MacroSIPCore` — Swift engine: accounts, calls, presence, recording, storage. No UI imports. - `Sources/MacroSIPApp` — SwiftUI/AppKit app. - `Tests/` — Swift Testing (`import Testing`) for Core; XCTest is unavailable with Command Line Tools only. -- `scripts/` — `build-pjsip.sh`, `make-app.sh`, `make-dmg.sh`, `make-appcast.sh`, `publish-appcast.sh`, `make-icon.swift`, `update-cask.sh`, `test.sh`, `selftest-call.sh`, `check-strings.sh`. `third_party/` holds the PJSIP, OpenSSL and Opus builds (git-ignored except `pjsip/config_site.h`; layout in `scripts/README-build.md`). +- `scripts/` — `build-pjsip.sh`, `make-app.sh`, `make-dmg.sh`, `make-appcast.sh`, `publish-appcast.sh`, `make-icon.swift`, `update-cask.sh`, `test.sh`, `selftest-call.sh`, `check-strings.sh`. `third_party/` holds the PJSIP, OpenSSL and Opus builds (git-ignored except `pjsip/config_site.h`; layout in `scripts/README-build.md`); `scripts/pjsip-patches/` holds our patches to pjproject, which `build-pjsip.sh` applies (ADR 0014). ## Rules - One product, one build: `MacroSIP`, bundle id `com.hsmm.macrosip` (ADR 0003). No build flags for features. @@ -71,7 +71,7 @@ Built on an Apple Silicon Mac; the x86_64 half is cross-compiled (ADR 0012). - **App icon**: `swift scripts/make-icon.swift` draws the icon (source of truth: `packaging/AppIcon.svg`, a dial pad whose pressed keys trace an M on a green gradient) into `packaging/AppIcon.icns` and `AppIcon-1024.png`; run `swift scripts/make-icon.swift` after changing the artwork. - **DMG**: `scripts/make-dmg.sh [release]` builds the app and writes `dist/MacroSIP-.dmg` (universal; volume "MacroSIP", Applications symlink, ad-hoc signed, no notarization). - **Updates** (ADR 0013): Sparkle 2.7.3 (SwiftPM binary XCFramework, pinned exactly). `Platform/Updater.swift` wraps `SPUStandardUpdaterController`; it starts in `applicationDidFinishLaunching` except for `--mock-engine`, demo launches and a binary outside an .app (`swift run`), where Settings › General › Updates is disabled with a note. `make-app.sh` copies `Sparkle.framework` into `Contents/Frameworks`, signs its XPC services, `Autoupdate`, `Updater.app` and the framework before the app, and writes `SUFeedURL` (`https://raw.githubusercontent.com/HSMM/MacroSIP/gh-pages/appcast.xml`), `SUPublicEDKey`, `SUEnableAutomaticChecks` and `SUScheduledCheckInterval` (24 h) into Info.plist. With "Check for updates automatically" on, `Updater.checkAtLaunch` also runs `checkForUpdatesInBackground()` 8 s after the start (no window unless an update exists; Sparkle ignores it while a session is in progress), besides Sparkle's own daily schedule. Release candidates are appcast items on the `beta` channel; the "Include release candidates" toggle (UserDefaults `updates.includeReleaseCandidates`) decides `allowedChannels`. Sparkle's tools (`generate_keys`, `generate_appcast`, `sign_update`) are in `.build/artifacts/sparkle/Sparkle/bin` after `swift build`. -- **CI**: `.github/workflows/ci.yml` (push and PR to main). Job `build` on `macos-15` (arm64): `build-pjsip.sh` with `third_party/pjsip` and `third_party/deps` cached (key: hash of the script and `config_site.h`), build, tests, selftest natively and the x86_64 slice under Rosetta 2, universal release app as artifact. Job `intel` on `macos-15-intel` (x86_64) takes the universal libraries and the app from `build`, launches the app for 15 s, and runs `swift build`, `scripts/test.sh` and `scripts/selftest-call.sh` natively. `release.yml` runs on tags `[0-9]*.[0-9]*.[0-9]*` and builds the same universal DMG on arm64 (with the Rosetta selftest). +- **CI**: `.github/workflows/ci.yml` (push and PR to main). Job `build` on `macos-15` (arm64): `build-pjsip.sh` with `third_party/pjsip` and `third_party/deps` cached (key: hash of the script, `config_site.h` and `scripts/pjsip-patches/`), build, tests, selftest natively and the x86_64 slice under Rosetta 2, universal release app as artifact. Job `intel` on `macos-15-intel` (x86_64) takes the universal libraries and the app from `build`, launches the app for 15 s, and runs `swift build`, `scripts/test.sh` and `scripts/selftest-call.sh` natively. `release.yml` runs on tags `[0-9]*.[0-9]*.[0-9]*` and builds the same universal DMG on arm64 (with the Rosetta selftest). - **Headset buttons** (USB/HID call control): `Platform/HeadsetButtons.swift` watches HID devices through `IOHIDManager` (`import IOKit.hid`): top-level collections on the Telephony page (0x0B: Headset 0x05, Telephony 0x01, Handset 0x04) and Consumer Control devices (0x0C/0x01) that carry Telephony elements (a keyboard's media keys and the 3.5 mm jack's "Headset" have none and are ignored). The manager only enumerates; each telephony device is opened on its own (`IOHIDDeviceOpen`), so no keyboard-class device is touched. A Telephony-page collection opens without a prompt; a device that exposes its telephony controls only inside a Consumer Control collection may be refused by macOS (Input Monitoring): the failure is logged (`headset buttons: cannot open ...`) and the device ignored. That case has not been tested on real hardware. Input usages: Hook Switch 0x0B/0x20, Flash 0x21, Hold 0x23, Redial 0x24, Drop 0x26, Phone Mute 0x2F; `HeadsetReportDecoder` (pure, no IOKit) turns them into `HeadsetEvent`s. The hook switch comes as a level (1 off-hook, 0 on-hook; "no preferred state" in the descriptor) or as a momentary button ("preferred state"); a switch that releases within 300 ms is treated as a button from then on, and so is one whose release arrives within 1 s of the call its off-hook answered (`HeadsetButtons.callAnswered` from `AppModel+Headset.swift`), so a long first press cannot answer and hang up in one go. `AppModel+Headset.swift` maps them: off-hook or a hook press answers the ringing call (the active one goes on hold), on-hook ends the active call, a hook press with no call ringing hangs up the current one, Flash answers the waiting call or swaps the held one in, Phone Mute toggles the current call's microphone, Redial calls the last outgoing number when no call exists. The LEDs Off-Hook (0x08/0x17), Ring (0x08/0x18) and Mute (0x08/0x09) are written as output reports when the device has them, from `afterCallsChanged` (`syncHeadsetIndicators`), so the headset follows the call state and level-type devices reset their hook after a remote hang-up. IOKit callbacks run on the controller's private queue; events and the device name hop to the main actor. `AppModel.headsetButtonsEnabled` (default on, `setHeadsetButtonsEnabled(_:)` starts and stops the controller) and `headsetButtonsDevice` (name of the connected device, nil when none, for the UI) are the API for Settings. Hot-plug is logged (`headset buttons: connected, hook button|switch, controls ...`, `... disconnected`) in the `app` category. Demo launches never open IOKit; `HeadsetButtons.simulate(_:)` (DEBUG) injects events and `--demo-state selftest` checks the decoder, answer/hang-up/mute/redial and the LED state through it. Out of scope: Bluetooth headsets whose buttons speak HFP (AT commands) rather than HID; macOS handles those itself and they do not appear as HID telephony devices. diff --git a/docs/ENGINE.md b/docs/ENGINE.md index a6d25be..25a7b6c 100644 --- a/docs/ENGINE.md +++ b/docs/ENGINE.md @@ -387,10 +387,10 @@ Dual stack since 26.3.1 ([#11](https://github.com/HSMM/MacroSIP/issues/11), ADR - **Decided again** (`refreshAccountFamily`) for Auto accounts with a host name (not the SRV case) at the start of every network-change round (before `cpjsua_acc_prepare_ip_change`) and before every REGISTER retry. When the family changed, the account is `pjsua_acc_modify`d onto the other family's transport without a REGISTER (`disable_reg_on_modify`); pjsua destroys its registration session, the round or the retry registers it afresh with a new Contact, and the registrar's requests are trusted again only after it accepted that REGISTER (`setRegistrarSource(nil)`). A call in progress keeps its dialog; the round re-INVITEs it like any call, and it may not survive a change of family (a move from an IPv4 network to an IPv6-only one cannot keep an IPv4 call anyway). A changed IP protocol goes through `updateAccount` (`pjsua_acc_modify`), without a restart. - **Media.** IPv6 accounts set `ipv6_media_use = PJSUA_IPV6_ENABLED_USE_IPV6_ONLY`: `get_media_ip_version` (pjsua_media.c) counts `::1`, link-local and a missing global address as "available" but not "usable", so PREFER_IPV6 would offer IPv4 on loopback and on a Mac without a global IPv6 address. The offer is `c=IN IP6` with IPv6 RTP sockets. An incoming offer is answered in its own family: an `IN IP4` offer to an IPv6 account gets an IPv4 answer and IPv4 RTP (with an IPv6 bind address that socket cannot be bound and the call fails). IPv4 accounts keep pjsua's default (PREFER_IPV4): IPv4 offers, and an `IN IP6` offer is answered with IPv6, as before. `localRTPAddress(of:)` reports the RTP address (diagnostics, tests). - **No STUN over IPv6.** IPv6 accounts have `sip_stun_use` and `media_stun_use` disabled (STUN and TURN over IPv6 are out of scope; pjsua maps IPv4 only) and `allow_sdp_nat_rewrite` on, so after the first REGISTER answer the SDP carries the address the registrar saw (with temporary addresses, the one actually used) instead of `pj_gethostip`'s pick. -- **No ICE over IPv6** (deviation from the plan). With ICE on, pjsua gives an IPv6 call an IPv6 ICE component bound to the string "0" (`IN6_ADDR_ANY` in `create_ice_media_transport`), which macOS `getaddrinfo` turns into `::ffff:0.0.0.0`; binding a V6ONLY socket to that fails ("Failed creating STUN transport #1 for comp 1: Can't assign requested address"), so the offer carried IPv4 host candidates and `c=IN IP4` only, and an IPv6 answer then failed the call (`pjmedia_stream_info_from_sdp`: PJ_EAFNOTSUP). IPv6 accounts therefore have ICE off (`iceEnabled = useICE && family == .ipv4`) and use plain RTP; a level 3 line says so when ICE is on. The fix belongs in PJSIP (bind the IPv6 component to "::"), which needs a patched pjsua_media.c and a rebuild; not done. +- **ICE over IPv6** (with a PJSIP patch). pjsua gives an IPv6 call an IPv6 ICE component (`create_ice_media_transport`: `ice_cfg.af = AF_INET6` and a second STUN transport of family IPv6) bound to the string "0" (`IN6_ADDR_ANY`). macOS `getaddrinfo` turns "0" into `::ffff:0.0.0.0`, and binding a V6ONLY socket to that fails ("Failed creating STUN transport #1 for comp 1: Can't assign requested address"): the offer then had IPv4 candidates and `c=IN IP4` only, and an IPv6 answer failed the call (`pjmedia_stream_info_from_sdp`: PJ_EAFNOTSUP). `scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch` (applied by `build-pjsip.sh`, see scripts/README-build.md) makes it "::" in both places (STUN and TURN transports). An IPv6 call with ICE now offers `c=IN IP6` with the IPv6 default candidate, IPv6 and IPv4 host candidates (pjsua adds an IPv4 STUN transport as well), and connects. pjnath leaves out `::1` (`loop_addr` is off) and every link-local address but the default one, so on a Mac without a global IPv6 address the only IPv6 candidate is link-local (`fe80::…`, its zone is not carried in SDP); between two ICE endpoints on this Mac those checks fail and ICE nominates an IPv4 pair (checked by hand on loopback). An IPv6 pair winning needs a global IPv6 address: not verified. - **Incoming.** Requests over UDP6, TCP6 and TLS6 reach the account bound to that transport: an IPv4 and an IPv6 account with the same user and domain each get the calls and messages of their own family. `SignallingSource` compares IPv6 addresses in any spelling (`[2001:DB8:0::1]` is `2001:db8::1`), so the registrar-source trust (answer-after) works over IPv6. - **Network changes.** `NetworkPath.address6` is the source address of the default IPv6 route (a UDP socket connected to 2001:db8::1, nothing sent; link-local and loopback do not count) and part of the primary route, so a new global IPv6 address, for example a new preferred temporary address, starts a round when NWPathMonitor reports an update (see "Network resilience") while an account is bound to IPv6, and so does IPv6 appearing (an Auto host name may resolve to IPv6 first now). Without IPv6 accounts a new IPv6 address alone starts no round: it changes nothing for them, and a round would end a ringing outgoing call (pjsua's 410). `pjsua_handle_ip_change` with `restart_listener` restarts every listener, the IPv6 ones included (all `tpdata`), and recomputes their published addresses. -- **Tests.** `EngineIPv6Tests.swift` with `IPv6Stub` (UDP and TCP on `[::1]`, optionally UDP on 127.0.0.1 with the same port; answers REGISTER and INVITE with `IN IP6 ::1`, records family, transport, Via, Contact and bodies; sends INVITE with an IPv6 or IPv4 offer and MESSAGE). Values: old JSON decodes as Auto (unknown values too), literals, first hop, contradictions, the decision with a fake resolver (literals, fixed families, resolver order, offline, availability, SRV), `IPFamilyResolver.system` against `getaddrinfo`, mapping by family and its read-back from `pjsua_acc_config` (transport id, `ipv6_media_use`, STUN, bind address), transport ids, IPv6 registrar-source comparison, `NetworkPath.address6`. pjsua: `bindAddressDecidesTransportFamilies`; `ipv6TransportFailureIsNotFatal` (`[::]:P` held by another socket: the engine starts with IPv4 UDP and TCP6 on P and refuses IPv6 UDP accounts; released, both UDP transports use P); `contradictoryIPProtocolIsRefused`; `ipv6AccountRegistersOverUDP6` (Via and Contact `[::1]`, the live config, a MESSAGE out over UDP6); `ipv6AccountRegistersOverTCP6`; `ipv6CallOffersIPv6MediaAndCarriesRTP` (`c=IN IP6 ::1`, RTP address `::1`, a loopback call over `[::1]` with RTP both ways); `incomingOverIPv6ReachesTheIPv6Account` (account by family, answers per offer family, MESSAGE); `autoFollowsSystemResolverForHostNames` ("localhost": Auto follows getaddrinfo's first family, IPv4 only and IPv6 only keep theirs); `familyIsDecidedAgainOnNetworkChangeAndRetry`; `newIPv6AddressStartsRoundOnlyForIPv6Accounts` (IPv6 appearing starts a round, a new address without IPv6 accounts does not, with one it does); `networkChangeRestartsIPv6Listeners`; `iceIsNotUsedOverIPv6`. In `Engine262Tests.swift`, `privateIPv6ServerAccountIsAdded` now registers over UDP6 with STUN on, and `privateServerAccountDoesNotUseSTUN` sets IPv4 only for its "localhost" account. +- **Tests.** `EngineIPv6Tests.swift` with `IPv6Stub` (UDP and TCP on `[::1]`, optionally UDP on 127.0.0.1 with the same port; answers REGISTER and INVITE with `IN IP6 ::1`, records family, transport, Via, Contact and bodies; sends INVITE with an IPv6 or IPv4 offer and MESSAGE). Values: old JSON decodes as Auto (unknown values too), literals, first hop, contradictions, the decision with a fake resolver (literals, fixed families, resolver order, offline, availability, SRV), `IPFamilyResolver.system` against `getaddrinfo`, mapping by family and its read-back from `pjsua_acc_config` (transport id, `ipv6_media_use`, STUN, bind address), transport ids, IPv6 registrar-source comparison, `NetworkPath.address6`. pjsua: `bindAddressDecidesTransportFamilies`; `ipv6TransportFailureIsNotFatal` (`[::]:P` held by another socket: the engine starts with IPv4 UDP and TCP6 on P and refuses IPv6 UDP accounts; released, both UDP transports use P); `contradictoryIPProtocolIsRefused`; `ipv6AccountRegistersOverUDP6` (Via and Contact `[::1]`, the live config, a MESSAGE out over UDP6); `ipv6AccountRegistersOverTCP6`; `ipv6CallOffersIPv6MediaAndCarriesRTP` (`c=IN IP6 ::1`, RTP address `::1`, a loopback call over `[::1]` with RTP both ways); `incomingOverIPv6ReachesTheIPv6Account` (account by family, answers per offer family, MESSAGE); `autoFollowsSystemResolverForHostNames` ("localhost": Auto follows getaddrinfo's first family, IPv4 only and IPv6 only keep theirs); `familyIsDecidedAgainOnNetworkChangeAndRetry`; `newIPv6AddressStartsRoundOnlyForIPv6Accounts` (IPv6 appearing starts a round, a new address without IPv6 accounts does not, with one it does); `networkChangeRestartsIPv6Listeners`; `iceGathersIPv6CandidatesOverIPv6` (ICE on: `c=IN IP6`, IPv6 host candidates including the default one, RTP to a peer without ICE). In `Engine262Tests.swift`, `privateIPv6ServerAccountIsAdded` now registers over UDP6 with STUN on, and `privateServerAccountDoesNotUseSTUN` sets IPv4 only for its "localhost" account. - **Only a real network can verify:** a real IPv6 PBX over UDP, TCP and TLS (a certificate for an AAAA name), a dual-stack server by host name, an IPv6-only network, router-advertised and temporary addresses (whether NWPathMonitor reports a new temporary address at all, and the Contact after a rotation), moving between IPv4-only, dual-stack and IPv6-only networks with calls in progress, SRV targets with AAAA records only, IPv6 firewalls without NAT, and RTP through them. ## Deny incoming calls diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index ffe8f88..1b06740 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -77,7 +77,7 @@ App: - Messages are off until switched on in Settings › General ([#8](https://github.com/HSMM/MacroSIP/issues/8)): with the switch off there is no Messages tab, no Send Message item, no notification and no sound, and incoming `MESSAGE` requests are dropped with a log line. - The ringtone chosen in Settings › Audio reaches the engine ([#7](https://github.com/HSMM/MacroSIP/issues/7)): Classic, Digital and Soft are three different melodies, a custom AIFF, M4A or MP3 file is converted to WAV once and reused, a file that cannot be read keeps the previous choice and says why, and the preview plays the real choice at the chosen volume. -`26.3.1` (not released yet): IPv6 ([#11](https://github.com/HSMM/MacroSIP/issues/11)). SIP over UDP, TCP and TLS and the audio over IPv6 next to IPv4, for a server given by an IPv6 address or by a host name with AAAA records; an account at `[2001:db8::1]` no longer retries forever. Account editor › Advanced › IP protocol: Auto (an IP address picks its own protocol, a host name follows the order macOS returns; decided again after a network change), IPv4 only, IPv6 only. IPv6 accounts use no STUN and no ICE (plain RTP: PJSIP 2.17 cannot open its IPv6 ICE socket on macOS). Tested on loopback only; a real IPv6 PBX and network are not verified. +`26.3.1` (not released yet): IPv6 ([#11](https://github.com/HSMM/MacroSIP/issues/11)). SIP over UDP, TCP and TLS and the audio over IPv6 next to IPv4, for a server given by an IPv6 address or by a host name with AAAA records; an account at `[2001:db8::1]` no longer retries forever. Account editor › Advanced › IP protocol: Auto (an IP address picks its own protocol, a host name follows the order macOS returns; decided again after a network change), IPv4 only, IPv6 only. IPv6 accounts use no STUN; ICE gathers IPv6 candidates with a PJSIP patch (pjsua bound its IPv6 ICE socket to "0", which macOS cannot bind; `scripts/pjsip-patches/`). Tested on loopback only; a real IPv6 PBX and network are not verified. ## Later diff --git a/docs/adr/0014-ipv6-dual-stack.md b/docs/adr/0014-ipv6-dual-stack.md index 4ad5e1a..fc9b4ac 100644 --- a/docs/adr/0014-ipv6-dual-stack.md +++ b/docs/adr/0014-ipv6-dual-stack.md @@ -38,11 +38,15 @@ loses the choice between the verifying and the non-verifying TLS listener (miles keep pjsua's default. Every offer is answered in its own family. - **No STUN over IPv6.** IPv6 accounts use neither SIP nor media STUN, and the SDP takes the address the registrar saw (`allow_sdp_nat_rewrite`), as for private IPv4 servers since 26.2. -- **No ICE over IPv6, for now.** The plan was IPv6 ICE candidates. PJSIP 2.17 binds the IPv6 ICE - component to the string "0", which macOS `getaddrinfo` turns into `::ffff:0.0.0.0`; that socket - cannot be bound, the offer carries IPv4 candidates only and a call fails on an IPv6 answer. IPv6 - accounts therefore have ICE off and use plain RTP. Enabling it needs a PJSIP patch (bind "::"), - which is a separate decision because it means patching and rebuilding PJSIP. +- **ICE over IPv6, with our first PJSIP patch.** PJSIP 2.17 binds the IPv6 ICE component to the + string "0", which macOS `getaddrinfo` turns into `::ffff:0.0.0.0`; that socket cannot be bound, the + offer carried IPv4 candidates only and a call failed on an IPv6 answer. Instead of turning ICE off + for IPv6 accounts, `scripts/build-pjsip.sh` applies `scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch` + ("::" instead of "0" in pjsua_media.c). This amends ADR 0002/0012: pjproject is no longer built + from the pristine tarball alone. Patches live in `scripts/pjsip-patches/`, one problem per file + with a header saying why, applied in name order with `patch -p1 --forward`; a patch that does not + apply stops the build; their hashes are part of the build stamp and of CI's cache key; every + pjproject upgrade reviews them (drop when fixed upstream). - **Out of scope:** NAT64 and 464XLAT for IPv4 servers on IPv6-only networks, STUN and TURN over IPv6, servers on link-local addresses (`fe80::…%en0`). @@ -52,6 +56,7 @@ An account at `[2001:db8::1]` or at an AAAA-only host name registers and calls o may move to IPv6 after the update when macOS orders the IPv6 address first (as `localhost` does); "IPv4 only" keeps the old behaviour. The engine opens four more listening sockets. With a host name whose order changes between networks, the account may change family at a network change; a call in -progress on the old family may not survive that. IPv6 accounts lose ICE until PJSIP is patched. +progress on the old family may not survive that. We now carry a PJSIP patch, which every pjproject +upgrade has to re-check. Everything is verified on loopback only (`[::1]` with in-process stubs); behaviour on a real IPv6 PBX and network is left to users and listed as not verified (docs/ENGINE.md "IPv6"). diff --git a/scripts/README-build.md b/scripts/README-build.md index ceaf4ab..532b58d 100644 --- a/scripts/README-build.md +++ b/scripts/README-build.md @@ -28,7 +28,7 @@ Pinned sources (version, URL and SHA-256 at the top of the script): | Component | Version | Notes | |---|---|---| -| pjproject | 2.17 | `config_site.h` from `third_party/pjsip/`, same for both architectures | +| pjproject | 2.17 | `config_site.h` from `third_party/pjsip/`, same for both architectures; patches from `scripts/pjsip-patches/` | | OpenSSL | 3.5.9 (LTS) | `no-shared no-module no-tests`, only `build_libs` + `install_dev` | | Opus | 1.6.1 | `--disable-shared --disable-doc --disable-extra-programs` | @@ -37,6 +37,23 @@ architecture and the `minos` of every archive and of `pjsua`. arm64 is a native passes `--host=x86_64-apple-darwin` to Opus and pjproject and the `darwin64-x86_64-cc` target to OpenSSL. +## Patches + +`scripts/pjsip-patches/*.patch` are applied to the extracted pjproject tree in name order +(`patch -p1 --forward`, after `config_site.h` is copied in, before configure). A patch that does +not apply, or leaves a `.rej` file, stops the build with an error; it never builds unpatched. +Each patch starts with a plain-text header saying what it fixes and why. Their names and SHA-256 +are part of the PJSIP recipe, so adding or changing a patch rebuilds PJSIP; CI's cache key covers +the folder too. When upgrading pjproject, check every patch: drop it if upstream fixed the +problem, refresh it otherwise. + +| Patch | Why | +|---|---| +| `0001-ipv6-ice-bind-any.patch` | pjsua binds the IPv6 ICE STUN/TURN components to the string "0", which macOS `getaddrinfo` turns into `::ffff:0.0.0.0`; that cannot be bound to an IPv6-only socket, so IPv6 calls with ICE got IPv4 candidates only. The patch uses "::" (ADR 0014). | + +To check a build: `lipo -thin arm64 third_party/pjsip/lib/libpjsua.a -output /tmp/x.a`, extract +`pjsua_media.o` with `ar -x`, and `otool -v -s __TEXT __cstring pjsua_media.o` lists `::`. + ## Layout All outputs are git-ignored except `third_party/pjsip/config_site.h`. @@ -58,7 +75,7 @@ All outputs are git-ignored except `third_party/pjsip/config_site.h`. ## Rebuild and caching Each component (OpenSSL, Opus, PJSIP per architecture, then the universal merge) writes a stamp -holding its recipe: versions, checksums, flags, the SHA-256 of `config_site.h` and the stamps of +holding its recipe: versions, checksums, flags, the SHA-256 of `config_site.h` and of each patch, and the stamps of what it was built against. A run skips every component whose stamp matches and rebuilds the rest from a freshly extracted source tree. So after changing `config_site.h` just rerun the script: it rebuilds PJSIP for both architectures (~2 min) and keeps OpenSSL and Opus. Then run @@ -69,8 +86,8 @@ To upgrade a component: change its version and checksum in the script, rerun. Ta from upstream (`openssl-.tar.gz.sha256` on the OpenSSL release, `SHA256SUMS.txt` on downloads.xiph.org) and compare it with `shasum -a 256` of the download. -CI caches `third_party/pjsip` and `third_party/deps` with a key over the script and -`config_site.h`; on a hit the script finds all stamps current and does nothing. +CI caches `third_party/pjsip` and `third_party/deps` with a key over the script, +`config_site.h` and `scripts/pjsip-patches/`; on a hit the script finds all stamps current and does nothing. ## Pitfalls diff --git a/scripts/build-pjsip.sh b/scripts/build-pjsip.sh index fd5e071..7f1da79 100755 --- a/scripts/build-pjsip.sh +++ b/scripts/build-pjsip.sh @@ -5,14 +5,15 @@ # # Targets: macOS arm64 (native) and x86_64 (cross-compiled on Apple Silicon), # static libraries, deployment target macOS 14.0 for both slices. -# Inputs : pinned source tarballs (SHA-256 verified), third_party/pjsip/config_site.h +# Inputs : pinned source tarballs (SHA-256 verified), third_party/pjsip/config_site.h, +# scripts/pjsip-patches/*.patch (applied to pjproject in name order; must apply cleanly) # Output : third_party/deps/universal/{include,lib} libssl.a, libcrypto.a, libopus.a # third_party/pjsip/{include,lib,bin/pjsua,LINKFLAGS,CFLAGS} universal PJSIP # Per-arch intermediate results: third_party/deps//, third_party/pjsip/arch// # # Idempotent and cache-friendly: every component (OpenSSL, Opus, PJSIP per architecture, # then the universal merge) records a stamp with its recipe (versions, checksums, flags, -# config_site.h hash). A component whose stamp matches is skipped; a changed recipe +# config_site.h and patch hashes). A component whose stamp matches is skipped; a changed recipe # rebuilds that component and everything that depends on it. Tarballs are downloaded only # when a component needs them and are SHA-256 verified before use. Each build starts from a # freshly extracted source tree, so stale objects never leak into a new build. @@ -50,6 +51,7 @@ BUILD_DIR="${TP}/build" DEPS="${TP}/deps" OUT="${TP}/pjsip" CONFIG_SITE="${OUT}/config_site.h" +PATCH_DIR="${SCRIPT_DIR}/pjsip-patches" LOG_DIR="${TP}/build-logs" CLEAN=0 @@ -207,13 +209,18 @@ with_per_arch() { sha_of() { shasum -a 256 "$1" | awk '{print $1}'; } +# Our patches to pjproject (scripts/pjsip-patches/*.patch, -p1 from the source root), in name order. +pjsip_patches() { local p; for p in "${PATCH_DIR}"/*.patch; do [[ -f "${p}" ]] && printf '%s\n' "${p}"; done; return 0; } +# One line per patch: name and SHA-256, so a changed patch changes the PJSIP recipe. +patches_recipe() { local p; while IFS= read -r p; do printf 'patch %s %s\n' "$(basename "${p}")" "$(sha_of "${p}")"; done < <(pjsip_patches); } + START_TS=$(date +%s) # ------------------------------------------------------------ prerequisites --- step "Checking prerequisites" [[ "$(uname -s)" == "Darwin" ]] || die "macOS only" [[ "$(uname -m)" == "arm64" ]] || die "Apple Silicon (arm64) host required (x86_64 is cross-compiled)" -for tool in clang make curl perl lipo otool shasum; do +for tool in clang make curl perl lipo otool shasum patch; do command -v "${tool}" >/dev/null || die "${tool} not found (install Xcode Command Line Tools)" done [[ -f "${CONFIG_SITE}" ]] || die "missing ${CONFIG_SITE}" @@ -301,6 +308,7 @@ build_pjsip() { local stamp="${dest}/.stamp" local recipe recipe="pjproject ${PJ_VERSION} ${PJ_SHA256} ${arch} macos-${MIN_MACOS} config_site $(sha_of "${CONFIG_SITE}") +$(patches_recipe) ${PJ_CONFIGURE_FLAGS[*]} $(cat "${deps}/.stamp-openssl") $(cat "${deps}/.stamp-opus")" @@ -314,6 +322,17 @@ $(cat "${deps}/.stamp-opus")" [[ -x "${src}/configure" ]] || die "unexpected tarball layout (no ${src}/configure)" cp "${CONFIG_SITE}" "${src}/pjlib/include/pj/config_site.h" info "config_site.h -> pjlib/include/pj/config_site.h" + local patch + while IFS= read -r patch; do + # --forward: a patch that is already in the source (or does not fit it) fails instead of + # being reversed; any failed hunk stops the build. + patch -p1 --forward --batch --silent -d "${src}" < "${patch}" \ + || die "patch $(basename "${patch}") does not apply to pjproject ${PJ_VERSION}" + if [[ -n "$(find "${src}" -name '*.rej' -print -quit)" ]]; then + die "patch $(basename "${patch}") left rejected hunks in ${src}" + fi + info "patched: $(basename "${patch}")" + done < <(pjsip_patches) host="$(arch_host "${arch}")" ( diff --git a/scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch b/scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch new file mode 100644 index 0000000..cf1e078 --- /dev/null +++ b/scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch @@ -0,0 +1,33 @@ +Bind the IPv6 ICE components to "::" instead of "0". + +pjsua builds the bound address of an IPv6 ICE STUN or TURN transport from the +string "0" (IN6_ADDR_ANY). pj_sockaddr_init(AF_INET6, "0") is not an IPv6 +literal, so pjlib falls back to getaddrinfo, which on macOS returns the +IPv4-mapped ::ffff:0.0.0.0. Binding that to an IPv6 socket with IPV6_V6ONLY set +(as pjlib does) fails with EADDRNOTAVAIL ("Failed creating STUN transport #1 +... Can't assign requested address"): an IPv6 call with ICE then has IPv4 +candidates only and fails on an IPv6 answer. "::" is the IPv6 any address and +parses with inet_pton on every platform. + +MacroSIP: applied by scripts/build-pjsip.sh (ADR 0014). + +--- a/pjsip/src/pjsua-lib/pjsua_media.c ++++ b/pjsip/src/pjsua-lib/pjsua_media.c +@@ -1230,7 +1230,7 @@ + } + + for (i = 0; i < ice_cfg.stun_tp_cnt; ++i) { +- pj_str_t IN6_ADDR_ANY = {"0", 1}; ++ pj_str_t IN6_ADDR_ANY = {"::", 2}; + + /* Configure STUN server */ + if (pjsua_media_acc_is_using_stun(call_med->call->acc_id) && +@@ -1317,7 +1317,7 @@ + ice_cfg.turn_tp[0].port = 3479; + + for (i = 0; i < ice_cfg.turn_tp_cnt; i++) { +- pj_str_t IN6_ADDR_ANY = {"0", 1}; ++ pj_str_t IN6_ADDR_ANY = {"::", 2}; + + /* Configure TURN connection settings and credential */ + ice_cfg.turn_tp[i].server = ice_cfg.turn_tp[0].server; From 27227f0db31a37da7973e4f3683e268cc98dffa7 Mon Sep 17 00:00:00 2001 From: HSMM Date: Mon, 9 Nov 2026 14:39:58 +0300 Subject: [PATCH 06/12] IPv6: Auto falls back to the other family; moves wait for calls and drop the old binding --- README.md | 2 +- README.ru.md | 2 +- Sources/CPJSUA/include/CPJSUA.h | 20 + Sources/CPJSUA/shim.c | 59 +++ .../MacroSIPCore/Engine/Engine+Accounts.swift | 185 ++++++++- .../MacroSIPCore/Engine/Engine+Network.swift | 94 ++++- .../Engine/Engine+NetworkOptions.swift | 1 + Sources/MacroSIPCore/Engine/Engine.swift | 16 + .../MacroSIPCore/Engine/EngineBridge.swift | 20 +- .../Engine/NetworkPathMonitor.swift | 22 ++ Sources/macrosip-cli/Interactive.swift | 11 +- Sources/macrosip-cli/SelfTest.swift | 5 +- Tests/MacroSIPCoreTests/EngineIPv6Tests.swift | 354 +++++++++++++++--- docs/ENGINE.md | 18 +- docs/ROADMAP.md | 2 +- docs/adr/0014-ipv6-dual-stack.md | 43 ++- 16 files changed, 753 insertions(+), 101 deletions(-) diff --git a/README.md b/README.md index 79fb2d6..c4bcdbf 100644 --- a/README.md +++ b/README.md @@ -93,7 +93,7 @@ Messages: the conversation list, and a conversation open: - Several SIP accounts registered at once; UDP, TCP and TLS with certificate verification; SRTP; STUN and ICE; outgoing-only accounts; each account switched on or off in the account pop-up; search and a status summary when there are many. Passwords are kept in the Keychain. - An account on a server addressed by a private IP address (10.x, 172.16-31.x, 192.168.x, 100.64-127.x, on the LAN or over a VPN) does not use STUN, so the first REGISTER carries the Mac's own address. -- IPv6 next to IPv4: SIP over UDP, TCP and TLS and the audio over IPv6, for a server given by an IPv6 address or by a host name with IPv6 (AAAA) records. Per account, IP protocol Auto (an IP address picks its own protocol, a host name follows the order macOS returns), IPv4 only or IPv6 only. Over IPv6 there is no STUN; ICE works over IPv6 too. +- IPv6 next to IPv4: SIP over UDP, TCP and TLS and the audio over IPv6, for a server given by an IPv6 address or by a host name with IPv6 (AAAA) records. Per account, IP protocol Auto (an IP address picks its own protocol, a host name follows the order macOS returns and tries the other protocol when the server does not answer), IPv4 only or IPv6 only. Over IPv6 there is no STUN; ICE works over IPv6 too. - After a network drop, an IP change or sleep the accounts register again at once, with backoff while the network is down; a running call survives an IP change. The status bar and the call window show "No network" and "Reconnecting…". - Network pane: RTP port range, rport, DNS SRV with a custom nameserver. - Codecs: Opus (with FEC and DTX), G.722, G.711 and, off until you turn them on, G.722.1, GSM, iLBC and Speex. diff --git a/README.ru.md b/README.ru.md index 8881354..75aed06 100644 --- a/README.ru.md +++ b/README.ru.md @@ -93,7 +93,7 @@ Electron и Qt. Одно небольшое окно, значок в строк - Несколько SIP-аккаунтов с одновременной регистрацией; UDP, TCP и TLS с проверкой сертификата; SRTP; STUN и ICE; аккаунты «только исходящие»; каждый аккаунт включается и выключается в меню аккаунтов; поиск и сводка состояния, когда аккаунтов много. Пароли хранятся в связке ключей. - Аккаунт на сервере с частным IP-адресом (10.x, 172.16–31.x, 192.168.x, 100.64–127.x, в локальной сети или через VPN) не использует STUN: первый REGISTER несёт собственный адрес Mac. -- IPv6 наряду с IPv4: SIP по UDP, TCP и TLS и звук по IPv6 для сервера, заданного IPv6-адресом или именем хоста с IPv6-записями (AAAA). У каждого аккаунта протокол IP: «Авто» (IP-адрес сам задаёт протокол, для имени хоста — порядок, который выдаёт macOS), «Только IPv4» или «Только IPv6». По IPv6 нет STUN; ICE работает и по IPv6. +- IPv6 наряду с IPv4: SIP по UDP, TCP и TLS и звук по IPv6 для сервера, заданного IPv6-адресом или именем хоста с IPv6-записями (AAAA). У каждого аккаунта протокол IP: «Авто» (IP-адрес сам задаёт протокол, для имени хоста — порядок, который выдаёт macOS, а если сервер не отвечает, другой протокол), «Только IPv4» или «Только IPv6». По IPv6 нет STUN; ICE работает и по IPv6. - После обрыва сети, смены IP или сна аккаунты сразу регистрируются заново, пока сети нет, попытки повторяются с нарастающей паузой; идущий разговор переживает смену IP. В строке состояния и в окне звонка видны «Нет сети» и «Переподключение…». - Раздел «Сеть»: диапазон портов RTP, rport, DNS SRV с собственным сервером имён. - Кодеки: Opus (с FEC и DTX), G.722, G.711 и, выключенные до включения вами, G.722.1, GSM, iLBC и Speex. diff --git a/Sources/CPJSUA/include/CPJSUA.h b/Sources/CPJSUA/include/CPJSUA.h index 3ffcaea..9a83f9e 100644 --- a/Sources/CPJSUA/include/CPJSUA.h +++ b/Sources/CPJSUA/include/CPJSUA.h @@ -469,6 +469,26 @@ pj_status_t cpjsua_handle_ip_change(int restart_listener, unsigned restart_delay * calls). Accounts with a registration session are always re-registered by pjsua. */ void cpjsua_acc_prepare_ip_change(pjsua_acc_id acc_id, int register_it); +/* ------------------------------------------------- moving an account between IP families --- */ + +/** Slots in pjsua's transport table (pjsua_var.tpdata, a fixed array of 8 in pjsua_internal.h, + * not a configurable macro): the engine creates at most this many transports. */ +unsigned cpjsua_transport_slots(void); + +/** pjsua_acc_modify never copies allow_sdp_nat_rewrite (only pjsua_acc_add does): set it on the + * live account config. */ +void cpjsua_acc_set_sdp_nat_rewrite(pjsua_acc_id acc_id, int on); + +/** After a move to another transport (the registration session is gone): end the MWI subscription, + * whose dialog keeps the old transport selector; pjsua subscribes again once the account has + * registered (regc_cb). No-op while the account still has a registration session. */ +void cpjsua_acc_end_mwi_after_move(pjsua_acc_id acc_id); + +/** Presence subscription of a buddy anew: the current one (its dialog keeps the transport selector + * of the account at subscribe time) is detached and unsubscribed, and a new one is created with the + * account's current selector. No-op for a buddy without an active subscription. */ +pj_status_t cpjsua_buddy_resubscribe(pjsua_buddy_id buddy_id); + /** Re-INVITE a confirmed call after a network change: new media transport, Contact and * Via (cpjsua_ip_change_reinvite_flags), local hold kept. */ pj_status_t cpjsua_call_reinvite_ip_change(pjsua_call_id call_id); diff --git a/Sources/CPJSUA/shim.c b/Sources/CPJSUA/shim.c index 3d8856b..163ad64 100644 --- a/Sources/CPJSUA/shim.c +++ b/Sources/CPJSUA/shim.c @@ -1635,6 +1635,65 @@ void cpjsua_acc_prepare_ip_change(pjsua_acc_id acc_id, int register_it) PJSUA_UNLOCK(); } +unsigned cpjsua_transport_slots(void) +{ + return (unsigned)PJ_ARRAY_SIZE(pjsua_var.tpdata); +} + +void cpjsua_acc_set_sdp_nat_rewrite(pjsua_acc_id acc_id, int on) +{ + if (acc_id < 0 || acc_id >= (int)PJ_ARRAY_SIZE(pjsua_var.acc)) + return; + PJSUA_LOCK(); + if (pjsua_var.acc[acc_id].valid) + pjsua_var.acc[acc_id].cfg.allow_sdp_nat_rewrite = on ? PJ_TRUE : PJ_FALSE; + PJSUA_UNLOCK(); +} + +void cpjsua_acc_end_mwi_after_move(pjsua_acc_id acc_id) +{ + if (acc_id < 0 || acc_id >= (int)PJ_ARRAY_SIZE(pjsua_var.acc)) + return; + PJSUA_LOCK(); + /* pjsua_start_mwi() unsubscribes and detaches the subscription when the account has no + * registration session (pjsua_pres.c); regc_cb starts a new one after the next REGISTER. */ + if (pjsua_var.acc[acc_id].valid && pjsua_var.acc[acc_id].regc == NULL && pjsua_var.acc[acc_id].mwi_sub) + pjsua_start_mwi(acc_id, PJ_FALSE); + PJSUA_UNLOCK(); +} + +pj_status_t cpjsua_buddy_resubscribe(pjsua_buddy_id buddy_id) +{ + pjsua_buddy *buddy; + pjsip_evsub *sub; + pjsip_dialog *dlg; + pjsip_tx_data *tdata; + + if (!pjsua_buddy_is_valid(buddy_id)) + return PJ_EINVAL; + PJSUA_LOCK(); + buddy = &pjsua_var.buddy[buddy_id]; + sub = buddy->sub; + dlg = buddy->dlg; + if (!sub || !dlg || !buddy->monitor) { + PJSUA_UNLOCK(); + return PJ_SUCCESS; + } + pjsip_dlg_inc_lock(dlg); + /* Detached: pjsua's callbacks ignore a subscription without the buddy as mod data. */ + buddy->sub = NULL; + buddy->dlg = NULL; + pjsip_evsub_set_mod_data(sub, pjsua_var.mod.id, NULL); + if (pjsip_evsub_get_state(sub) != PJSIP_EVSUB_STATE_TERMINATED && + pjsip_pres_initiate(sub, 0, &tdata) == PJ_SUCCESS) + { + pjsip_pres_send_request(sub, tdata); + } + pjsip_dlg_dec_lock(dlg); + PJSUA_UNLOCK(); + return pjsua_buddy_update_pres(buddy_id); +} + pj_status_t cpjsua_call_reinvite_ip_change(pjsua_call_id call_id) { pjsua_call_info ci; diff --git a/Sources/MacroSIPCore/Engine/Engine+Accounts.swift b/Sources/MacroSIPCore/Engine/Engine+Accounts.swift index 6f037a4..493e2f6 100644 --- a/Sources/MacroSIPCore/Engine/Engine+Accounts.swift +++ b/Sources/MacroSIPCore/Engine/Engine+Accounts.swift @@ -1,5 +1,6 @@ internal import CPJSUA import Foundation +import os extension Engine { /// Adds the account to pjsua and registers it when `cfg.registers`. Atomic: if the @@ -46,8 +47,17 @@ extension Engine { try requireStarted() guard var entry = accounts[cfg.id] else { throw EngineError.unknownAccount(cfg.id) } let pw = password ?? entry.password - let family = try decideFamily(cfg) + var family = try decideFamily(cfg) + // Never move an account with a call to the other family: the call's dialog would keep its + // peer and lose its transport. The move waits for the calls (`runDeferredMoves`). + var deferred: (family: IPFamily, reason: String)? + if family != entry.family, accountHasCalls(entry.index) { + deferred = (family, "settings changed") + family = entry.family + emit(.log(level: 3, "engine: account \(cfg.uri): move to \(deferred!.family) waits for its calls")) + } let settings = try accountSettings(cfg, password: pw, family: family) + let moving = family != entry.family // New settings start a new series of attempts. cancelRegistrationRetry(cfg.id) bridge.resetRetryAttempts(cfg.id) @@ -61,11 +71,18 @@ extension Engine { PJ.warn(error, "unregister before modifying account") } } + // A move to the other family destroys the registration session without an un-REGISTER + // (disable_reg_on_modify); remove the old binding first, so it does not stay at the registrar. + let unregisterFirst = moving && cfg.registers && hasBinding(cfg.id) + if unregisterFirst { unregisterBeforeMove(entry) } + defer { if unregisterFirst { bridge.setIgnoringUnregister(entry.index, false) } } try AccountMapping.withPJConfig(settings) { p in // We decide about (re-)registration below, not pjsua_acc_modify. p.pointee.disable_reg_on_modify = 1 try PJ.check(pjsua_acc_modify(entry.index, p), "pjsua_acc_modify") } + cpjsua_acc_set_sdp_nat_rewrite(entry.index, settings.sdpNATRewrite ? 1 : 0) + if moving { cpjsua_acc_end_mwi_after_move(entry.index) } if cfg.isDefaultOutgoing { PJ.warn(pjsua_acc_set_default(entry.index), "set default account") } @@ -76,6 +93,9 @@ extension Engine { entry.config = cfg entry.password = pw entry.family = family + entry.pendingMove = deferred + entry.familySticky = false + entry.familyFallbackTried = false accounts[cfg.id] = entry bridge.setAccount(entry.index, cfg.id, registrationInterval: cfg.registrationInterval, proxy: SignallingSource.proxy(cfg.outboundProxy, transport: cfg.transport)) @@ -87,7 +107,9 @@ extension Engine { if cfg.publishPresence { do { try applyPresence(entry.presence, index: entry.index) } catch { PJ.warn(error, "presence") } } - // A SUBSCRIBE that failed with the old settings would wait 300 s for pjsua's retry. + // A SUBSCRIBE that failed with the old settings would wait 300 s for pjsua's retry; after a + // move every subscription is made anew on the new transport. + if moving { resubscribePresence(accountIndex: entry.index) } refreshPresenceSubscriptions(accountIndex: entry.index) if cfg.registers { try applyRegistration(cfg.id, true) @@ -144,15 +166,43 @@ extension Engine { var srvInEffect: Bool { !dnsServers.isEmpty } /// The account's IP family (`IPFamilyPolicy`). Throws `.invalidArgument` when IPv4 only or IPv6 only - /// contradicts the server's IP literal: such an account could never register. + /// contradicts the server's IP literal: such an account could never register. A host name that is + /// not resolved within `familyLookupTimeout` counts as unresolved (IPv4). func decideFamily(_ cfg: AccountConfig) throws -> IPFamily { if let literal = IPFamilyPolicy.conflict(in: cfg) { let host = IPFamilyPolicy.firstHop(of: cfg).host throw EngineError.invalidArgument("server \(host) is an \(literal) address but the account is set to " + "\(literal == .ipv6 ? "IPv4" : "IPv6") only") } - return IPFamilyPolicy.decide(cfg, available: transports.families(for: cfg), srv: srvInEffect, - resolve: resolveFamilies) + return IPFamilyPolicy.decide(cfg, available: transports.families(for: cfg), srv: srvInEffect) { host in + lookupFamilies([host])[host] ?? [] + } + } + + /// The families of each host name, looked up concurrently off the engine queue (each host once) and + /// waited for at most `familyLookupTimeout` in all. A host missing from the result did not answer in + /// time; its lookup goes on and is discarded. Up to N lookups thus block the engine for one limit at + /// most, not N in a row. + func lookupFamilies(_ hosts: [String]) -> [String: [IPFamily]] { + let unique = Array(Set(hosts.filter { !$0.isEmpty })) + guard !unique.isEmpty else { return [:] } + let results = OSAllocatedUnfairLock(initialState: [String: [IPFamily]]()) + let group = DispatchGroup() + let resolve = resolveFamilies + for host in unique { + group.enter() + DispatchQueue.global(qos: .userInitiated).async { + let families = resolve(host) + results.withLock { $0[host] = families } + group.leave() + } + } + let limit = familyLookupTimeout.components + let seconds = Double(limit.seconds) + Double(limit.attoseconds) / 1e18 + if group.wait(timeout: .now() + seconds) == .timedOut { + emit(.log(level: 3, "engine: address lookup of \(unique.joined(separator: ", ")) not finished within \(seconds) s")) + } + return results.withLock { $0 } } private func logFamily(_ cfg: AccountConfig, _ family: IPFamily) { @@ -160,17 +210,62 @@ extension Engine { emit(.log(level: 4, "engine: account \(cfg.uri): \(family) (\(how), server \(IPFamilyPolicy.firstHop(of: cfg).host))")) } - /// Decides the family of an Auto account with a host name again (network change, REGISTER retry). - /// When it changed, the account moves to the other family's transport (pjsua_acc_modify without a - /// REGISTER; the caller registers) and its registrar must accept a REGISTER again before its - /// INVITEs are trusted. Returns true when the family changed. + /// The registrar holds a binding of the account (last REGISTER answered 2xx). + func hasBinding(_ id: AccountID) -> Bool { + if case .registered = bridge.registration(of: id) { return true } + return false + } + + /// The account has a call in any state (ringing, connecting, connected, held). + func accountHasCalls(_ index: pjsua_acc_id) -> Bool { + CallSnapshot.allSlots().contains { slot in + guard let snap = CallSnapshot.read(slot) else { return false } + return snap.accIndex == index && snap.state != .disconnected + } + } + + /// Sends the un-REGISTER of the account's current binding (Expires 0 on the old family) and marks + /// its result as no state of the account (the session is destroyed by the move right after, which + /// keeps the request going but drops its callback). + func unregisterBeforeMove(_ entry: AccountEntry) { + bridge.setIgnoringUnregister(entry.index, true) + PJ.warn(pjsua_acc_set_registration(entry.index, 0), "account \(entry.config.uri): un-REGISTER before the move") + } + + /// Moves the account to `family`'s transport: the old binding is un-REGISTERed, the account is + /// `pjsua_acc_modify`d without a REGISTER (`disable_reg_on_modify`), `allow_sdp_nat_rewrite` is set + /// (pjsua_acc_modify does not copy it), the MWI and presence subscriptions are made anew (their + /// dialogs keep the old transport), and the registrar's INVITEs are trusted again only after it + /// accepted a REGISTER. `register`: send that REGISTER now (outside a network-change round, which + /// registers the account itself). An account with a call is not moved: the move waits for the + /// calls to end (`runDeferredMoves`). Returns true when the account moved. @discardableResult - func refreshAccountFamily(_ id: AccountID, reason: String) -> Bool { - guard isStarted, PJ.registerThread(), var entry = accounts[id], - IPFamilyPolicy.followsResolver(entry.config, srv: srvInEffect), - let family = try? decideFamily(entry.config), family != entry.family else { return false } + func moveAccount(_ id: AccountID, to family: IPFamily, reason: String, register: Bool) -> Bool { + guard isStarted, PJ.registerThread(), var entry = accounts[id] else { return false } + guard entry.family != family else { + entry.pendingMove = nil + accounts[id] = entry + return false + } + if accountHasCalls(entry.index) { + if entry.pendingMove?.family != family { + emit(.log(level: 3, "engine: account \(entry.config.uri): move to \(family) (\(reason)) waits for its calls")) + } + entry.pendingMove = (family, reason) + accounts[id] = entry + return false + } + let settings: PJAccountSettings + do { + settings = try accountSettings(entry.config, password: entry.password, family: family) + } catch { + PJ.warn(error, "account \(entry.config.uri): move to \(family)") + return false + } + let unregisterFirst = hasBinding(id) + if unregisterFirst { unregisterBeforeMove(entry) } + defer { if unregisterFirst { bridge.setIgnoringUnregister(entry.index, false) } } do { - let settings = try accountSettings(entry.config, password: entry.password, family: family) try AccountMapping.withPJConfig(settings) { p in p.pointee.disable_reg_on_modify = 1 try PJ.check(pjsua_acc_modify(entry.index, p), "pjsua_acc_modify") @@ -179,17 +274,65 @@ extension Engine { PJ.warn(error, "account \(entry.config.uri): move to \(family)") return false } + cpjsua_acc_set_sdp_nat_rewrite(entry.index, settings.sdpNATRewrite ? 1 : 0) + cpjsua_acc_end_mwi_after_move(entry.index) emit(.log(level: 3, "engine: account \(entry.config.uri): server now reached over \(family) " + "(was \(entry.family), \(reason))")) entry.family = family + entry.pendingMove = nil accounts[id] = entry bridge.setRegistrarSource(entry.index, nil) + resubscribePresence(accountIndex: entry.index) + if register, entry.wantsRegistration, !sleeping, networkStatus == .online, ipChange == nil { + do { try applyRegistration(id, true) } catch { PJ.warn(error, "account \(entry.config.uri): REGISTER after the move") } + } return true } - /// `refreshAccountFamily` for every account. - func refreshAccountFamilies(reason: String) { - for id in Array(accounts.keys) { refreshAccountFamily(id, reason: reason) } + /// Decides the family of Auto accounts with a host name again (network change, REGISTER retry, + /// IPv6 appearing) and moves those whose family changed. Each host is looked up once, all of them + /// together within `familyLookupTimeout`; an account whose lookup failed or did not finish keeps + /// its family (during a network change DNS often fails for a moment). Sticky accounts (Auto moved + /// them after a REGISTER got no answer) are left alone; the caller clears that at a network change. + func refreshAccountFamilies(_ ids: [AccountID], reason: String, register: Bool) { + guard isStarted, PJ.registerThread() else { return } + let srv = srvInEffect + let candidates = ids.compactMap { id -> (AccountID, AccountEntry, String)? in + guard let entry = accounts[id], !entry.familySticky, + IPFamilyPolicy.followsResolver(entry.config, srv: srv) else { return nil } + return (id, entry, IPFamilyPolicy.firstHop(of: entry.config).host) + } + guard !candidates.isEmpty else { return } + let resolved = lookupFamilies(candidates.map(\.2)) + for (id, entry, host) in candidates { + guard let families = resolved[host], !families.isEmpty else { continue } + let family = IPFamilyPolicy.decide(entry.config, available: transports.families(for: entry.config), + srv: srv) { _ in families } + moveAccount(id, to: family, reason: reason, register: register) + } + } + + /// Moves that waited for an account's calls, once its calls have ended (watchdog tick). + func runDeferredMoves() { + guard isStarted, ipChange == nil else { return } + for (id, entry) in accounts { + guard let move = entry.pendingMove, !accountHasCalls(entry.index) else { continue } + accounts[id]?.pendingMove = nil + moveAccount(id, to: move.family, reason: "\(move.reason), after the calls ended", register: true) + } + } + + /// Presence subscriptions of buddies watched through this account, anew (after a move). + func resubscribePresence(accountIndex index: pjsua_acc_id) { + guard isStarted, PJ.registerThread() else { return } + for (key, buddy) in buddies.sorted(by: { $0.key < $1.key }) { + let account = key.withCString { p -> pjsua_acc_id in + var uri = cpjsua_str(p) + return pjsua_acc_find_for_outgoing(&uri) + } + guard account == index else { continue } + PJ.warn(cpjsua_buddy_resubscribe(buddy.id), "resubscribe presence of \(key)") + } } // MARK: test hooks @@ -202,6 +345,14 @@ extension Engine { resolveFamilies = resolve } + func setFamilyLookupTimeoutForTests(_ limit: Duration) { + familyLookupTimeout = limit + } + + func setIPv6AddressAssignedForTests(_ assigned: @escaping @Sendable (String) -> Bool) { + ipv6AddressAssigned = assigned + } + /// The account's pjsua_acc_config as pjsua holds it now (pjsua_acc_get_config). func liveAccountSettingsForTests(_ id: AccountID) -> PJAccountSettings? { guard isStarted, PJ.registerThread(), let entry = accounts[id], diff --git a/Sources/MacroSIPCore/Engine/Engine+Network.swift b/Sources/MacroSIPCore/Engine/Engine+Network.swift index db82395..b5cb340 100644 --- a/Sources/MacroSIPCore/Engine/Engine+Network.swift +++ b/Sources/MacroSIPCore/Engine/Engine+Network.swift @@ -262,26 +262,43 @@ extension Engine { emit(.log(level: 3, "engine: network path without a default route; keeping address " + (kept.isEmpty ? "unknown" : kept.joined(separator: " ")))) } - // Per family, the same: an IPv6-only network has no IPv4 route and most networks no IPv6 one. + // IPv4: an IPv6-only network has no IPv4 route; keep the address we had. IPv6: keep it only + // while it is still assigned (the lookup failed for a moment); otherwise IPv6 is gone. if path.address.isEmpty { path.address = previous?.address ?? "" } - if path.address6.isEmpty { path.address6 = previous?.address6 ?? "" } + if path.address6.isEmpty, let kept = previous?.address6, !kept.isEmpty, ipv6AddressAssigned(kept) { + path.address6 = kept + } handledPath = path guard !sleeping, !first else { return } if previous.map({ path.routeDiffers(from: $0) }) ?? true || old == .offline || wake { refreshSystemNameservers() } - // A new IPv6 address (a new temporary address, about once a day) matters to accounts bound to - // IPv6, and IPv6 appearing may change what an Auto host name resolves to first; otherwise it - // is no reason for a round (which would end a ringing outgoing call: pjsua's 410). - let ipv6Matters = accounts.values.contains { $0.family == .ipv6 } || (previous?.address6.isEmpty ?? true) - let primary = previous.map { path.primaryDiffers(from: $0, ipv6: ipv6Matters) } ?? true + // IPv6 (docs/ENGINE.md "IPv6"): a new IPv6 address matters to accounts bound to IPv6. It is a + // primary change (run at once, even while an outgoing call rings) only when the address they + // used is gone; a new temporary address whose predecessor is still assigned (it stays for + // days) waits like any non-primary change. Without IPv6 accounts it starts no round at all: + // Auto host names are decided again without disturbing anyone's calls. + let ipv6Accounts = accounts.values.contains { $0.family == .ipv6 } + let oldV6 = previous?.address6 ?? "" + let v6Changed = previous != nil && path.address6 != oldV6 + let v6Gone = v6Changed && !oldV6.isEmpty && !ipv6AddressAssigned(oldV6) + let primary = (previous.map { path.primaryDiffers(from: $0, ipv6: false) } ?? true) || (ipv6Accounts && v6Gone) if wake { requestIPChange(IPChangeRequest(reason: "wake", registerFailed: true, primary: primary)) } else if old == .offline { requestIPChange(IPChangeRequest(reason: "network back", registerFailed: false, primary: primary)) - } else if let previous, path.routeDiffers(from: previous, ipv6: ipv6Matters) { + } else if let previous, path.routeDiffers(from: previous, ipv6: false) || (v6Changed && ipv6Accounts) { emit(.log(level: 3, "engine: network route changed: \(previous.summary) -> \(path.summary)")) requestIPChange(IPChangeRequest(reason: "route changed", registerFailed: false, primary: primary)) + } else if v6Changed { + emit(.log(level: 3, "engine: IPv6 address \(oldV6.isEmpty ? "none" : oldV6) -> " + + "\(path.address6.isEmpty ? "none" : path.address6); no account uses IPv6, no round")) + // IPv6 appearing or going away may change what an Auto host name resolves to first; a new + // temporary address does not. A family Auto fell back to stays (no change of reachability). + if oldV6.isEmpty != path.address6.isEmpty { + refreshAccountFamilies(Array(accounts.keys), reason: "IPv6 \(path.address6.isEmpty ? "lost" : "appeared")", + register: true) + } } } @@ -371,8 +388,11 @@ extension Engine { // A host name may now resolve to the other family first (an IPv6-only network, IPv6 lost): // move such accounts before pjsua re-registers them (an account whose registration was - // destroyed by the move is registered afresh: cpjsua_acc_prepare_ip_change below). - refreshAccountFamilies(reason: "network change") + // destroyed by the move is registered afresh: cpjsua_acc_prepare_ip_change below). The + // family Auto fell back to stays only until a network change. Accounts with calls keep + // their family until the calls end. + clearFamilyFallbacks() + refreshAccountFamilies(Array(accounts.keys), reason: "network change", register: false) var pending: Set = [] for (id, entry) in accounts { let state = bridge.registration(of: id) @@ -679,6 +699,7 @@ extension Engine { for key in Array(reinviteAttempts.keys) where !live.contains(key) { reinviteAttempts[key] = nil } for key in Array(reinviteSince.keys) where !live.contains(key) { reinviteSince[key] = nil } expireStaleReinvites(now) + runDeferredMoves() if let postponed = postponedIPChange, ipChange == nil, !outgoingCallRinging() || now - postponed.since >= Engine.postponeLimit { postponedIPChange = nil @@ -743,7 +764,49 @@ extension Engine { } emit(.log(level: RegistrationBackoff.logLevel(attempt: attempt + 1), "engine: account \(entry.config.uri): REGISTER retry \(attempt + 1)")) - refreshAccountFamily(id, reason: "REGISTER retry") + accounts[id]?.familyFallbackTried = false + refreshAccountFamilies([id], reason: "REGISTER retry", register: false) + do { + try applyRegistration(id, true, retrying: true) + } catch { + if let next = bridge.registrationFailedTemporarily(id, lastError: "\(error)") { + scheduleRegistrationRetry(id, attempt: next.attempt, after: next.delay) + } + } + } + + /// A REGISTER failed temporarily (`.reconnecting` is out). When it got no answer at all, an Auto + /// account may try the other family at once (`tryOtherFamily`); otherwise the backoff retry. + func registrationRetryNeeded(_ id: AccountID, attempt: Int, after delay: TimeInterval, noAnswer: Bool) { + if noAnswer, tryOtherFamily(id) { return } + scheduleRegistrationRetry(id, attempt: attempt, after: delay) + } + + /// Auto keeps the system's order for the first attempt; when a REGISTER over that family got no + /// answer at all (no response: a timeout, a refused or broken connection, no address of the + /// family), the account moves to the other family and registers at once, if the host name has an + /// address of it (or DNS SRV is in effect: the SRV targets are unknown here, the other family is + /// the only chance). Once per series of failures; the family then stays until the next network + /// change (`familySticky`). Not for literals, IPv4 only / IPv6 only, accounts with calls, during a + /// round, offline or asleep. + private func tryOtherFamily(_ id: AccountID) -> Bool { + guard isStarted, PJ.registerThread(), var entry = accounts[id], entry.wantsRegistration, + !entry.familyFallbackTried, !sleeping, networkStatus == .online, ipChange == nil, + entry.config.ipProtocol == .auto else { return false } + let hop = IPFamilyPolicy.firstHop(of: entry.config) + guard !hop.host.isEmpty, IPFamilyPolicy.literalFamily(hop.host) == nil else { return false } + let other: IPFamily = entry.family == .ipv4 ? .ipv6 : .ipv4 + guard transports.id(for: entry.config, family: other) != nil, !accountHasCalls(entry.index) else { return false } + if !(srvInEffect && hop.port == nil) { + guard lookupFamilies([hop.host])[hop.host]?.contains(other) == true else { return false } + } + let from = entry.family + entry.familyFallbackTried = true + accounts[id] = entry + emit(.log(level: 3, "engine: account \(entry.config.uri): no answer over \(from); trying \(other)")) + guard moveAccount(id, to: other, reason: "no answer over \(from)", register: false) else { return false } + accounts[id]?.familySticky = true + cancelRegistrationRetry(id) do { try applyRegistration(id, true, retrying: true) } catch { @@ -751,6 +814,15 @@ extension Engine { scheduleRegistrationRetry(id, attempt: next.attempt, after: next.delay) } } + return true + } + + /// A network change: Auto accounts follow the resolver again. + func clearFamilyFallbacks() { + for id in Array(accounts.keys) { + accounts[id]?.familySticky = false + accounts[id]?.familyFallbackTried = false + } } func cancelRegistrationRetry(_ id: AccountID) { diff --git a/Sources/MacroSIPCore/Engine/Engine+NetworkOptions.swift b/Sources/MacroSIPCore/Engine/Engine+NetworkOptions.swift index a099a69..3cb5e7b 100644 --- a/Sources/MacroSIPCore/Engine/Engine+NetworkOptions.swift +++ b/Sources/MacroSIPCore/Engine/Engine+NetworkOptions.swift @@ -35,6 +35,7 @@ extension Engine { p.pointee.disable_reg_on_modify = 1 try PJ.check(pjsua_acc_modify(entry.index, p), "pjsua_acc_modify") } + cpjsua_acc_set_sdp_nat_rewrite(entry.index, s.sdpNATRewrite ? 1 : 0) // not copied by modify } catch { PJ.warn(error, "network settings for account \(id.raw)") } diff --git a/Sources/MacroSIPCore/Engine/Engine.swift b/Sources/MacroSIPCore/Engine/Engine.swift index 7967f6b..cb94065 100644 --- a/Sources/MacroSIPCore/Engine/Engine.swift +++ b/Sources/MacroSIPCore/Engine/Engine.swift @@ -54,6 +54,13 @@ public actor Engine { /// The IP family the account is bound to (`IPFamilyPolicy`); decided again on network /// changes and REGISTER retries when it follows the resolver. var family: IPFamily = .ipv4 + /// Auto moved the account to the other family after a REGISTER got no answer; the family + /// that works stays until the next network change (no re-decision before retries). + var familySticky = false + /// The other family was tried at once in this series of failed REGISTERs. + var familyFallbackTried = false + /// A move to another family that waits for the account's calls to end. + var pendingMove: (family: IPFamily, reason: String)? /// Last status given to `publishPresence` (re-applied when the account changes). var presence: PresenceStatus = .available /// Registration requested (cfg.registers or setRegistered): retried after temporary @@ -76,6 +83,12 @@ public actor Engine { /// The families of a host name in the system resolver's order (`IPFamilyResolver.system`; tests /// inject their own so they do not depend on real DNS). var resolveFamilies: @Sendable (String) -> [IPFamily] = { IPFamilyResolver.system($0) } + /// How long the engine waits for family lookups (they run concurrently off the engine queue; a + /// host not resolved in time keeps the account's family, or gives IPv4 for a new account). + var familyLookupTimeout: Duration = .seconds(2) + /// Whether an IPv6 address is still assigned to an interface (`NetworkPath.isAssignedLocally`; + /// tests inject their own). + var ipv6AddressAssigned: @Sendable (String) -> Bool = { NetworkPath.isAssignedLocally($0) } var requestedWiring: [Wire: Bool] = [:] /// Level (0...2) last requested for each connection that is requested on (per-call speaker /// and microphone volume live on the call<->sound device connections). @@ -472,6 +485,9 @@ public actor Engine { emit(.log(level: 1, "engine: \(text)")) } let families = transportFamilies + // pjsua keeps transports in a fixed table (pjsua_var.tpdata, 8 slots, not configurable): + // 4 per family fill it exactly with both families. A further transport needs a PJSIP patch. + assert(families.count * 4 <= Int(cpjsua_transport_slots()), "pjsua has \(cpjsua_transport_slots()) transport slots") for family in families { try createTransports(family, network: network, caFile: caFile, required: family == families.first) } diff --git a/Sources/MacroSIPCore/Engine/EngineBridge.swift b/Sources/MacroSIPCore/Engine/EngineBridge.swift index c87f88e..d039c50 100644 --- a/Sources/MacroSIPCore/Engine/EngineBridge.swift +++ b/Sources/MacroSIPCore/Engine/EngineBridge.swift @@ -114,6 +114,9 @@ final class EngineBridge: Sendable { var pendingRegistration: [AccountID: Bool] = [:] /// Failed REGISTER attempts since the last success (temporary failures only). var retryAttempts: [AccountID: Int] = [:] + /// Accounts being moved to the other IP family: the result of the un-REGISTER of the old + /// binding sent just before the move is not a registration state of the account. + var ignoringUnregister: Set = [] /// Accounts with a repair of a missing binding going on, or given up (see `BindingRepair`). var bindingRepair: [AccountID: BindingRepair] = [:] /// Calls pjsua re-INVITEd in the current network change (by call serial). @@ -226,6 +229,14 @@ final class EngineBridge: Sendable { state.withLock { $0.registrarSources[index] = source } } + func setIgnoringUnregister(_ index: Int32, _ on: Bool) { + state.withLock { if on { $0.ignoringUnregister.insert(index) } else { $0.ignoringUnregister.remove(index) } } + } + + func isIgnoringUnregister(_ index: Int32) -> Bool { + state.withLock { $0.ignoringUnregister.contains(index) } + } + /// The INVITE came from the server that accepted the account's REGISTER, or from its /// outbound proxy (IP literal). func isTrustedSource(_ source: SignallingSource, account index: Int32) -> Bool { @@ -973,15 +984,21 @@ private func pjOnRegStarted2(_ accID: pjsua_acc_id, _ info: UnsafeMutablePointer private func pjOnRegState2(_ accID: pjsua_acc_id, _ info: UnsafeMutablePointer?) { let bridge = EngineBridge.shared guard let account = bridge.account(for: accID) else { return } + // The un-REGISTER of the old binding before a move to the other IP family (Engine.moveAccount). + if let info, info.pointee.renew == 0, bridge.isIgnoringUnregister(accID) { return } let id = account.id var new: RegistrationState var source: SignallingSource? var transientError: String? + /// No response at all (timeout, transport or connection error, no address of the account's + /// family): Auto accounts may try the other IP family at once. + var noAnswer = false var ourContactListed = true if let info, let param = info.pointee.cbparam { let p = param.pointee ourContactListed = cpjsua_regc_lists_our_contact(param, accID) != 0 source = SignallingSource.read(p.rdata) + noAnswer = p.rdata == nil new = RegistrationMapping.state( renew: info.pointee.renew != 0, status: p.status, code: Int(p.code), reason: PJ.string(p.reason), expiration: p.expiration, @@ -1059,7 +1076,8 @@ private func pjOnRegState2(_ accID: pjsua_acc_id, _ info: UnsafeMutablePointer

Bool { + var wanted = in6_addr() + guard inet_pton(AF_INET6, text, &wanted) == 1 else { return false } + var list: UnsafeMutablePointer? + guard getifaddrs(&list) == 0 else { return false } + defer { freeifaddrs(list) } + var entry = list + while let e = entry { + if let sa = e.pointee.ifa_addr, sa.pointee.sa_family == sa_family_t(AF_INET6) { + let found = sa.withMemoryRebound(to: sockaddr_in6.self, capacity: 1) { a -> Bool in + var addr = a.pointee.sin6_addr + return withUnsafeBytes(of: &addr) { x in withUnsafeBytes(of: &wanted) { y in x.elementsEqual(y) } } + } + if found { return true } + } + entry = e.pointee.ifa_next + } + return false + } + /// A global IPv6 address: not unspecified, loopback or link-local (fe80::/10). static func isUsableIPv6Source(_ text: String) -> Bool { var a = in6_addr() diff --git a/Sources/macrosip-cli/Interactive.swift b/Sources/macrosip-cli/Interactive.swift index 288f6fc..20b7abe 100644 --- a/Sources/macrosip-cli/Interactive.swift +++ b/Sources/macrosip-cli/Interactive.swift @@ -32,8 +32,15 @@ final class Interactive { print("start failed: \(error)") exit(1) } - print("macrosip-cli ready. SIP UDP port \(await engine.localPort(of: .udp)), " + - "TCP \(await engine.localPort(of: .tcp)), TLS \(await engine.localPort(of: .tls)). Type 'help'.") + // Each family the engine has transports for (a bind address has one: its own). + var ports: [String] = [] + for family in IPFamily.allCases { + let udp = await engine.localPort(of: .udp, family: family) + guard udp > 0 else { continue } + ports.append("\(family): SIP UDP port \(udp), TCP \(await engine.localPort(of: .tcp, family: family)), " + + "TLS \(await engine.localPort(of: .tls, family: family))") + } + print("macrosip-cli ready. \(ports.joined(separator: "; ")). Type 'help'.") for await line in Interactive.stdinLines() { let words = line.split(separator: " ", omittingEmptySubsequences: true).map(String.init) guard let cmd = words.first else { continue } diff --git a/Sources/macrosip-cli/SelfTest.swift b/Sources/macrosip-cli/SelfTest.swift index ae1c83e..f2a4e13 100644 --- a/Sources/macrosip-cli/SelfTest.swift +++ b/Sources/macrosip-cli/SelfTest.swift @@ -48,7 +48,10 @@ enum SelfTest { network: NetworkSettings(stunServer: nil, localPort: 0, keepAliveSeconds: 15, useICE: false, echoCancellation: false), codecPriorities: Engine.defaultCodecOrder) - step("engine started (null audio), SIP UDP \(bind ?? "*"):\(await engine.localPort(of: .udp))") + // The port of the bind address's family (IPv4 without one, the family the steps below use). + let family = bind.flatMap { IPFamilyPolicy.literalFamily($0) } ?? .ipv4 + let host = bind.map { family == .ipv6 ? "[\($0)]" : $0 } ?? "*" + step("engine started (null audio), SIP UDP \(host):\(await engine.localPort(of: .udp, family: family))") try await networkAtStart(recorder, step: step) let account = AccountConfig(displayName: "selftest", username: "selftest", domain: "127.0.0.1", diff --git a/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift b/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift index 83ff020..af45ba1 100644 --- a/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift +++ b/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift @@ -11,9 +11,10 @@ import Testing /// A SIP stub on [::1]: one UDP socket and one TCP listener, and with `dualStack` a UDP socket on /// 127.0.0.1 with the same port number, so an account at "localhost:" reaches it over either -/// family. Answers REGISTER with 200 (Contacts listed), INVITE with 200 and an `IN IP6 ::1` answer, -/// everything else with 200; requests that arrive on a family in `silentFamilies` are recorded and -/// left unanswered. Records every request with the family and transport it came over. Can send +/// family. Answers REGISTER with 200 (Contacts listed; 403 on a family in `forbiddenFamilies`), +/// INVITE with 200 and an answer in the offer's family (`IN IP6 ::1` or `IN IP4 127.0.0.1`; only 180 +/// with `ringOnly`), everything else with 200; requests that arrive on a family in `silentFamilies` are +/// recorded and left unanswered. Records every request with the family and transport it came over. Can send /// INVITE and MESSAGE to the engine from its UDP sockets; their responses are recorded, a 2xx to /// INVITE is ACKed and the call hung up with BYE. final class IPv6Stub: Sendable { @@ -25,6 +26,10 @@ final class IPv6Stub: Sendable { var contact: String // first Contact value var cseq: String var body: String + /// REGISTER with Expires 0 (or every Contact with expires=0): an un-REGISTER. + var unregister = false + /// The Event header ("message-summary", "presence"). + var event = "" } struct Response: Sendable { @@ -42,6 +47,10 @@ final class IPv6Stub: Sendable { private let rtp6: Int32 private let stopped = OSAllocatedUnfairLock(initialState: false) private let silent = OSAllocatedUnfairLock(initialState: Set()) + private let forbidden = OSAllocatedUnfairLock(initialState: Set()) + private let ringing = OSAllocatedUnfairLock(initialState: false) + /// Headers of the INVITE left ringing (`ringOnly`), for the 487 after a CANCEL. + private let ringingInvite = OSAllocatedUnfairLock<([String], String)?>(initialState: nil) private let received = OSAllocatedUnfairLock(initialState: [Request]()) private let answers = OSAllocatedUnfairLock(initialState: [Response]()) @@ -56,6 +65,16 @@ final class IPv6Stub: Sendable { get { silent.withLock { $0 } } set { silent.withLock { $0 = newValue } } } + var forbiddenFamilies: Set { + get { forbidden.withLock { $0 } } + set { forbidden.withLock { $0 = newValue } } + } + var ringOnly: Bool { + get { ringing.withLock { $0 } } + set { ringing.withLock { $0 = newValue } } + } + /// REGISTERs that add a binding (not un-REGISTERs), in order. + var bindingRegisters: [Request] { registers.filter { !$0.unregister } } init(dualStack: Bool = false) throws { var attempt = 0 @@ -223,7 +242,7 @@ final class IPv6Stub: Sendable { let lines = head.components(separatedBy: "\r\n") guard let first = lines.first else { return } var echoed: [String] = [], toLine = "", cseq = "", topVia = "", contacts: [String] = [], callID = "" - var fromLine = "", expiresZero = false + var fromLine = "", expiresZero = false, expiresHeaderZero = false, event = "" for line in lines.dropFirst() { guard let colon = line.firstIndex(of: ":") else { continue } let name = line[.."], body: sdp) + case "CANCEL": + reply("200 OK") + if let (echo, to) = ringingInvite.withLock({ $0 }) { + ringingInvite.withLock { $0 = nil } + reply("487 Request Terminated", echo: echo.map { $0.replacingOccurrences(of: "CANCEL", with: "INVITE") }, to: to) + } default: reply("200 OK") } @@ -665,21 +707,29 @@ extension EngineTests { await engine.stop() } - /// IPv4 only with an IPv6 server address (and the other way round) is refused, not retried forever. + /// IPv4 only with an IPv6 server address (and the other way round) is refused with + /// `.invalidArgument`, not retried forever. @Test func contradictoryIPProtocolIsRefused() async throws { let engine = await makeEngine(bindAddress: nil) try await engine.start(network: Self.network) + func isInvalidArgument(_ error: EngineError?) -> Bool { + if case .invalidArgument? = error { return true } + return false + } let a = AccountConfig(displayName: "X", username: "1", domain: "[::1]", enabled: false, ipProtocol: .ipv4) - await #expect(throws: EngineError.self) { try await engine.addAccount(a, password: "") } + let e1 = await #expect(throws: EngineError.self) { try await engine.addAccount(a, password: "") } + #expect(isInvalidArgument(e1), "\(String(describing: e1))") var b = a b.domain = "127.0.0.1" b.ipProtocol = .ipv6 - await #expect(throws: EngineError.self) { try await engine.addAccount(b, password: "") } + let e2 = await #expect(throws: EngineError.self) { try await engine.addAccount(b, password: "") } + #expect(isInvalidArgument(e2), "\(String(describing: e2))") b.ipProtocol = .auto try await engine.addAccount(b, password: "") b.domain = "[::1]" b.ipProtocol = .ipv4 - await #expect(throws: EngineError.self) { try await engine.updateAccount(b, password: nil) } + let e3 = await #expect(throws: EngineError.self) { try await engine.updateAccount(b, password: nil) } + #expect(isInvalidArgument(e3), "\(String(describing: e3))") await engine.stop() } @@ -855,68 +905,278 @@ extension EngineTests { } } - /// The family of an Auto host name is decided again on a network change and before a REGISTER retry; - /// when it changed the account is moved to the other transport and registers there. - @Test func familyIsDecidedAgainOnNetworkChangeAndRetry() async throws { - let stub = try IPv6Stub(dualStack: true) - defer { stub.stop() } - let answer = OSAllocatedUnfairLock(initialState: [IPFamily.ipv4, .ipv6]) + /// An Auto account whose host name resolves to both families, registered over UDP. (`answer`: what + /// the injected resolver returns.) + func startAutoLocalhost(_ stub: IPv6Stub, answer: OSAllocatedUnfairLock<[IPFamily]>, transport: TransportKind = .udp, + mwi: Bool = false, publish: Bool = false) async throws -> (Engine, AccountConfig, EventLog, Task) { let engine = await makeEngine(bindAddress: nil) + let log = EventLog() + let consumer = log.consume(engine) await engine.setTestTimings(transactionTimeoutMs: 2000) await engine.setFamilyResolverForTests { _ in answer.withLock { $0 } } try await engine.start(network: Self.network) - let ids = await engine.transportIDsForTests() - let account = AccountConfig(displayName: "L", username: "1009", domain: "localhost", - registrar: "localhost:\(stub.port)", mwi: false) + let port = transport == .tcp ? stub.tcpPort : stub.port + // The domain carries the port, so MWI SUBSCRIBEs (to the account's own URI) reach the stub too. + let account = AccountConfig(displayName: "L", username: "1009", domain: "localhost:\(port)", + transport: transport, publishPresence: publish, mwi: mwi) try await engine.addAccount(account, password: "pw") + return (engine, account, log, consumer) + } + + func logLines(_ log: EventLog, containing text: String) -> [String] { + log.all.compactMap { if case let .log(_, t) = $0, t.contains(text) { return t }; return nil } + } + + /// The family of an Auto host name is decided again on a network change; when it changed, the old + /// binding is removed (un-REGISTER over the old family) before the account registers over the new + /// one, and `allow_sdp_nat_rewrite` follows the family (pjsua_acc_modify does not copy it). + @Test func familyIsDecidedAgainOnNetworkChange() async throws { + let stub = try IPv6Stub(dualStack: true) + defer { stub.stop() } + let answer = OSAllocatedUnfairLock(initialState: [IPFamily.ipv4, .ipv6]) + let (engine, account, _, consumer) = try await startAutoLocalhost(stub, answer: answer) + defer { consumer.cancel() } + let ids = await engine.transportIDsForTests() #expect(await waitUntil { await engine.registrationState(of: account.id).isRegistered }) - #expect(stub.registers.last?.family == .ipv4) + #expect(stub.bindingRegisters.last?.family == .ipv4) + #expect(await engine.liveAccountSettingsForTests(account.id)?.sdpNATRewrite == false) - // Network change: the resolver now puts IPv6 first. answer.withLock { $0 = [.ipv6, .ipv4] } + let mark = stub.registers.count + await engine.simulateNetworkChange() + #expect(await waitUntil { stub.bindingRegisters.last?.family == .ipv6 }) + #expect(await waitUntil { await engine.registrationState(of: account.id).isRegistered }) + let after = Array(stub.registers.dropFirst(mark)) + let unregister = after.firstIndex { $0.unregister && $0.family == .ipv4 } + let register6 = after.firstIndex { !$0.unregister && $0.family == .ipv6 } + #expect(unregister != nil && register6 != nil && unregister! < register6!, "\(after.map { "\($0.family) \($0.unregister)" })") + let live = try #require(await engine.liveAccountSettingsForTests(account.id)) + #expect(live.transportID == ids.udp6 && live.sdpNATRewrite && live.mediaIPv6Only) + + answer.withLock { $0 = [.ipv4, .ipv6] } await engine.simulateNetworkChange() - #expect(await waitUntil { stub.registers.last?.family == .ipv6 }) + #expect(await waitUntil { stub.bindingRegisters.last?.family == .ipv4 }) #expect(await waitUntil { await engine.registrationState(of: account.id).isRegistered }) - #expect(await engine.liveAccountSettingsForTests(account.id)?.transportID == ids.udp6) + #expect(await engine.liveAccountSettingsForTests(account.id)?.sdpNATRewrite == false) + await engine.stop() + } + + /// Changing the IP protocol in the editor (updateAccount) moves the account too: old binding removed, + /// `allow_sdp_nat_rewrite` set for the new family. + @Test func ipProtocolChangeMovesTheAccount() async throws { + let stub = try IPv6Stub(dualStack: true) + defer { stub.stop() } + let answer = OSAllocatedUnfairLock(initialState: [IPFamily.ipv4, .ipv6]) + let (engine, account, _, consumer) = try await startAutoLocalhost(stub, answer: answer) + defer { consumer.cancel() } + #expect(await waitUntil { await engine.registrationState(of: account.id).isRegistered }) + var six = account + six.ipProtocol = .ipv6 + let mark = stub.registers.count + try await engine.updateAccount(six, password: nil) + #expect(await waitUntil { stub.bindingRegisters.last?.family == .ipv6 }) + #expect(await waitUntil { await engine.registrationState(of: account.id).isRegistered }) + #expect(stub.registers.dropFirst(mark).contains { $0.unregister && $0.family == .ipv4 }) + #expect(await engine.liveAccountSettingsForTests(account.id)?.sdpNATRewrite == true) + await engine.stop() + } - // IPv6 stops answering; the retry after the timeout finds IPv4 first again. + /// Auto follows the system order for the first REGISTER; when that gets no answer at all (here: the + /// IPv6 side of the server is silent), it moves to the other family at once and registers there. + /// The working family then stays (sticky) until the next network change: a later retry stays on it. + @Test func autoFallsBackToTheOtherFamilyWithoutAnswer() async throws { + let stub = try IPv6Stub(dualStack: true) + defer { stub.stop() } stub.silentFamilies = [.ipv6] - let count = stub.registers.count + let answer = OSAllocatedUnfairLock(initialState: [IPFamily.ipv6, .ipv4]) + let (engine, account, log, consumer) = try await startAutoLocalhost(stub, answer: answer) + defer { consumer.cancel() } + #expect(await waitUntil(timeout: 6) { await engine.registrationState(of: account.id).isRegistered }) + #expect(stub.bindingRegisters.map(\.family).prefix(1) == [.ipv6]) + #expect(stub.bindingRegisters.last?.family == .ipv4) + #expect(await engine.accountFamilyForTests(account.id) == .ipv4) + #expect(!logLines(log, containing: "no answer over IPv6; trying IPv4").isEmpty) + + // Sticky: IPv4 goes silent too; the backoff retry stays on IPv4 (the resolver still says IPv6 + // first), and only its failure moves the account back to IPv6, which answers again. + stub.silentFamilies = [.ipv4] + let mark = stub.bindingRegisters.count try await engine.setRegistered(account.id, true) - #expect(await waitUntil(timeout: 6) { - if case .reconnecting = await engine.registrationState(of: account.id) { return true } + #expect(await waitUntil(timeout: 10) { await engine.registrationState(of: account.id).isRegistered + && stub.bindingRegisters.count > mark + 2 }) + let families = stub.bindingRegisters.dropFirst(mark).map(\.family) + #expect(Array(families.prefix(3)) == [.ipv4, .ipv4, .ipv6], "\(families)") + await engine.stop() + } + + /// A TCP connection that is refused counts as no answer: the account moves to IPv6 at once. + @Test func autoFallsBackWhenTheConnectionIsRefused() async throws { + let stub = try IPv6Stub() // TCP on [::1] only + defer { stub.stop() } + let answer = OSAllocatedUnfairLock(initialState: [IPFamily.ipv4, .ipv6]) + let (engine, account, _, consumer) = try await startAutoLocalhost(stub, answer: answer, transport: .tcp) + defer { consumer.cancel() } + #expect(await waitUntil(timeout: 4) { await engine.registrationState(of: account.id).isRegistered }) + #expect(stub.registers.last?.family == .ipv6 && stub.registers.last?.transport == "TCP") + #expect(await engine.accountFamilyForTests(account.id) == .ipv6) + await engine.stop() + } + + /// A server that answers (403) is not a reason to try the other family. + @Test func autoKeepsTheFamilyWhenTheServerAnswers() async throws { + let stub = try IPv6Stub(dualStack: true) + defer { stub.stop() } + stub.forbiddenFamilies = [.ipv6] + let answer = OSAllocatedUnfairLock(initialState: [IPFamily.ipv6, .ipv4]) + let (engine, account, _, consumer) = try await startAutoLocalhost(stub, answer: answer) + defer { consumer.cancel() } + #expect(await waitUntil { + if case .failed(403, _) = await engine.registrationState(of: account.id) { return true } return false }) - answer.withLock { $0 = [.ipv4, .ipv6] } - #expect(await waitUntil(timeout: 8) { await engine.registrationState(of: account.id).isRegistered }) - #expect(stub.registers.dropFirst(count).last?.family == .ipv4) - #expect(await engine.liveAccountSettingsForTests(account.id)?.transportID == ids.udp) + try await Task.sleep(for: .milliseconds(500)) + #expect(stub.registers.allSatisfy { $0.family == .ipv6 }) + #expect(await engine.accountFamilyForTests(account.id) == .ipv6) + await engine.stop() + } + + /// An account is never moved to the other family while it has a call (the dialog would keep + /// the old family's peer and lose its transport): the round keeps it, the move waits for the + /// call to end, then the account moves and registers. + @Test func familyMoveWaitsForTheAccountsCalls() async throws { + let stub = try IPv6Stub(dualStack: true) + defer { stub.stop() } + let answer = OSAllocatedUnfairLock(initialState: [IPFamily.ipv4, .ipv6]) + let (engine, account, log, consumer) = try await startAutoLocalhost(stub, answer: answer) + defer { consumer.cancel() } + #expect(await waitUntil { await engine.registrationState(of: account.id).isRegistered }) + let call = try await engine.makeCall(to: DialString(uri: "sip:300@localhost:\(stub.port)", display: "300"), from: account.id) + #expect(await waitUntil { await engine.calls().first { $0.id == call }?.state == .connected }) + + answer.withLock { $0 = [.ipv6, .ipv4] } + await engine.simulateNetworkChange() + #expect(await waitUntil { await engine.ipChangeStateForTests().running == nil }) + try await Task.sleep(for: .milliseconds(500)) + #expect(await engine.accountFamilyForTests(account.id) == .ipv4) + #expect(stub.bindingRegisters.allSatisfy { $0.family == .ipv4 }) + #expect(await engine.calls().first { $0.id == call }?.state == .connected) + #expect(!logLines(log, containing: "waits for its calls").isEmpty) + + try await engine.hangup(call) + #expect(await waitUntil { await engine.calls().isEmpty }) + #expect(await waitUntil(timeout: 4) { stub.bindingRegisters.last?.family == .ipv6 }) + #expect(await waitUntil { await engine.registrationState(of: account.id).isRegistered }) + #expect(await engine.accountFamilyForTests(account.id) == .ipv6) await engine.stop() } - /// A new IPv6 source address (a new temporary address) starts a round only when it matters: IPv6 - /// appearing does, a later new address does not while no account uses IPv6, and does once one does. - @Test func newIPv6AddressStartsRoundOnlyForIPv6Accounts() async throws { + /// After a move, the voicemail (MWI) and presence subscriptions are made anew over the new family + /// (their dialogs keep the transport they were created with). + @Test func subscriptionsFollowAFamilyMove() async throws { + let stub = try IPv6Stub(dualStack: true) + defer { stub.stop() } + let answer = OSAllocatedUnfairLock(initialState: [IPFamily.ipv4, .ipv6]) + let (engine, account, _, consumer) = try await startAutoLocalhost(stub, answer: answer, mwi: true) + defer { consumer.cancel() } + #expect(await waitUntil { await engine.registrationState(of: account.id).isRegistered }) + try await engine.subscribePresence(uri: "sip:200@localhost:\(stub.port)") + func subscribes(_ event: String, _ family: IPFamily) -> Int { + stub.requests.filter { $0.method == "SUBSCRIBE" && $0.event.hasPrefix(event) && $0.family == family }.count + } + #expect(await waitUntil { subscribes("message-summary", .ipv4) > 0 && subscribes("presence", .ipv4) > 0 }, + "\(stub.requests.map { "\($0.method) \($0.event) \($0.family)" })") + + answer.withLock { $0 = [.ipv6, .ipv4] } + await engine.simulateNetworkChange() + #expect(await waitUntil { await engine.accountFamilyForTests(account.id) == .ipv6 }) + #expect(await waitUntil { subscribes("message-summary", .ipv6) > 0 }, "\(stub.requests.map { "\($0.method) \($0.event) \($0.family)" })") + #expect(await waitUntil { subscribes("presence", .ipv6) > 0 }, "\(stub.requests.map { "\($0.method) \($0.event) \($0.family)" })") + await engine.stop() + } + + /// Family lookups during a round are made once per host name, concurrently and off the engine + /// queue's critical path: a slow resolver delays the round by the lookup limit at most, and an + /// account whose lookup did not finish keeps its family. `addAccount` waits no longer either. + @Test func familyLookupsAreDedupedAndBounded() async throws { + let calls = OSAllocatedUnfairLock(initialState: [String: Int]()) + let slow = OSAllocatedUnfairLock(initialState: false) let engine = await makeEngine(bindAddress: nil) + await engine.setFamilyLookupTimeoutForTests(.milliseconds(300)) + await engine.setFamilyResolverForTests { host in + calls.withLock { $0[host, default: 0] += 1 } + if slow.withLock({ $0 }) { Thread.sleep(forTimeInterval: 1.5); return [.ipv6, .ipv4] } + return [.ipv4, .ipv6] + } + try await engine.start(network: Self.network) + let a = AccountConfig(displayName: "A", username: "1", domain: "localhost", registerWithServer: false, mwi: false) + let b = AccountConfig(displayName: "B", username: "2", domain: "localhost", registerWithServer: false, mwi: false) + try await engine.addAccount(a, password: "") + try await engine.addAccount(b, password: "") + #expect(await engine.accountFamilyForTests(a.id) == .ipv4) + + slow.withLock { $0 = true } + calls.withLock { $0 = [:] } + let started = ContinuousClock.now + await engine.simulateNetworkChange() + #expect(ContinuousClock.now - started < .seconds(1.2)) + #expect(calls.withLock { $0["localhost"] } == 1) + #expect(await engine.accountFamilyForTests(a.id) == .ipv4) + #expect(await engine.accountFamilyForTests(b.id) == .ipv4) + + let c = AccountConfig(displayName: "C", username: "3", domain: "localhost", registerWithServer: false, mwi: false) + let added = ContinuousClock.now + try await engine.addAccount(c, password: "") + #expect(ContinuousClock.now - added < .seconds(1.2)) + #expect(await engine.accountFamilyForTests(c.id) == .ipv4) // not resolved in time: IPv4 + await engine.stop() + } + + /// IPv6 address changes (pure rules through injected paths): IPv6 appearing or a new address + /// without IPv6 accounts starts no round (the family of Auto accounts is decided again without + /// one); with an IPv6 account a new temporary address whose predecessor is still assigned is a + /// non-primary change (it waits for a ringing outgoing call), while losing the address is primary. + @Test func ipv6AddressChangesStartRoundsOnlyWhenTheyMatter() async throws { + let stub = try IPv6Stub() + defer { stub.stop() } + let assigned = OSAllocatedUnfairLock(initialState: Set()) + let engine = await makeEngine(bindAddress: nil) + await engine.setIPv6AddressAssignedForTests { address in assigned.withLock { $0.contains(address) } } try await engine.start(network: Self.network) func path(_ v6: String) -> NetworkPath { NetworkPath(satisfied: true, interface: "en0", address: "192.168.1.20", address6: v6, gateway: "192.168.1.1") } func settle() async { _ = await waitUntil { await engine.ipChangeStateForTests().running == nil } } + func rounds() async -> UInt64 { await engine.ipChangeStateForTests().rounds } await engine.applyPathForTests(path("")) // a new primary route await settle() - var rounds = await engine.ipChangeStateForTests().rounds - await engine.applyPathForTests(path("2001:db8::10")) // IPv6 appeared + var count = await rounds() + assigned.withLock { $0 = ["2001:db8::10"] } + await engine.applyPathForTests(path("2001:db8::10")) // IPv6 appeared, no IPv6 account await settle() - #expect(await engine.ipChangeStateForTests().rounds == rounds + 1) - rounds += 1 - await engine.applyPathForTests(path("2001:db8::11")) // rotated; no IPv6 account + #expect(await rounds() == count) + assigned.withLock { $0 = ["2001:db8::10", "2001:db8::11"] } + await engine.applyPathForTests(path("2001:db8::11")) // rotated, no IPv6 account await settle() - #expect(await engine.ipChangeStateForTests().rounds == rounds) - try await engine.addAccount(localIPv6Account("6"), password: "") - await engine.applyPathForTests(path("2001:db8::12")) + #expect(await rounds() == count) + + let account = localIPv6Account("6") + try await engine.addAccount(account, password: "") + stub.ringOnly = true + let call = try await engine.makeCall(to: DialString(uri: "sip:300@[::1]:\(stub.port)", display: "300"), from: account.id) + #expect(await waitUntil { await engine.calls().first { $0.id == call }?.state == .early }) + assigned.withLock { $0 = ["2001:db8::11", "2001:db8::12"] } + await engine.applyPathForTests(path("2001:db8::12")) // rotated, ::11 still assigned + #expect(await engine.ipChangeStateForTests().postponed) + #expect(await rounds() == count) + #expect(await engine.calls().first { $0.id == call }?.state == .early) + + assigned.withLock { $0 = [] } + await engine.applyPathForTests(path("")) // IPv6 lost: primary, at once + #expect(await waitUntil { await rounds() == count + 1 }) + count += 1 await settle() - #expect(await engine.ipChangeStateForTests().rounds == rounds + 1) + try? await engine.hangup(call) + #expect(await waitUntil(timeout: 5) { await engine.calls().isEmpty }) await engine.stop() } diff --git a/docs/ENGINE.md b/docs/ENGINE.md index 25a7b6c..238ce88 100644 --- a/docs/ENGINE.md +++ b/docs/ENGINE.md @@ -342,9 +342,9 @@ Goal: a network drop, a Wi-Fi -> Ethernet/LTE switch, an IP change or sleep/wake **Ordering.** Path updates go through one `AsyncStream` per `NWPathMonitor` and are applied by one consumer task in order (a Task per update could apply an unsatisfied/satisfied pair at wake reversed and leave the engine offline). Follow-up work from PJSIP callbacks (`EngineBridge.hop`) also runs through one ordered queue (one consumer task per started engine), so for example two final responses of the same call, or a REGISTER result and the end of a network change, are handled in the order PJSIP reported them. -**Path monitoring.** `NWPathMonitor` on its own queue (`macrosip.network`). `.satisfied` = online. A path is reduced to its primary route (`NetworkPath`): the first available interface (the one the system routes through), the source address of the default route (a UDP socket "connected" to 192.0.2.1 and read back with getsockname: the address pjsua's sockets use towards a server on the default route), the same for the default IPv6 route (2001:db8::1; a global address only, see "IPv6") and the first gateway. Secondary interfaces (bridge100 of Internet Sharing, a split-tunnel utun, a second Wi-Fi) coming and going change nothing; a full-tunnel VPN that takes the default route changes the interface and the address. The first update after `start` and every update while a wake is pending are applied at once; later ones are debounced by 2.5 s (the last one wins). Online -> offline: `.network(.offline)`, calls get `isReconnecting`. Offline -> online: `.network(.online)` and a round; a changed primary route while online: a round. A new local address on the same interface and gateway that produces no path update is not noticed (keep-alives, `allow_contact_rewrite` and the next REGISTER refresh deal with it). If no update arrives within 2 s after start, `.network(.online)` is emitted anyway. A satisfied path without a default route (the 192.0.2.1 lookup fails) keeps the previous address and counts as unchanged (logged); the same per family, so an IPv6-only network keeps the last IPv4 address and an IPv4-only one the last IPv6 address (the line is logged only when both are missing). `Engine(monitorNetwork: false)` runs no NWPathMonitor: the network counts as online from `start` (a fixed path is reported at once) and only paths injected by tests change it; the engine tests use it so they do not depend on the host's network. +**Path monitoring.** `NWPathMonitor` on its own queue (`macrosip.network`). `.satisfied` = online. A path is reduced to its primary route (`NetworkPath`): the first available interface (the one the system routes through), the source address of the default route (a UDP socket "connected" to 192.0.2.1 and read back with getsockname: the address pjsua's sockets use towards a server on the default route), the same for the default IPv6 route (2001:db8::1; a global address only, see "IPv6") and the first gateway. Secondary interfaces (bridge100 of Internet Sharing, a split-tunnel utun, a second Wi-Fi) coming and going change nothing; a full-tunnel VPN that takes the default route changes the interface and the address. The first update after `start` and every update while a wake is pending are applied at once; later ones are debounced by 2.5 s (the last one wins). Online -> offline: `.network(.offline)`, calls get `isReconnecting`. Offline -> online: `.network(.online)` and a round; a changed primary route while online: a round. A new local address on the same interface and gateway that produces no path update is not noticed (keep-alives, `allow_contact_rewrite` and the next REGISTER refresh deal with it). If no update arrives within 2 s after start, `.network(.online)` is emitted anyway. A satisfied path without a default route (the 192.0.2.1 lookup fails) keeps the previous address and counts as unchanged (logged); an IPv6-only network keeps the last IPv4 address the same way; the last IPv6 address is kept only while it is still assigned to an interface, so losing IPv6 is a change (the line is logged only when both are missing). IPv6 changes follow their own rules (see "IPv6": no round without IPv6 accounts, non-primary for a new temporary address). `Engine(monitorNetwork: false)` runs no NWPathMonitor: the network counts as online from `start` (a fixed path is reported at once) and only paths injected by tests change it; the engine tests use it so they do not depend on the host's network. -**Rounds (`requestIPChange` / `performIPChange`).** One round = one `pjsua_handle_ip_change`. Rounds never overlap: a request while a round runs is queued (the latest reason, flags merged) and started when the round completes. A request is "primary" when the interface or the local address changed (and for `simulateNetworkChange`); otherwise (gateway-only change, network back with the same address, wake with the same address) it is postponed while an outgoing call is still unanswered and runs when no outgoing call rings any more (checked every second, at most 90 s): pjsua hangs up an account's unconfirmed outgoing calls with 410 after that account's re-REGISTER (`pjsua_acc_handle_call_on_ip_change`; test `ringingCallOfReRegisteringAccountEndsOnAddressChange`), which is accepted only when the address really changed (such a call cannot complete then anyway). Steps: (1) every confirmed call gets `reinviteWanted = round` (`isReconnecting`). (2) Auto accounts with a host name decide their IP family again and move to the other family's transport when it changed (`refreshAccountFamilies`, see "IPv6"); then `cpjsua_acc_prepare_ip_change` per account decides whether pjsua re-REGISTERs it: pjsua's `handle_ip_change_on_acc` re-registers an account without a registration session only when its last REGISTER status was 200 or a temporary failure, and would therefore also REGISTER an account the user switched off (last code 200 after the un-REGISTER) and skip a working outgoing-only account's calls. The shim sets that internal status to 200 for accounts that should be registered (not while asleep; `.failed` ones only on wake) and to 0 for the rest, which pjsua then skips ("Permanent registration failure, IP change handling will stop for acc N" in PJSIP's log is this skip). A REGISTER that still arrives for an account that is off is undone. (3) `keep_inv_after_tsx_timeout` is switched on by the engine before pjsua sees it (pjsua then does not schedule its own timer that would switch it off one transaction timeout later, while re-INVITEs may still run) and off again when no round runs and no call waits for its re-INVITE, and after `pjsua_destroy`: a re-INVITE that times out does not end the call inside PJSIP; the engine decides. (4) `pjsua_handle_ip_change`: `shutdown_transport` (all TCP/TLS connections), `restart_listener` only when the engine is bound to all interfaces (a restart rebinds to 0.0.0.0 and recomputes the published address; with `bindAddress` set, as in the tests and the self-test, it would undo the binding), `restart_lis_delay` 100 ms. Account config: `ip_change_cfg.shutdown_tp = true`, `hangup_calls = false`, `reinvite_flags = PJSUA_CALL_REINIT_MEDIA | PJSUA_CALL_UPDATE_CONTACT | PJSUA_CALL_UPDATE_VIA`. pjsua re-REGISTERs (new Contact through `allow_contact_rewrite`) and after the 2xx re-INVITEs that account's confirmed calls. (5) On `PJSUA_IP_CHANGE_OP_COMPLETED` of this round (or after one transaction timeout + 5 s without it, so a late report cannot close the next round) the engine re-INVITEs every call of step 1 that pjsua did not (`PJSUA_IP_CHANGE_OP_ACC_REINVITE_CALLS` reports those), except calls whose account's re-REGISTER is still unanswered (pjsua re-INVITEs them after the answer; two re-INVITEs would reinitialise the media twice). Same flags, local hold kept (no UNHOLD flag, pjsua offers the hold SDP), audio only. Then a queued request runs. +**Rounds (`requestIPChange` / `performIPChange`).** One round = one `pjsua_handle_ip_change`. Rounds never overlap: a request while a round runs is queued (the latest reason, flags merged) and started when the round completes. A request is "primary" when the interface or the local address changed (and for `simulateNetworkChange`); otherwise (gateway-only change, network back with the same address, wake with the same address) it is postponed while an outgoing call is still unanswered and runs when no outgoing call rings any more (checked every second, at most 90 s): pjsua hangs up an account's unconfirmed outgoing calls with 410 after that account's re-REGISTER (`pjsua_acc_handle_call_on_ip_change`; test `ringingCallOfReRegisteringAccountEndsOnAddressChange`), which is accepted only when the address really changed (such a call cannot complete then anyway). Steps: (1) every confirmed call gets `reinviteWanted = round` (`isReconnecting`). (2) Auto accounts with a host name decide their IP family again and move to the other family's transport when it changed, except accounts with calls, whose move waits (`refreshAccountFamilies`, see "IPv6"); then `cpjsua_acc_prepare_ip_change` per account decides whether pjsua re-REGISTERs it: pjsua's `handle_ip_change_on_acc` re-registers an account without a registration session only when its last REGISTER status was 200 or a temporary failure, and would therefore also REGISTER an account the user switched off (last code 200 after the un-REGISTER) and skip a working outgoing-only account's calls. The shim sets that internal status to 200 for accounts that should be registered (not while asleep; `.failed` ones only on wake) and to 0 for the rest, which pjsua then skips ("Permanent registration failure, IP change handling will stop for acc N" in PJSIP's log is this skip). A REGISTER that still arrives for an account that is off is undone. (3) `keep_inv_after_tsx_timeout` is switched on by the engine before pjsua sees it (pjsua then does not schedule its own timer that would switch it off one transaction timeout later, while re-INVITEs may still run) and off again when no round runs and no call waits for its re-INVITE, and after `pjsua_destroy`: a re-INVITE that times out does not end the call inside PJSIP; the engine decides. (4) `pjsua_handle_ip_change`: `shutdown_transport` (all TCP/TLS connections), `restart_listener` only when the engine is bound to all interfaces (a restart rebinds to 0.0.0.0 and recomputes the published address; with `bindAddress` set, as in the tests and the self-test, it would undo the binding), `restart_lis_delay` 100 ms. Account config: `ip_change_cfg.shutdown_tp = true`, `hangup_calls = false`, `reinvite_flags = PJSUA_CALL_REINIT_MEDIA | PJSUA_CALL_UPDATE_CONTACT | PJSUA_CALL_UPDATE_VIA`. pjsua re-REGISTERs (new Contact through `allow_contact_rewrite`) and after the 2xx re-INVITEs that account's confirmed calls. (5) On `PJSUA_IP_CHANGE_OP_COMPLETED` of this round (or after one transaction timeout + 5 s without it, so a late report cannot close the next round) the engine re-INVITEs every call of step 1 that pjsua did not (`PJSUA_IP_CHANGE_OP_ACC_REINVITE_CALLS` reports those), except calls whose account's re-REGISTER is still unanswered (pjsua re-INVITEs them after the answer; two re-INVITEs would reinitialise the media twice). Same flags, local hold kept (no UNHOLD flag, pjsua offers the hold SDP), audio only. Then a queued request runs. **The engine's re-INVITE.** `reinviteInFlight = round` is set before `pjsua_call_reinvite2` is called (on loopback the answer can arrive before it returns) and put back if the call fails synchronously. A transaction in flight (hold, the remote's re-INVITE, an older round's re-INVITE) is waited for in 250 ms steps for up to one transaction timeout. Retry and busy tasks are kept per call and cancelled when a new round starts. @@ -354,7 +354,7 @@ Goal: a network drop, a Wi-Fi -> Ethernet/LTE switch, an IP change or sleep/wake **Media watchdog** (1 s tick, `ContinuousClock`, so wall-clock jumps do not count): per confirmed call the RTP packet count and the number of RTCP reports received (`rtcp.tx.update_cnt`). Clocks pause while the media is not active (local or remote hold), the network is offline or the Mac sleeps; a counter that goes back (new stream after a re-INVITE) restarts them and disarms the watchdog until RTCP arrives on the new stream. Armed only after at least one RTCP report on the stream (a peer without RTCP is never ended by it). No RTP and no RTCP for 60 s while online: an in-dialog OPTIONS probe; 408 or 481 -> the call ends as connection lost (PJSIP ends the dialog on these itself; the bridge maps that end the same way); any other answer (200, 405, 501) -> the call stays and the next probe is one period later. Offline calls are never ended by the engine. -**REGISTER retry with backoff.** pjsua's own retry is off (`reg_retry_interval = 0`, `drop_calls_on_reg_fail = false`). `RegistrationMapping.isTemporary`: 408, 480, 500, 502, 503, 504, no code, or a local failure (status other than PJ_SUCCESS: transport error, DNS failure, `PJSIP_ETPNOTAVAIL`, a refresh that could not be sent) -> temporary; 401/403/404/407/423 and every other 4xx-6xx -> `.failed`, no retry. Also permanent: TLS certificate and TLS configuration errors (the reason contains the text of `PJSIP_TLS_ECERTVERIF`, `ECACERT`, `ECERTFILE`, `EKEYFILE`, `EINVMETHOD`, `ECIPHER`, or "certificate"), and a host name that does not resolve (`PJ_ERESOLVE`, `PJLIB_UTIL_EDNS_NXDOMAIN`) after the network has been online for 10 s (a typo in the server name; right after a change DNS may not work yet, so then it is retried). A temporary failure of an account that should be registered emits `.reconnecting(attempt: n, nextRetryIn: d, lastError:)` with d = 2, 4, 8, 16, 32, then 60 s (`RegistrationBackoff`), and a timer sends the REGISTER again after d (an Auto account with a host name first decides its IP family again, see "IPv6"). While a retry runs the state stays `.reconnecting` (no `.registering` in between). Success resets the count. A request that met `PJSIP_EBUSY` (a REGISTER in flight) is remembered and repeated when that transaction ends, except when its result is a temporary failure: then only the backoff retry sends the next REGISTER (26.0.1 sent both, so every retry met EBUSY and a REGISTER left after each transaction timeout without backoff). A REGISTER that cannot even be sent (without a network DNS and sendto fail inside `pjsua_acc_set_registration`; pjsua reports it through `on_reg_state2` before returning the error) is such a temporary failure too: `addAccount`, `updateAccount` and `setRegistered` do not throw or roll back for it (deviation from milestone 2.1's "addAccount rolls back if the registration cannot start", which still holds for other errors), the account stays and is retried, so the app can start offline. A retry that falls due while offline or asleep is not sent (the network coming back or wake re-registers through a round); during a round it waits for it. `setRegistered(true)`, `updateAccount` and wake start a fresh series; switching off cancels it. TCP/TLS: `on_transport_state` DISCONNECTED/SHUTDOWN of the transport an account's registration uses (pjsua's own registration bookkeeping, read in the callback before pjsua releases it) counts as a temporary failure ("TLS connection to ... disconnected") -> the same backoff; ignored during a round (it closes them on purpose). Keep-alives are unchanged. +**REGISTER retry with backoff.** pjsua's own retry is off (`reg_retry_interval = 0`, `drop_calls_on_reg_fail = false`). `RegistrationMapping.isTemporary`: 408, 480, 500, 502, 503, 504, no code, or a local failure (status other than PJ_SUCCESS: transport error, DNS failure, `PJSIP_ETPNOTAVAIL`, a refresh that could not be sent) -> temporary; 401/403/404/407/423 and every other 4xx-6xx -> `.failed`, no retry. Also permanent: TLS certificate and TLS configuration errors (the reason contains the text of `PJSIP_TLS_ECERTVERIF`, `ECACERT`, `ECERTFILE`, `EKEYFILE`, `EINVMETHOD`, `ECIPHER`, or "certificate"), and a host name that does not resolve (`PJ_ERESOLVE`, `PJLIB_UTIL_EDNS_NXDOMAIN`) after the network has been online for 10 s (a typo in the server name; right after a change DNS may not work yet, so then it is retried). A temporary failure of an account that should be registered emits `.reconnecting(attempt: n, nextRetryIn: d, lastError:)` with d = 2, 4, 8, 16, 32, then 60 s (`RegistrationBackoff`), and a timer sends the REGISTER again after d (an Auto account with a host name first decides its IP family again unless Auto moved it after a REGISTER without any answer, which also happens at once, without waiting for d; see "IPv6"). While a retry runs the state stays `.reconnecting` (no `.registering` in between). Success resets the count. A request that met `PJSIP_EBUSY` (a REGISTER in flight) is remembered and repeated when that transaction ends, except when its result is a temporary failure: then only the backoff retry sends the next REGISTER (26.0.1 sent both, so every retry met EBUSY and a REGISTER left after each transaction timeout without backoff). A REGISTER that cannot even be sent (without a network DNS and sendto fail inside `pjsua_acc_set_registration`; pjsua reports it through `on_reg_state2` before returning the error) is such a temporary failure too: `addAccount`, `updateAccount` and `setRegistered` do not throw or roll back for it (deviation from milestone 2.1's "addAccount rolls back if the registration cannot start", which still holds for other errors), the account stays and is retried, so the app can start offline. A retry that falls due while offline or asleep is not sent (the network coming back or wake re-registers through a round); during a round it waits for it. `setRegistered(true)`, `updateAccount` and wake start a fresh series; switching off cancels it. TCP/TLS: `on_transport_state` DISCONNECTED/SHUTDOWN of the transport an account's registration uses (pjsua's own registration bookkeeping, read in the callback before pjsua releases it) counts as a temporary failure ("TLS connection to ... disconnected") -> the same backoff; ignored during a round (it closes them on purpose). Keep-alives are unchanged. **A 2xx that leaves out our Contact.** A 2xx to a REGISTER lists the bindings the server holds. Behind NAT with Asterisk's `rewrite_contact=yes`, PJSIP's Contact rewrite (`PJSUA_CONTACT_REWRITE_NO_UNREG`) sends the new Contact and the old one at expires=0 in one request; the server rewrites both to the source address, adds and removes the same binding, and answers 200 with no Contact. Until the next refresh, up to the registration interval, no incoming call arrives. `pjOnRegState2` checks the answer (`cpjsua_regc_lists_our_contact`, other devices on the extension do not count) and sends the REGISTER again, now with one Contact; the account shows as registered only after that. A server that leaves it out again is believed from then on (`BindingRepair`), so it gets one extra REGISTER and not one per refresh. @@ -379,18 +379,20 @@ Code: `Model/NetworkSettings.swift` (fields, decoding, `isValidRTPRange`, `effec ## IPv6 Dual stack since 26.3.1 ([#11](https://github.com/HSMM/MacroSIP/issues/11), ADR 0014). Code: `IPFamily.swift` (`IPFamily`, `IPFamilyPolicy`, `IPFamilyResolver`, `SIPHop`), `transportFamilies` and `createTransports` in `Engine.swift`, `decideFamily` and `refreshAccountFamily` in `Engine+Accounts.swift`, `TransportIDs` and `AccountMapping.settings(... family:)`, `NetworkPath.address6`; C helpers `cpjsua_tls_transport_create(type, ...)` and `cpjsua_call_local_rtp_addr`. Setting: `AccountConfig.ipProtocol` (account editor › Advanced › Connection › IP protocol: Auto, IPv4 only, IPv6 only). -- **Transports.** Every transport has an IPv6 twin: UDP6, TCP6, TLS6 verifying and TLS6 non-verifying (`TransportIDs.udp6`, `tcp6`, `tls6`, `tls6NoVerify`). pjlib sets `IPV6_V6ONLY` on every IPv6 socket (`PJ_SOCK_HAS_IPV6_V6ONLY` is 1 in our build, `pj_sock_socket`), so `[::]:P` and `0.0.0.0:P` coexist and both families listen on the configured `localPort` (TLS on a random port, as before; with port 0 each family gets its own random port). The IPv4 UDP transport is required as before; the IPv6 ones are best effort: a failure is logged ("UDP over IPv6 transport on port P: ...") and only the accounts that would need that transport are refused (`EngineError.transportUnavailable(kind, ipv6: true)`). Without a global IPv6 address pjsua publishes the UDP6 transport with a link-local or loopback address (`pj_gethostip`), which only a server on the same link or on loopback can use. `localPort(of:family:)` reports the ports; `localPort(of:)` stays IPv4. +- **Transports.** Every transport has an IPv6 twin: UDP6, TCP6, TLS6 verifying and TLS6 non-verifying (`TransportIDs.udp6`, `tcp6`, `tls6`, `tls6NoVerify`). pjlib sets `IPV6_V6ONLY` on every IPv6 socket (`PJ_SOCK_HAS_IPV6_V6ONLY` is 1 in our build, `pj_sock_socket`), so `[::]:P` and `0.0.0.0:P` coexist and both families listen on the configured `localPort` (TLS on a random port, as before; with port 0 each family gets its own random port). The IPv4 UDP transport is required as before; the IPv6 ones are best effort: a failure is logged ("UDP over IPv6 transport on port P: ...") and only the accounts that would need that transport are refused (`EngineError.transportUnavailable(kind, ipv6: true)`). Without a global IPv6 address pjsua publishes the UDP6 transport with a link-local or loopback address (`pj_gethostip`), which only a server on the same link or on loopback can use. `localPort(of:family:)` reports the ports; `localPort(of:)` stays IPv4. pjsua keeps transports in a fixed table of 8 (`pjsua_var.tpdata[8]` in pjsua_internal.h, not a configurable macro): two families of four fill it exactly, so another transport needs a PJSIP patch (`createTransports` asserts it, `cpjsua_transport_slots`). - **Bind address** (`Engine(bindAddress:)`, `macrosip-cli --bind`; brackets are dropped, "[::1]" is "::1"). An address of one family creates that family's transports only, and its UDP is the required one; accounts of the other family are refused with `transportUnavailable`. No bind address: both families on all interfaces. RTP binds to the bind address only for accounts of its family (`AccountMapping`), which with a bind address are the only ones. A bind address that is not an IP literal counts as IPv4 (pjsua resolves it for an IPv4 socket). - **Accounts stay bound.** `pjsua_init_tpselector` turns `transport_id` into a TRANSPORT selector (UDP) or a LISTENER selector (TCP/TLS), which fixes the family; `ipv6_sip_use` (`PJSIP_TPSELECTOR_IP_VER`) only applies to unbound accounts. Unbinding would change Contact and Via under STUN and lose the choice between the verifying and the non-verifying TLS listener, so every account is bound to the transport of its family. pjsua then takes Contact and Via from that transport (`pjsua_acc_get_uac_addr` adds the IPv6 flag for an account whose `tp_type` is IPv6), and an incoming request over UDP6, TCP6 or TLS6 scores the transport match only for the accounts bound to that transport type (`pjsua_acc_find_for_incoming`). The unbound exception of "No STUN for private servers" is IPv4 only. -- **Which family** (`IPFamilyPolicy.decide`). The server is the first hop: the outbound proxy when one is set, otherwise the registrar (or the domain). An IP literal picks its own family; IPv4 only and IPv6 only with a host name use that family. Auto with a host name: when only one family has a transport for the account's kind (a bind address, a failed IPv6 transport), that family without a lookup; with DNS SRV in effect (pjsua has a resolver) and no explicit port, IPv4, because `getaddrinfo` cannot follow SRV records (pjsua resolves the SRV targets itself, A and AAAA, and skips entries of the other family; choose IPv6 only for a server whose SRV targets have AAAA records only); otherwise the first family that `getaddrinfo(host, AF_UNSPEC)` returns (`IPFamilyResolver.system`, with `pj_getaddrinfo`'s hints: no socket type, no flags, so it is the first address PJSIP itself sends to) and that has a transport. Nothing resolved (offline): IPv4, decided again later. The lookup is synchronous on the engine queue, like PJSIP's own lookup when it sends a request without its DNS resolver (sip_resolve.c) and pjsua's lookup for a TCP/TLS Contact in `pjsua_acc_get_uac_addr`; tests inject a resolver (`setFamilyResolverForTests`). A host name that lacks the chosen family (IPv6 only, no AAAA) fails to register with a DNS error like any unknown host. +- **Which family** (`IPFamilyPolicy.decide`). The server is the first hop: the outbound proxy when one is set, otherwise the registrar (or the domain). An IP literal picks its own family; IPv4 only and IPv6 only with a host name use that family. Auto with a host name: when only one family has a transport for the account's kind (a bind address, a failed IPv6 transport), that family without a lookup; with DNS SRV in effect (pjsua has a resolver) and no explicit port, IPv4 first, because `getaddrinfo` cannot follow SRV records (pjsua resolves the SRV targets itself, A and AAAA, and skips entries of the other family; when nothing of IPv4 answers, the fallback below moves the account to IPv6); otherwise the first family that `getaddrinfo(host, AF_UNSPEC)` returns (`IPFamilyResolver.system`, with `pj_getaddrinfo`'s hints: no socket type, no flags) and that has a transport. That is the order PJSIP itself tries when it resolves a host name without its DNS resolver; it is not what PJSIP does with DNS SRV on (its own A/AAAA queries), and for an account that does not register the INVITEs go to the dialled URI's host, which may differ from the first hop. Nothing resolved (offline): IPv4, decided again later. Lookups run concurrently off the engine queue (`lookupFamilies`: each host once, one wait of at most `familyLookupTimeout`, 2 s, for all of them); a host not resolved in time gives IPv4 for a new account and keeps the family of an existing one. Tests inject a resolver (`setFamilyResolverForTests`). A host name that lacks the chosen family (IPv6 only, no AAAA) fails to register with a DNS error like any unknown host. - **Contradictions.** IPv4 only with an IPv6 literal server (or IPv6 only with an IPv4 literal) can never register: `addAccount` and `updateAccount` throw `.invalidArgument("server 2001:db8::1 is an IPv6 address but the account is set to IPv4 only")`, and the account editor shows "The server's address is an IPv6 address. Choose Auto or IPv6 only." under Connection with Save and Test off (`IPFamilyPolicy.conflict`, also used by the editor). An IPv4-mapped literal (`[::ffff:a.b.c.d]`) is an IPv6 literal. -- **Decided again** (`refreshAccountFamily`) for Auto accounts with a host name (not the SRV case) at the start of every network-change round (before `cpjsua_acc_prepare_ip_change`) and before every REGISTER retry. When the family changed, the account is `pjsua_acc_modify`d onto the other family's transport without a REGISTER (`disable_reg_on_modify`); pjsua destroys its registration session, the round or the retry registers it afresh with a new Contact, and the registrar's requests are trusted again only after it accepted that REGISTER (`setRegistrarSource(nil)`). A call in progress keeps its dialog; the round re-INVITEs it like any call, and it may not survive a change of family (a move from an IPv4 network to an IPv6-only one cannot keep an IPv4 call anyway). A changed IP protocol goes through `updateAccount` (`pjsua_acc_modify`), without a restart. +- **Decided again** (`refreshAccountFamilies`) for Auto accounts with a host name (not the SRV case) at the start of every network-change round (before `cpjsua_acc_prepare_ip_change`), when IPv6 appears or goes away while no account uses IPv6 (without a round), and before every REGISTER retry (not for a sticky account, see below). A lookup that fails or does not finish keeps the account's family (DNS often fails for a moment during a network change). A changed IP protocol in the editor goes through `updateAccount`, without a restart. +- **Fallback when there is no answer** (`tryOtherFamily`). Auto keeps the system's order for the first REGISTER. When a REGISTER gets no response at all (no `rdata` in `on_reg_state2`: a local timeout, a refused or broken connection, PJSIP_ETPNOTSUITABLE when the host has no address of the bound family), the account moves to the other family and registers at once, if the host name has an address of it (or DNS SRV is in effect: the SRV targets are unknown to the engine, the other family is the only chance); a log line says "no answer over IPv6; trying IPv4". Once per series of failures (`familyFallbackTried`, cleared by the next backoff retry and by a network change), so two silent families alternate at the backoff pace, not in a loop. The family that is moved to stays (`familySticky`) until the next network change: backoff retries do not decide again from the resolver. A server that answers (401, 403, 404, a 408 or 503 it sends itself) is no reason to switch. In 26.3.0 an account bound to IPv4 reached a dual-stack server over IPv4 whatever the order (PJSIP skipped the IPv6 entries with ETPNOTSUITABLE); without this fallback, Auto would have kept retrying the family that does not answer (an Asterisk listening on 0.0.0.0 only, an IPv6 firewall). +- **Moving an account** (`moveAccount`). Never while the account has a call in any state: the call's dialog keeps its peer of the old family, and `pjsua_acc_modify` plus a re-INVITE with `UPDATE_CONTACT` would give it the new family's selector, so in-dialog requests would fail with ETPNOTSUITABLE. The move waits (`pendingMove`, a log line "move to IPv6 ... waits for its calls"); the round keeps the account on its family, and the watchdog tick runs the move once the calls have ended (`runDeferredMoves`), with a REGISTER. A move un-REGISTERs the current binding first (Expires 0 over the old family): `pjsua_acc_modify` with `disable_reg_on_modify` destroys the registration session without one (pjsua_acc.c, `unreg_first`), and a lingering old Contact makes Kamailio fork calls to both, and Asterisk with `max_contacts=1`, `remove_existing=no` refuse the new one with 403, which is never retried. The session is destroyed right after (pjsip_regc_destroy2 with force keeps the request going and drops its callback), and the bridge ignores an un-REGISTER result that arrives in between (`setIgnoringUnregister`). Then: `allow_sdp_nat_rewrite` is set on the live config (`cpjsua_acc_set_sdp_nat_rewrite`: pjsua_acc_modify copies every field we set but this one), the MWI subscription is ended (`cpjsua_acc_end_mwi_after_move`; pjsua subscribes again after the REGISTER) and the presence subscriptions of the account's buddies are made anew (`cpjsua_buddy_resubscribe`), because their dialogs keep the transport selector they were created with (pjsua_pres.c); PUBLISH has no selector (`pjsip_publishc`) and needs nothing. The registrar's requests are trusted again only after it accepted a REGISTER (`setRegistrarSource(nil)`). The same applies to `updateAccount` when the family changes. - **Media.** IPv6 accounts set `ipv6_media_use = PJSUA_IPV6_ENABLED_USE_IPV6_ONLY`: `get_media_ip_version` (pjsua_media.c) counts `::1`, link-local and a missing global address as "available" but not "usable", so PREFER_IPV6 would offer IPv4 on loopback and on a Mac without a global IPv6 address. The offer is `c=IN IP6` with IPv6 RTP sockets. An incoming offer is answered in its own family: an `IN IP4` offer to an IPv6 account gets an IPv4 answer and IPv4 RTP (with an IPv6 bind address that socket cannot be bound and the call fails). IPv4 accounts keep pjsua's default (PREFER_IPV4): IPv4 offers, and an `IN IP6` offer is answered with IPv6, as before. `localRTPAddress(of:)` reports the RTP address (diagnostics, tests). - **No STUN over IPv6.** IPv6 accounts have `sip_stun_use` and `media_stun_use` disabled (STUN and TURN over IPv6 are out of scope; pjsua maps IPv4 only) and `allow_sdp_nat_rewrite` on, so after the first REGISTER answer the SDP carries the address the registrar saw (with temporary addresses, the one actually used) instead of `pj_gethostip`'s pick. - **ICE over IPv6** (with a PJSIP patch). pjsua gives an IPv6 call an IPv6 ICE component (`create_ice_media_transport`: `ice_cfg.af = AF_INET6` and a second STUN transport of family IPv6) bound to the string "0" (`IN6_ADDR_ANY`). macOS `getaddrinfo` turns "0" into `::ffff:0.0.0.0`, and binding a V6ONLY socket to that fails ("Failed creating STUN transport #1 for comp 1: Can't assign requested address"): the offer then had IPv4 candidates and `c=IN IP4` only, and an IPv6 answer failed the call (`pjmedia_stream_info_from_sdp`: PJ_EAFNOTSUP). `scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch` (applied by `build-pjsip.sh`, see scripts/README-build.md) makes it "::" in both places (STUN and TURN transports). An IPv6 call with ICE now offers `c=IN IP6` with the IPv6 default candidate, IPv6 and IPv4 host candidates (pjsua adds an IPv4 STUN transport as well), and connects. pjnath leaves out `::1` (`loop_addr` is off) and every link-local address but the default one, so on a Mac without a global IPv6 address the only IPv6 candidate is link-local (`fe80::…`, its zone is not carried in SDP); between two ICE endpoints on this Mac those checks fail and ICE nominates an IPv4 pair (checked by hand on loopback). An IPv6 pair winning needs a global IPv6 address: not verified. - **Incoming.** Requests over UDP6, TCP6 and TLS6 reach the account bound to that transport: an IPv4 and an IPv6 account with the same user and domain each get the calls and messages of their own family. `SignallingSource` compares IPv6 addresses in any spelling (`[2001:DB8:0::1]` is `2001:db8::1`), so the registrar-source trust (answer-after) works over IPv6. -- **Network changes.** `NetworkPath.address6` is the source address of the default IPv6 route (a UDP socket connected to 2001:db8::1, nothing sent; link-local and loopback do not count) and part of the primary route, so a new global IPv6 address, for example a new preferred temporary address, starts a round when NWPathMonitor reports an update (see "Network resilience") while an account is bound to IPv6, and so does IPv6 appearing (an Auto host name may resolve to IPv6 first now). Without IPv6 accounts a new IPv6 address alone starts no round: it changes nothing for them, and a round would end a ringing outgoing call (pjsua's 410). `pjsua_handle_ip_change` with `restart_listener` restarts every listener, the IPv6 ones included (all `tpdata`), and recomputes their published addresses. -- **Tests.** `EngineIPv6Tests.swift` with `IPv6Stub` (UDP and TCP on `[::1]`, optionally UDP on 127.0.0.1 with the same port; answers REGISTER and INVITE with `IN IP6 ::1`, records family, transport, Via, Contact and bodies; sends INVITE with an IPv6 or IPv4 offer and MESSAGE). Values: old JSON decodes as Auto (unknown values too), literals, first hop, contradictions, the decision with a fake resolver (literals, fixed families, resolver order, offline, availability, SRV), `IPFamilyResolver.system` against `getaddrinfo`, mapping by family and its read-back from `pjsua_acc_config` (transport id, `ipv6_media_use`, STUN, bind address), transport ids, IPv6 registrar-source comparison, `NetworkPath.address6`. pjsua: `bindAddressDecidesTransportFamilies`; `ipv6TransportFailureIsNotFatal` (`[::]:P` held by another socket: the engine starts with IPv4 UDP and TCP6 on P and refuses IPv6 UDP accounts; released, both UDP transports use P); `contradictoryIPProtocolIsRefused`; `ipv6AccountRegistersOverUDP6` (Via and Contact `[::1]`, the live config, a MESSAGE out over UDP6); `ipv6AccountRegistersOverTCP6`; `ipv6CallOffersIPv6MediaAndCarriesRTP` (`c=IN IP6 ::1`, RTP address `::1`, a loopback call over `[::1]` with RTP both ways); `incomingOverIPv6ReachesTheIPv6Account` (account by family, answers per offer family, MESSAGE); `autoFollowsSystemResolverForHostNames` ("localhost": Auto follows getaddrinfo's first family, IPv4 only and IPv6 only keep theirs); `familyIsDecidedAgainOnNetworkChangeAndRetry`; `newIPv6AddressStartsRoundOnlyForIPv6Accounts` (IPv6 appearing starts a round, a new address without IPv6 accounts does not, with one it does); `networkChangeRestartsIPv6Listeners`; `iceGathersIPv6CandidatesOverIPv6` (ICE on: `c=IN IP6`, IPv6 host candidates including the default one, RTP to a peer without ICE). In `Engine262Tests.swift`, `privateIPv6ServerAccountIsAdded` now registers over UDP6 with STUN on, and `privateServerAccountDoesNotUseSTUN` sets IPv4 only for its "localhost" account. +- **Network changes.** `NetworkPath.address6` is the source address of the default IPv6 route (a UDP socket connected to 2001:db8::1, nothing sent; link-local and loopback do not count). With an account bound to IPv6, a new address starts a round (see "Network resilience"): a primary one (at once, even while an outgoing call rings) when the address those accounts used is no longer assigned to any interface (`NetworkPath.isAssignedLocally`, getifaddrs; IPv6 lost, or replaced and gone), a non-primary one when it is still assigned, as a deprecated temporary address stays for days after a new one takes over (the round waits for a ringing outgoing call like a gateway change; it restarts the listeners and re-REGISTERs, so Contact moves to the new address before the old one expires). Without IPv6 accounts an IPv6 change starts no round at all, so IPv4 accounts and their calls are not disturbed; when IPv6 appears or goes away, Auto host names are decided again (a family Auto fell back to stays) and moved accounts register; a new temporary address alone changes nothing for them. An empty IPv6 lookup keeps the previous address only while it is still assigned, so losing IPv6 is noticed. `pjsua_handle_ip_change` with `restart_listener` restarts every listener, the IPv6 ones included (all `tpdata`), and recomputes their published addresses. +- **Tests.** `EngineIPv6Tests.swift` with `IPv6Stub` (UDP and TCP on `[::1]`, optionally UDP on 127.0.0.1 with the same port; answers REGISTER and INVITE with `IN IP6 ::1`, records family, transport, Via, Contact and bodies; sends INVITE with an IPv6 or IPv4 offer and MESSAGE). Values: old JSON decodes as Auto (unknown values too), literals, first hop, contradictions, the decision with a fake resolver (literals, fixed families, resolver order, offline, availability, SRV), `IPFamilyResolver.system` against `getaddrinfo`, mapping by family and its read-back from `pjsua_acc_config` (transport id, `ipv6_media_use`, STUN, bind address), transport ids, IPv6 registrar-source comparison, `NetworkPath.address6`. pjsua: `bindAddressDecidesTransportFamilies`; `ipv6TransportFailureIsNotFatal` (`[::]:P` held by another socket: the engine starts with IPv4 UDP and TCP6 on P and refuses IPv6 UDP accounts; released, both UDP transports use P); `contradictoryIPProtocolIsRefused` (`.invalidArgument`); `ipv6AccountRegistersOverUDP6` (Via and Contact `[::1]`, the live config, a MESSAGE out over UDP6); `ipv6AccountRegistersOverTCP6`; `ipv6CallOffersIPv6MediaAndCarriesRTP` (`c=IN IP6 ::1`, RTP address `::1`, a loopback call over `[::1]` with RTP both ways); `incomingOverIPv6ReachesTheIPv6Account` (account by family, answers per offer family, MESSAGE); `autoFollowsSystemResolverForHostNames` ("localhost": Auto follows getaddrinfo's first family, IPv4 only and IPv6 only keep theirs); `familyIsDecidedAgainOnNetworkChange` (un-REGISTER over IPv4 before the IPv6 REGISTER, `allow_sdp_nat_rewrite` read back both ways); `ipProtocolChangeMovesTheAccount`; `autoFallsBackToTheOtherFamilyWithoutAnswer` (IPv6 side silent: IPv4 at once; then sticky: a retry stays on IPv4 before moving back); `autoFallsBackWhenTheConnectionIsRefused` (TCP refused over IPv4: TCP6 at once); `autoKeepsTheFamilyWhenTheServerAnswers` (403: no switch); `familyMoveWaitsForTheAccountsCalls`; `subscriptionsFollowAFamilyMove` (MWI and presence SUBSCRIBE anew over IPv6); `familyLookupsAreDedupedAndBounded` (one lookup per host, a slow resolver delays a round and `addAccount` by the limit only, families kept); `ipv6AddressChangesStartRoundsOnlyWhenTheyMatter` (no round without IPv6 accounts; with one, a rotation with the old address assigned waits for a ringing call, a loss runs at once); `networkChangeRestartsIPv6Listeners`; `iceGathersIPv6CandidatesOverIPv6` (ICE on: `c=IN IP6`, IPv6 host candidates including the default one, RTP to a peer without ICE). In `Engine262Tests.swift`, `privateIPv6ServerAccountIsAdded` now registers over UDP6 with STUN on, and `privateServerAccountDoesNotUseSTUN` sets IPv4 only for its "localhost" account. - **Only a real network can verify:** a real IPv6 PBX over UDP, TCP and TLS (a certificate for an AAAA name), a dual-stack server by host name, an IPv6-only network, router-advertised and temporary addresses (whether NWPathMonitor reports a new temporary address at all, and the Contact after a rotation), moving between IPv4-only, dual-stack and IPv6-only networks with calls in progress, SRV targets with AAAA records only, IPv6 firewalls without NAT, and RTP through them. ## Deny incoming calls diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 1b06740..a93c7a7 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -77,7 +77,7 @@ App: - Messages are off until switched on in Settings › General ([#8](https://github.com/HSMM/MacroSIP/issues/8)): with the switch off there is no Messages tab, no Send Message item, no notification and no sound, and incoming `MESSAGE` requests are dropped with a log line. - The ringtone chosen in Settings › Audio reaches the engine ([#7](https://github.com/HSMM/MacroSIP/issues/7)): Classic, Digital and Soft are three different melodies, a custom AIFF, M4A or MP3 file is converted to WAV once and reused, a file that cannot be read keeps the previous choice and says why, and the preview plays the real choice at the chosen volume. -`26.3.1` (not released yet): IPv6 ([#11](https://github.com/HSMM/MacroSIP/issues/11)). SIP over UDP, TCP and TLS and the audio over IPv6 next to IPv4, for a server given by an IPv6 address or by a host name with AAAA records; an account at `[2001:db8::1]` no longer retries forever. Account editor › Advanced › IP protocol: Auto (an IP address picks its own protocol, a host name follows the order macOS returns; decided again after a network change), IPv4 only, IPv6 only. IPv6 accounts use no STUN; ICE gathers IPv6 candidates with a PJSIP patch (pjsua bound its IPv6 ICE socket to "0", which macOS cannot bind; `scripts/pjsip-patches/`). Tested on loopback only; a real IPv6 PBX and network are not verified. +`26.3.1` (not released yet): IPv6 ([#11](https://github.com/HSMM/MacroSIP/issues/11)). SIP over UDP, TCP and TLS and the audio over IPv6 next to IPv4, for a server given by an IPv6 address or by a host name with AAAA records; an account at `[2001:db8::1]` no longer retries forever. Account editor › Advanced › IP protocol: Auto (an IP address picks its own protocol, a host name follows the order macOS returns and falls back to the other protocol at once when the server does not answer; decided again after a network change, never during a call), IPv4 only, IPv6 only. IPv6 accounts use no STUN; ICE gathers IPv6 candidates with a PJSIP patch (pjsua bound its IPv6 ICE socket to "0", which macOS cannot bind; `scripts/pjsip-patches/`). Tested on loopback only; a real IPv6 PBX and network are not verified. ## Later diff --git a/docs/adr/0014-ipv6-dual-stack.md b/docs/adr/0014-ipv6-dual-stack.md index fc9b4ac..be60db9 100644 --- a/docs/adr/0014-ipv6-dual-stack.md +++ b/docs/adr/0014-ipv6-dual-stack.md @@ -24,12 +24,30 @@ loses the choice between the verifying and the non-verifying TLS listener (miles IPv4 only, IPv6 only (`AccountConfig.ipProtocol`; older files decode as Auto). - **Auto** looks at the first hop (outbound proxy, else registrar): an IP literal picks its own family; a host name follows the first address the system resolver returns (`getaddrinfo` with - `AF_UNSPEC`, the call PJSIP itself makes when it sends), "as the system decides". With DNS SRV in - effect and no explicit port the name cannot be asked that way, so Auto uses IPv4 there; a host - name that does not resolve (offline) also gives IPv4. The decision is made again at every network - change and before every REGISTER retry, and an account whose family changed is moved to the other - transport before it registers. The lookup runs synchronously on the engine queue, as PJSIP's own - lookup does when it sends without its DNS resolver. + `AF_UNSPEC` and pj_getaddrinfo's hints), "as the system decides". That matches the order PJSIP + tries when it resolves without its DNS resolver; with DNS SRV on PJSIP uses its own queries, and an + account that does not register sends its INVITEs to the dialled host, so it is the system's order, + not always PJSIP's. With DNS SRV in effect and no explicit port the name cannot be asked that way, + so Auto starts with IPv4 there; a host name that does not resolve (offline) also gives IPv4. Lookups + run concurrently off the engine queue, each host once, with one bounded wait (2 s); a host not + resolved in time keeps the account's family. +- **Auto falls back.** The system order is only the first attempt: a REGISTER that gets no answer at + all (timeout, refused or broken connection, no address of the bound family) moves the account to + the other family at once when the host has an address of it (or DNS SRV makes the other family the + only chance), and that family then stays until the next network change. A server that answers + (401, 403, its own 503) is not a reason to switch. Without this, a dual-stack name whose server + does not answer over the first family (Asterisk listening on 0.0.0.0 only, an IPv6 firewall) + would retry forever where 26.3.0 registered over IPv4. +- **Decided again** at every network change, when IPv6 comes or goes, and before REGISTER retries + (not after a fallback). An account whose family changed is moved: its old binding is + un-REGISTERed first (a lingering Contact forks calls or makes a `max_contacts=1` server refuse the + new one), its subscriptions are made anew on the new transport, and it registers there. **Never + while the account has a call**: the call's dialog would keep a peer of the old family on a + transport of the new one; the move waits for the calls to end. +- **IPv6 address changes** count only for accounts that use IPv6. A new temporary address while the + old one is still assigned is a non-primary change (it waits for a ringing outgoing call); losing + the address is primary. Without IPv6 accounts IPv6 coming, going or rotating starts no round, so + IPv4 calls are not disturbed. - **Contradictions are refused.** IPv4 only with an IPv6 literal server, or IPv6 only with an IPv4 literal, can never work: the editor says so and keeps Save off, and the engine throws `invalidArgument`. @@ -52,11 +70,14 @@ loses the choice between the verifying and the non-verifying TLS listener (miles ## Consequences An account at `[2001:db8::1]` or at an AAAA-only host name registers and calls over IPv6, with -`c=IN IP6` and IPv6 RTP; existing IPv4 accounts behave as before. A host name with A and AAAA records -may move to IPv6 after the update when macOS orders the IPv6 address first (as `localhost` does); -"IPv4 only" keeps the old behaviour. The engine opens four more listening sockets. With a host name -whose order changes between networks, the account may change family at a network change; a call in -progress on the old family may not survive that. We now carry a PJSIP patch, which every pjproject +`c=IN IP6` and IPv6 RTP. Accounts whose server is an IPv4 address, and accounts set to IPv4 only, +behave as before. An Auto account whose server is a host name with A and AAAA records may move to +IPv6 after the update when macOS orders the IPv6 address first (as `localhost` does); if the server +does not answer over IPv6 it falls back to IPv4 at once, and "IPv4 only" keeps the old behaviour +outright. IPv4 accounts' calls are never touched by IPv6 address changes. The engine opens four more +listening sockets, which fills pjsua's fixed table of eight transports. With a host name whose order +changes between networks, an Auto account may change family at a network change, but only when it +has no call. We now carry a PJSIP patch, which every pjproject upgrade has to re-check. Everything is verified on loopback only (`[::1]` with in-process stubs); behaviour on a real IPv6 PBX and network is left to users and listed as not verified (docs/ENGINE.md "IPv6"). From ddb91dfd9bf20414a03cc3d3391849d7223e4d19 Mon Sep 17 00:00:00 2001 From: HSMM Date: Mon, 9 Nov 2026 15:13:11 +0300 Subject: [PATCH 07/12] PJSIP patch: IPv6 ICE components use the account's IPv6 bind address --- Tests/MacroSIPCoreTests/EngineIPv6Tests.swift | 47 +++++++++ docs/ENGINE.md | 4 +- docs/adr/0014-ipv6-dual-stack.md | 5 +- scripts/README-build.md | 2 +- .../0001-ipv6-ice-bind-any.patch | 97 +++++++++++++++++-- 5 files changed, 144 insertions(+), 11 deletions(-) diff --git a/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift b/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift index af45ba1..4463924 100644 --- a/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift +++ b/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift @@ -1211,6 +1211,53 @@ extension EngineTests { await engine.stop() } + /// ICE honours an IPv6 bind address (scripts/pjsip-patches/0001: the IPv6 ICE component binds to the + /// account's IPv6 bound address, as the IPv4 one does, and keeps a loopback candidate when that is + /// where it is bound). With `bindAddress` "::1" the offer's only IPv6 candidate is ::1, and a call + /// between two ICE legs on loopback negotiates ICE over IPv6 and carries RTP. + @Test func iceOverIPv6HonoursTheBindAddress() async throws { + let stub = try IPv6Stub() + defer { stub.stop() } + let engine = await makeEngine(bindAddress: "::1") + let log = EventLog() + let consumer = log.consume(engine) + defer { consumer.cancel() } + var net = Self.network + net.useICE = true + try await engine.start(network: net) + let account = localIPv6Account("ice") + try await engine.addAccount(account, password: "") + let probe = try await engine.makeCall(to: DialString(uri: "sip:300@[::1]:\(stub.port)", display: "300"), from: account.id) + #expect(await waitUntil(timeout: 8) { stub.requests.contains { $0.method == "INVITE" } }) + let offer = try #require(stub.requests.first { $0.method == "INVITE" }).body + let v6 = offer.components(separatedBy: "\r\n").filter { $0.hasPrefix("a=candidate:") }.compactMap { line -> String? in + let f = line.split(separator: " ") + return f.count > 7 && f[4].contains(":") ? String(f[4]) : nil + } + #expect(!v6.isEmpty && v6.allSatisfy { $0 == "::1" }, "IPv6 candidates \(v6)") + #expect(sdpConnection(offer) == "IN IP6 ::1", "\(offer)") + try? await engine.hangup(probe) + #expect(await waitUntil { await engine.calls().isEmpty }) + + let port6 = await engine.localPort(of: .udp, family: .ipv6) + let mark = log.all.count + let out = try await engine.makeCall(to: DialString(uri: "sip:ice@[::1]:\(port6)", display: "ice"), from: account.id) + func incoming() -> CallInfo? { + log.all.dropFirst(mark).lazy.compactMap { if case let .incomingCall(c) = $0 { return c }; return nil }.first + } + #expect(await waitUntil { incoming() != nil }) + let inc = try #require(incoming()) + try await engine.answer(inc.id) + #expect(await waitUntil(timeout: 8) { + let a = try? await engine.mediaStats(out), b = try? await engine.mediaStats(inc.id) + return (a?.rxPackets ?? 0) > 10 && (b?.rxPackets ?? 0) > 10 + }) + #expect(await engine.localRTPAddress(of: out) == "::1") + try await engine.hangup(out) + #expect(await waitUntil { await engine.calls().isEmpty }) + await engine.stop() + } + /// With ICE on (PJSIP patched: scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch), an IPv6 call /// gathers IPv6 host candidates: the offer is `c=IN IP6` with an IPv6 default candidate, lists IPv6 /// `typ host` candidates (and IPv4 ones from pjsua's second component), and the call to a peer diff --git a/docs/ENGINE.md b/docs/ENGINE.md index 238ce88..7dafe3f 100644 --- a/docs/ENGINE.md +++ b/docs/ENGINE.md @@ -389,10 +389,10 @@ Dual stack since 26.3.1 ([#11](https://github.com/HSMM/MacroSIP/issues/11), ADR - **Moving an account** (`moveAccount`). Never while the account has a call in any state: the call's dialog keeps its peer of the old family, and `pjsua_acc_modify` plus a re-INVITE with `UPDATE_CONTACT` would give it the new family's selector, so in-dialog requests would fail with ETPNOTSUITABLE. The move waits (`pendingMove`, a log line "move to IPv6 ... waits for its calls"); the round keeps the account on its family, and the watchdog tick runs the move once the calls have ended (`runDeferredMoves`), with a REGISTER. A move un-REGISTERs the current binding first (Expires 0 over the old family): `pjsua_acc_modify` with `disable_reg_on_modify` destroys the registration session without one (pjsua_acc.c, `unreg_first`), and a lingering old Contact makes Kamailio fork calls to both, and Asterisk with `max_contacts=1`, `remove_existing=no` refuse the new one with 403, which is never retried. The session is destroyed right after (pjsip_regc_destroy2 with force keeps the request going and drops its callback), and the bridge ignores an un-REGISTER result that arrives in between (`setIgnoringUnregister`). Then: `allow_sdp_nat_rewrite` is set on the live config (`cpjsua_acc_set_sdp_nat_rewrite`: pjsua_acc_modify copies every field we set but this one), the MWI subscription is ended (`cpjsua_acc_end_mwi_after_move`; pjsua subscribes again after the REGISTER) and the presence subscriptions of the account's buddies are made anew (`cpjsua_buddy_resubscribe`), because their dialogs keep the transport selector they were created with (pjsua_pres.c); PUBLISH has no selector (`pjsip_publishc`) and needs nothing. The registrar's requests are trusted again only after it accepted a REGISTER (`setRegistrarSource(nil)`). The same applies to `updateAccount` when the family changes. - **Media.** IPv6 accounts set `ipv6_media_use = PJSUA_IPV6_ENABLED_USE_IPV6_ONLY`: `get_media_ip_version` (pjsua_media.c) counts `::1`, link-local and a missing global address as "available" but not "usable", so PREFER_IPV6 would offer IPv4 on loopback and on a Mac without a global IPv6 address. The offer is `c=IN IP6` with IPv6 RTP sockets. An incoming offer is answered in its own family: an `IN IP4` offer to an IPv6 account gets an IPv4 answer and IPv4 RTP (with an IPv6 bind address that socket cannot be bound and the call fails). IPv4 accounts keep pjsua's default (PREFER_IPV4): IPv4 offers, and an `IN IP6` offer is answered with IPv6, as before. `localRTPAddress(of:)` reports the RTP address (diagnostics, tests). - **No STUN over IPv6.** IPv6 accounts have `sip_stun_use` and `media_stun_use` disabled (STUN and TURN over IPv6 are out of scope; pjsua maps IPv4 only) and `allow_sdp_nat_rewrite` on, so after the first REGISTER answer the SDP carries the address the registrar saw (with temporary addresses, the one actually used) instead of `pj_gethostip`'s pick. -- **ICE over IPv6** (with a PJSIP patch). pjsua gives an IPv6 call an IPv6 ICE component (`create_ice_media_transport`: `ice_cfg.af = AF_INET6` and a second STUN transport of family IPv6) bound to the string "0" (`IN6_ADDR_ANY`). macOS `getaddrinfo` turns "0" into `::ffff:0.0.0.0`, and binding a V6ONLY socket to that fails ("Failed creating STUN transport #1 for comp 1: Can't assign requested address"): the offer then had IPv4 candidates and `c=IN IP4` only, and an IPv6 answer failed the call (`pjmedia_stream_info_from_sdp`: PJ_EAFNOTSUP). `scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch` (applied by `build-pjsip.sh`, see scripts/README-build.md) makes it "::" in both places (STUN and TURN transports). An IPv6 call with ICE now offers `c=IN IP6` with the IPv6 default candidate, IPv6 and IPv4 host candidates (pjsua adds an IPv4 STUN transport as well), and connects. pjnath leaves out `::1` (`loop_addr` is off) and every link-local address but the default one, so on a Mac without a global IPv6 address the only IPv6 candidate is link-local (`fe80::…`, its zone is not carried in SDP); between two ICE endpoints on this Mac those checks fail and ICE nominates an IPv4 pair (checked by hand on loopback). An IPv6 pair winning needs a global IPv6 address: not verified. +- **ICE over IPv6** (with a PJSIP patch). pjsua gives an IPv6 call an IPv6 ICE component (`create_ice_media_transport`: `ice_cfg.af = AF_INET6` and a second STUN transport of family IPv6) bound to the string "0" (`IN6_ADDR_ANY`). macOS `getaddrinfo` turns "0" into `::ffff:0.0.0.0`, and binding a V6ONLY socket to that fails ("Failed creating STUN transport #1 for comp 1: Can't assign requested address"): the offer then had IPv4 candidates and `c=IN IP4` only, and an IPv6 answer failed the call (`pjmedia_stream_info_from_sdp`: PJ_EAFNOTSUP). pjsua also ignored the account's bound address for the IPv6 components (only the IPv4 ones use `rtp_cfg.bound_addr`). `scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch` (applied by `build-pjsip.sh`, see scripts/README-build.md) binds the IPv6 STUN and TURN components like the IPv4 ones: to the account's bound address when it is an IPv6 address, else to "::"; and a STUN component bound to a loopback address keeps its host candidate (`loop_addr`), which pjnath leaves out by default. An IPv6 call with ICE now offers `c=IN IP6` with the IPv6 default candidate, IPv6 and IPv4 host candidates (pjsua adds an IPv4 STUN transport as well), and connects. On all interfaces pjnath leaves out `::1` and every link-local address but the default one, so on a Mac without a global IPv6 address the only IPv6 candidate is link-local (`fe80::…`, its zone is not carried in SDP), and between two ICE endpoints its checks fail and ICE nominates an IPv4 pair. With the bind address `::1` the only candidates are `::1` (the IPv4 component cannot bind an IPv6 address and is left out), and two ICE legs negotiate ICE over IPv6 and carry RTP (tested). An IPv6 pair winning over a real network needs a global IPv6 address: not verified. - **Incoming.** Requests over UDP6, TCP6 and TLS6 reach the account bound to that transport: an IPv4 and an IPv6 account with the same user and domain each get the calls and messages of their own family. `SignallingSource` compares IPv6 addresses in any spelling (`[2001:DB8:0::1]` is `2001:db8::1`), so the registrar-source trust (answer-after) works over IPv6. - **Network changes.** `NetworkPath.address6` is the source address of the default IPv6 route (a UDP socket connected to 2001:db8::1, nothing sent; link-local and loopback do not count). With an account bound to IPv6, a new address starts a round (see "Network resilience"): a primary one (at once, even while an outgoing call rings) when the address those accounts used is no longer assigned to any interface (`NetworkPath.isAssignedLocally`, getifaddrs; IPv6 lost, or replaced and gone), a non-primary one when it is still assigned, as a deprecated temporary address stays for days after a new one takes over (the round waits for a ringing outgoing call like a gateway change; it restarts the listeners and re-REGISTERs, so Contact moves to the new address before the old one expires). Without IPv6 accounts an IPv6 change starts no round at all, so IPv4 accounts and their calls are not disturbed; when IPv6 appears or goes away, Auto host names are decided again (a family Auto fell back to stays) and moved accounts register; a new temporary address alone changes nothing for them. An empty IPv6 lookup keeps the previous address only while it is still assigned, so losing IPv6 is noticed. `pjsua_handle_ip_change` with `restart_listener` restarts every listener, the IPv6 ones included (all `tpdata`), and recomputes their published addresses. -- **Tests.** `EngineIPv6Tests.swift` with `IPv6Stub` (UDP and TCP on `[::1]`, optionally UDP on 127.0.0.1 with the same port; answers REGISTER and INVITE with `IN IP6 ::1`, records family, transport, Via, Contact and bodies; sends INVITE with an IPv6 or IPv4 offer and MESSAGE). Values: old JSON decodes as Auto (unknown values too), literals, first hop, contradictions, the decision with a fake resolver (literals, fixed families, resolver order, offline, availability, SRV), `IPFamilyResolver.system` against `getaddrinfo`, mapping by family and its read-back from `pjsua_acc_config` (transport id, `ipv6_media_use`, STUN, bind address), transport ids, IPv6 registrar-source comparison, `NetworkPath.address6`. pjsua: `bindAddressDecidesTransportFamilies`; `ipv6TransportFailureIsNotFatal` (`[::]:P` held by another socket: the engine starts with IPv4 UDP and TCP6 on P and refuses IPv6 UDP accounts; released, both UDP transports use P); `contradictoryIPProtocolIsRefused` (`.invalidArgument`); `ipv6AccountRegistersOverUDP6` (Via and Contact `[::1]`, the live config, a MESSAGE out over UDP6); `ipv6AccountRegistersOverTCP6`; `ipv6CallOffersIPv6MediaAndCarriesRTP` (`c=IN IP6 ::1`, RTP address `::1`, a loopback call over `[::1]` with RTP both ways); `incomingOverIPv6ReachesTheIPv6Account` (account by family, answers per offer family, MESSAGE); `autoFollowsSystemResolverForHostNames` ("localhost": Auto follows getaddrinfo's first family, IPv4 only and IPv6 only keep theirs); `familyIsDecidedAgainOnNetworkChange` (un-REGISTER over IPv4 before the IPv6 REGISTER, `allow_sdp_nat_rewrite` read back both ways); `ipProtocolChangeMovesTheAccount`; `autoFallsBackToTheOtherFamilyWithoutAnswer` (IPv6 side silent: IPv4 at once; then sticky: a retry stays on IPv4 before moving back); `autoFallsBackWhenTheConnectionIsRefused` (TCP refused over IPv4: TCP6 at once); `autoKeepsTheFamilyWhenTheServerAnswers` (403: no switch); `familyMoveWaitsForTheAccountsCalls`; `subscriptionsFollowAFamilyMove` (MWI and presence SUBSCRIBE anew over IPv6); `familyLookupsAreDedupedAndBounded` (one lookup per host, a slow resolver delays a round and `addAccount` by the limit only, families kept); `ipv6AddressChangesStartRoundsOnlyWhenTheyMatter` (no round without IPv6 accounts; with one, a rotation with the old address assigned waits for a ringing call, a loss runs at once); `networkChangeRestartsIPv6Listeners`; `iceGathersIPv6CandidatesOverIPv6` (ICE on: `c=IN IP6`, IPv6 host candidates including the default one, RTP to a peer without ICE). In `Engine262Tests.swift`, `privateIPv6ServerAccountIsAdded` now registers over UDP6 with STUN on, and `privateServerAccountDoesNotUseSTUN` sets IPv4 only for its "localhost" account. +- **Tests.** `EngineIPv6Tests.swift` with `IPv6Stub` (UDP and TCP on `[::1]`, optionally UDP on 127.0.0.1 with the same port; answers REGISTER and INVITE with `IN IP6 ::1`, records family, transport, Via, Contact and bodies; sends INVITE with an IPv6 or IPv4 offer and MESSAGE). Values: old JSON decodes as Auto (unknown values too), literals, first hop, contradictions, the decision with a fake resolver (literals, fixed families, resolver order, offline, availability, SRV), `IPFamilyResolver.system` against `getaddrinfo`, mapping by family and its read-back from `pjsua_acc_config` (transport id, `ipv6_media_use`, STUN, bind address), transport ids, IPv6 registrar-source comparison, `NetworkPath.address6`. pjsua: `bindAddressDecidesTransportFamilies`; `ipv6TransportFailureIsNotFatal` (`[::]:P` held by another socket: the engine starts with IPv4 UDP and TCP6 on P and refuses IPv6 UDP accounts; released, both UDP transports use P); `contradictoryIPProtocolIsRefused` (`.invalidArgument`); `ipv6AccountRegistersOverUDP6` (Via and Contact `[::1]`, the live config, a MESSAGE out over UDP6); `ipv6AccountRegistersOverTCP6`; `ipv6CallOffersIPv6MediaAndCarriesRTP` (`c=IN IP6 ::1`, RTP address `::1`, a loopback call over `[::1]` with RTP both ways); `incomingOverIPv6ReachesTheIPv6Account` (account by family, answers per offer family, MESSAGE); `autoFollowsSystemResolverForHostNames` ("localhost": Auto follows getaddrinfo's first family, IPv4 only and IPv6 only keep theirs); `familyIsDecidedAgainOnNetworkChange` (un-REGISTER over IPv4 before the IPv6 REGISTER, `allow_sdp_nat_rewrite` read back both ways); `ipProtocolChangeMovesTheAccount`; `autoFallsBackToTheOtherFamilyWithoutAnswer` (IPv6 side silent: IPv4 at once; then sticky: a retry stays on IPv4 before moving back); `autoFallsBackWhenTheConnectionIsRefused` (TCP refused over IPv4: TCP6 at once); `autoKeepsTheFamilyWhenTheServerAnswers` (403: no switch); `familyMoveWaitsForTheAccountsCalls`; `subscriptionsFollowAFamilyMove` (MWI and presence SUBSCRIBE anew over IPv6); `familyLookupsAreDedupedAndBounded` (one lookup per host, a slow resolver delays a round and `addAccount` by the limit only, families kept); `ipv6AddressChangesStartRoundsOnlyWhenTheyMatter` (no round without IPv6 accounts; with one, a rotation with the old address assigned waits for a ringing call, a loss runs at once); `networkChangeRestartsIPv6Listeners`; `iceGathersIPv6CandidatesOverIPv6` (ICE on: `c=IN IP6`, IPv6 host candidates including the default one, RTP to a peer without ICE); `iceOverIPv6HonoursTheBindAddress` (bind address `::1`: the only IPv6 candidate is `::1`, and a call between two ICE legs carries RTP over IPv6). In `Engine262Tests.swift`, `privateIPv6ServerAccountIsAdded` now registers over UDP6 with STUN on, and `privateServerAccountDoesNotUseSTUN` sets IPv4 only for its "localhost" account. - **Only a real network can verify:** a real IPv6 PBX over UDP, TCP and TLS (a certificate for an AAAA name), a dual-stack server by host name, an IPv6-only network, router-advertised and temporary addresses (whether NWPathMonitor reports a new temporary address at all, and the Contact after a rotation), moving between IPv4-only, dual-stack and IPv6-only networks with calls in progress, SRV targets with AAAA records only, IPv6 firewalls without NAT, and RTP through them. ## Deny incoming calls diff --git a/docs/adr/0014-ipv6-dual-stack.md b/docs/adr/0014-ipv6-dual-stack.md index be60db9..fc11d56 100644 --- a/docs/adr/0014-ipv6-dual-stack.md +++ b/docs/adr/0014-ipv6-dual-stack.md @@ -59,8 +59,9 @@ loses the choice between the verifying and the non-verifying TLS listener (miles - **ICE over IPv6, with our first PJSIP patch.** PJSIP 2.17 binds the IPv6 ICE component to the string "0", which macOS `getaddrinfo` turns into `::ffff:0.0.0.0`; that socket cannot be bound, the offer carried IPv4 candidates only and a call failed on an IPv6 answer. Instead of turning ICE off - for IPv6 accounts, `scripts/build-pjsip.sh` applies `scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch` - ("::" instead of "0" in pjsua_media.c). This amends ADR 0002/0012: pjproject is no longer built + for IPv6 accounts, `scripts/build-pjsip.sh` applies `scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch`: + pjsua_media.c binds the IPv6 components like the IPv4 ones (the account's IPv6 bound address, + else "::") and keeps the candidate of a component bound to loopback on purpose. This amends ADR 0002/0012: pjproject is no longer built from the pristine tarball alone. Patches live in `scripts/pjsip-patches/`, one problem per file with a header saying why, applied in name order with `patch -p1 --forward`; a patch that does not apply stops the build; their hashes are part of the build stamp and of CI's cache key; every diff --git a/scripts/README-build.md b/scripts/README-build.md index 532b58d..f6f3e57 100644 --- a/scripts/README-build.md +++ b/scripts/README-build.md @@ -49,7 +49,7 @@ problem, refresh it otherwise. | Patch | Why | |---|---| -| `0001-ipv6-ice-bind-any.patch` | pjsua binds the IPv6 ICE STUN/TURN components to the string "0", which macOS `getaddrinfo` turns into `::ffff:0.0.0.0`; that cannot be bound to an IPv6-only socket, so IPv6 calls with ICE got IPv4 candidates only. The patch uses "::" (ADR 0014). | +| `0001-ipv6-ice-bind-any.patch` | pjsua binds the IPv6 ICE STUN/TURN components to the string "0" and ignores the account's bound address; macOS `getaddrinfo` turns "0" into `::ffff:0.0.0.0`, which cannot be bound to an IPv6-only socket, so IPv6 calls with ICE got IPv4 candidates only. The patch binds them like the IPv4 ones (the account's IPv6 bound address, else "::") and keeps the host candidate of a component bound to loopback on purpose (`loop_addr`), which pjnath leaves out otherwise (ADR 0014). | To check a build: `lipo -thin arm64 third_party/pjsip/lib/libpjsua.a -output /tmp/x.a`, extract `pjsua_media.o` with `ar -x`, and `otool -v -s __TEXT __cstring pjsua_media.o` lists `::`. diff --git a/scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch b/scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch index cf1e078..f213079 100644 --- a/scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch +++ b/scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch @@ -1,33 +1,118 @@ -Bind the IPv6 ICE components to "::" instead of "0". +Bind the IPv6 ICE components like the IPv4 ones. pjsua builds the bound address of an IPv6 ICE STUN or TURN transport from the -string "0" (IN6_ADDR_ANY). pj_sockaddr_init(AF_INET6, "0") is not an IPv6 +string "0" (IN6_ADDR_ANY) and ignores the account's bound address, which only +the IPv4 components use. pj_sockaddr_init(AF_INET6, "0") is not an IPv6 literal, so pjlib falls back to getaddrinfo, which on macOS returns the IPv4-mapped ::ffff:0.0.0.0. Binding that to an IPv6 socket with IPV6_V6ONLY set (as pjlib does) fails with EADDRNOTAVAIL ("Failed creating STUN transport #1 ... Can't assign requested address"): an IPv6 call with ICE then has IPv4 -candidates only and fails on an IPv6 answer. "::" is the IPv6 any address and -parses with inet_pton on every platform. +candidates only and fails on an IPv6 answer. + +- The IPv6 components bind to the account's bound address when that is an IPv6 + address, otherwise to "::" (the IPv6 any address, parsed by inet_pton). +- A STUN component bound to a loopback address on purpose keeps its host + candidate (loop_addr); pjnath leaves loopback candidates out by default, so a + loopback bound address would leave the component without any candidate. MacroSIP: applied by scripts/build-pjsip.sh (ADR 0014). --- a/pjsip/src/pjsua-lib/pjsua_media.c +++ b/pjsip/src/pjsua-lib/pjsua_media.c -@@ -1230,7 +1230,7 @@ +@@ -33,16 +33,16 @@ + + static void stop_media_stream(pjsua_call *call, unsigned med_idx); + +-char *pjsua_get_basename(const char* path, unsigned len) +-{ +- char* p = ((char*)path) + len; +- +- if (len == 0) +- return p; +- +- for (--p; p != path && *p != '/' && *p != '\\'; ) --p; +- +- return (p == path) ? p : p + 1; ++char *pjsua_get_basename(const char* path, unsigned len) ++{ ++ char* p = ((char*)path) + len; ++ ++ if (len == 0) ++ return p; ++ ++ for (--p; p != path && *p != '/' && *p != '\\'; ) --p; ++ ++ return (p == path) ? p : p + 1; + } + + static void pjsua_media_config_dup(pj_pool_t *pool, +@@ -1230,7 +1230,11 @@ } for (i = 0; i < ice_cfg.stun_tp_cnt; ++i) { - pj_str_t IN6_ADDR_ANY = {"0", 1}; + pj_str_t IN6_ADDR_ANY = {"::", 2}; ++ /* An IPv6 component binds like the IPv4 one: to the account's ++ * bound address when that is an IPv6 address, else to any. */ ++ const pj_str_t *bound6 = pj_strchr(&cfg->bound_addr, ':') ? ++ &cfg->bound_addr : &IN6_ADDR_ANY; /* Configure STUN server */ if (pjsua_media_acc_is_using_stun(call_med->call->acc_id) && -@@ -1317,7 +1317,7 @@ +@@ -1252,8 +1256,16 @@ + pj_sockaddr_init(ice_cfg.stun_tp[i].af, + &ice_cfg.stun_tp[i].cfg.bound_addr, + (ice_cfg.stun_tp[i].af == pj_AF_INET()? +- &cfg->bound_addr: &IN6_ADDR_ANY), ++ &cfg->bound_addr: bound6), + (pj_uint16_t)cfg->port); ++ /* Bound to a loopback address on purpose: keep its host ++ * candidate, which pjnath otherwise leaves out. */ ++ if (pj_sockaddr_has_addr(&ice_cfg.stun_tp[i].cfg.bound_addr) && ++ pj_check_addr_type(&ice_cfg.stun_tp[i].cfg.bound_addr, ++ PJ_ADDR_TYPE_LOOPBACK)) ++ { ++ ice_cfg.stun_tp[i].loop_addr = PJ_TRUE; ++ } + ice_cfg.stun_tp[i].cfg.port_range = (pj_uint16_t)cfg->port_range; + if (cfg->port != 0 && ice_cfg.stun_tp[i].cfg.port_range == 0) { + ice_cfg.stun_tp[i].cfg.port_range = +@@ -1317,7 +1329,9 @@ ice_cfg.turn_tp[0].port = 3479; for (i = 0; i < ice_cfg.turn_tp_cnt; i++) { - pj_str_t IN6_ADDR_ANY = {"0", 1}; + pj_str_t IN6_ADDR_ANY = {"::", 2}; ++ const pj_str_t *bound6 = pj_strchr(&cfg->bound_addr, ':') ? ++ &cfg->bound_addr : &IN6_ADDR_ANY; /* Configure TURN connection settings and credential */ ice_cfg.turn_tp[i].server = ice_cfg.turn_tp[0].server; +@@ -1336,7 +1350,7 @@ + pj_sockaddr_init(ice_cfg.turn_tp[i].af, + &ice_cfg.turn_tp[i].cfg.bound_addr, + (ice_cfg.turn_tp[i].af == pj_AF_INET()? +- &cfg->bound_addr: &IN6_ADDR_ANY), ++ &cfg->bound_addr: bound6), + (pj_uint16_t)cfg->port); + ice_cfg.turn_tp[i].cfg.port_range = (pj_uint16_t)cfg->port_range; + if (cfg->port != 0 && ice_cfg.turn_tp[i].cfg.port_range == 0) +@@ -1977,12 +1991,12 @@ + goto on_return; + } + +- /* Check if media is deinitializing */ +- if (call_med->call->async_call.med_ch_deinit || !call_med->tp) { +- status = PJ_ECANCELLED; +- goto on_return; +- } +- ++ /* Check if media is deinitializing */ ++ if (call_med->call->async_call.med_ch_deinit || !call_med->tp) { ++ status = PJ_ECANCELLED; ++ goto on_return; ++ } ++ + pjmedia_transport_simulate_lost(call_med->tp, PJMEDIA_DIR_ENCODING, + pjsua_var.media_cfg.tx_drop_pct); + From 0d2b9a519be51db4ddbdfd5d1325119b7c864190 Mon Sep 17 00:00:00 2001 From: HSMM Date: Mon, 9 Nov 2026 15:38:47 +0300 Subject: [PATCH 08/12] IPv6: one reconciler moves accounts between families --- Sources/CPJSUA/include/CPJSUA.h | 3 + Sources/CPJSUA/shim.c | 16 + .../MacroSIPCore/Engine/Engine+Accounts.swift | 291 +++------------ .../MacroSIPCore/Engine/Engine+Families.swift | 336 +++++++++++++++++ .../MacroSIPCore/Engine/Engine+Network.swift | 76 +--- Sources/MacroSIPCore/Engine/Engine.swift | 30 +- .../MacroSIPCore/Engine/EngineBridge.swift | 41 ++- Sources/MacroSIPCore/Engine/IPFamily.swift | 56 +++ .../Engine/NetworkPathMonitor.swift | 10 +- Tests/MacroSIPCoreTests/Engine262Tests.swift | 8 +- Tests/MacroSIPCoreTests/EngineIPv6Tests.swift | 341 +++++++++++++----- docs/ENGINE.md | 18 +- docs/ROADMAP.md | 2 +- docs/adr/0014-ipv6-dual-stack.md | 27 +- 14 files changed, 818 insertions(+), 437 deletions(-) create mode 100644 Sources/MacroSIPCore/Engine/Engine+Families.swift diff --git a/Sources/CPJSUA/include/CPJSUA.h b/Sources/CPJSUA/include/CPJSUA.h index 9a83f9e..e1c5c71 100644 --- a/Sources/CPJSUA/include/CPJSUA.h +++ b/Sources/CPJSUA/include/CPJSUA.h @@ -475,6 +475,9 @@ void cpjsua_acc_prepare_ip_change(pjsua_acc_id acc_id, int register_it); * not a configurable macro): the engine creates at most this many transports. */ unsigned cpjsua_transport_slots(void); +/** 1 while the account's registration session has a REGISTER (or un-REGISTER) transaction in flight. */ +int cpjsua_acc_reg_busy(pjsua_acc_id acc_id); + /** pjsua_acc_modify never copies allow_sdp_nat_rewrite (only pjsua_acc_add does): set it on the * live account config. */ void cpjsua_acc_set_sdp_nat_rewrite(pjsua_acc_id acc_id, int on); diff --git a/Sources/CPJSUA/shim.c b/Sources/CPJSUA/shim.c index 163ad64..fe5d74a 100644 --- a/Sources/CPJSUA/shim.c +++ b/Sources/CPJSUA/shim.c @@ -1640,6 +1640,22 @@ unsigned cpjsua_transport_slots(void) return (unsigned)PJ_ARRAY_SIZE(pjsua_var.tpdata); } +int cpjsua_acc_reg_busy(pjsua_acc_id acc_id) +{ + pjsip_regc_info info; + int busy = 0; + if (acc_id < 0 || acc_id >= (int)PJ_ARRAY_SIZE(pjsua_var.acc)) + return 0; + PJSUA_LOCK(); + if (pjsua_var.acc[acc_id].valid && pjsua_var.acc[acc_id].regc && + pjsip_regc_get_info(pjsua_var.acc[acc_id].regc, &info) == PJ_SUCCESS) + { + busy = info.is_busy ? 1 : 0; + } + PJSUA_UNLOCK(); + return busy; +} + void cpjsua_acc_set_sdp_nat_rewrite(pjsua_acc_id acc_id, int on) { if (acc_id < 0 || acc_id >= (int)PJ_ARRAY_SIZE(pjsua_var.acc)) diff --git a/Sources/MacroSIPCore/Engine/Engine+Accounts.swift b/Sources/MacroSIPCore/Engine/Engine+Accounts.swift index 493e2f6..b05c105 100644 --- a/Sources/MacroSIPCore/Engine/Engine+Accounts.swift +++ b/Sources/MacroSIPCore/Engine/Engine+Accounts.swift @@ -1,6 +1,5 @@ internal import CPJSUA import Foundation -import os extension Engine { /// Adds the account to pjsua and registers it when `cfg.registers`. Atomic: if the @@ -10,7 +9,7 @@ extension Engine { guard accounts[cfg.id] == nil else { throw EngineError.invalidArgument("account \(cfg.id.raw) is already added") } - let family = try decideFamily(cfg) + let (family, lookupStarted) = try decideFamily(cfg) let settings = try accountSettings(cfg, password: password, family: family) var index = PJ.invalidID try AccountMapping.withPJConfig(settings) { p in @@ -31,6 +30,13 @@ extension Engine { do { try applyPresence(.available, index: index) } catch { PJ.warn(error, "initial presence") } } guard cfg.registers else { return } + if lookupStarted { + // The family depends on a lookup that is running: the first REGISTER waits for it + // (`reconcileFamilies`, at most `lookupWait`), so it goes out over the right family. + accounts[cfg.id]?.registerDeadline = .now + Engine.lookupWait + bridge.setRegistration(cfg.id, .registering) + return + } do { try applyRegistration(cfg.id, true) } catch { @@ -43,21 +49,39 @@ extension Engine { /// `password == nil` keeps the current one. The new configuration is always applied; /// a failing un-REGISTER of the old one is only logged. Re-registers when `cfg.registers`. + /// IP family (docs/ENGINE.md "IPv6"): another server is configured over its own family at once (no + /// binding of this account there to remove); a changed IP protocol for the same server becomes a + /// desired family that `reconcileFamilies` moves the account to; anything else keeps the family, + /// including one Auto fell back to. public func updateAccount(_ cfg: AccountConfig, password: String?) throws { try requireStarted() guard var entry = accounts[cfg.id] else { throw EngineError.unknownAccount(cfg.id) } let pw = password ?? entry.password - var family = try decideFamily(cfg) - // Never move an account with a call to the other family: the call's dialog would keep its - // peer and lose its transport. The move waits for the calls (`runDeferredMoves`). - var deferred: (family: IPFamily, reason: String)? - if family != entry.family, accountHasCalls(entry.index) { - deferred = (family, "settings changed") - family = entry.family - emit(.log(level: 3, "engine: account \(cfg.uri): move to \(deferred!.family) waits for its calls")) + let old = entry.config + let serverChanged = old.registrarURI != cfg.registrarURI || old.outboundProxy != cfg.outboundProxy + || old.transport != cfg.transport + let protocolChanged = old.ipProtocol != cfg.ipProtocol + var family = entry.family + var lookupStarted = false + entry.generation &+= 1 + if serverChanged || protocolChanged { + entry.familySticky = false + entry.familyFallbackTried = false + entry.fallbackWaitsForLookup = false + let decided = try decideFamily(cfg, provisional: serverChanged ? nil : entry.family) + lookupStarted = decided.lookupStarted + if serverChanged && !accountHasCalls(entry.index) { + family = decided.family + entry.desired = nil + } else { + entry.desired = decided.family == entry.family ? nil + : FamilyDesire(family: decided.family, reason: "settings changed", generation: entry.generation) + } + } else { + entry.desired?.generation = entry.generation } let settings = try accountSettings(cfg, password: pw, family: family) - let moving = family != entry.family + let familyChanged = family != entry.family // New settings start a new series of attempts. cancelRegistrationRetry(cfg.id) bridge.resetRetryAttempts(cfg.id) @@ -71,47 +95,46 @@ extension Engine { PJ.warn(error, "unregister before modifying account") } } - // A move to the other family destroys the registration session without an un-REGISTER - // (disable_reg_on_modify); remove the old binding first, so it does not stay at the registrar. - let unregisterFirst = moving && cfg.registers && hasBinding(cfg.id) - if unregisterFirst { unregisterBeforeMove(entry) } - defer { if unregisterFirst { bridge.setIgnoringUnregister(entry.index, false) } } try AccountMapping.withPJConfig(settings) { p in // We decide about (re-)registration below, not pjsua_acc_modify. p.pointee.disable_reg_on_modify = 1 try PJ.check(pjsua_acc_modify(entry.index, p), "pjsua_acc_modify") } - cpjsua_acc_set_sdp_nat_rewrite(entry.index, settings.sdpNATRewrite ? 1 : 0) - if moving { cpjsua_acc_end_mwi_after_move(entry.index) } + cpjsua_acc_set_sdp_nat_rewrite(entry.index, settings.sdpNATRewrite ? 1 : 0) // not copied by modify + if familyChanged { cpjsua_acc_end_mwi_after_move(entry.index) } if cfg.isDefaultOutgoing { PJ.warn(pjsua_acc_set_default(entry.index), "set default account") } - let serverChanged = entry.config.registrarURI != cfg.registrarURI - || entry.config.outboundProxy != cfg.outboundProxy || entry.config.transport != cfg.transport - || entry.family != family - if entry.family != family || entry.config.ipProtocol != cfg.ipProtocol { logFamily(cfg, family) } + if familyChanged || protocolChanged { logFamily(cfg, entry.desired?.family ?? family) } entry.config = cfg entry.password = pw entry.family = family - entry.pendingMove = deferred - entry.familySticky = false - entry.familyFallbackTried = false + entry.moveUnregisterSent = nil + entry.registerDeadline = nil accounts[cfg.id] = entry bridge.setAccount(entry.index, cfg.id, registrationInterval: cfg.registrationInterval, - proxy: SignallingSource.proxy(cfg.outboundProxy, transport: cfg.transport)) + proxy: SignallingSource.proxy(cfg.outboundProxy, transport: cfg.transport), + generation: entry.generation) // Another server: trust its INVITEs only after it accepted a REGISTER. - if serverChanged { bridge.setRegistrarSource(entry.index, nil) } + if serverChanged || familyChanged { bridge.setRegistrarSource(entry.index, nil) } warnIfUnverifiedTLS(cfg) // Switching publishing off makes pjsua un-PUBLISH and go offline; switching it back // on must not publish "offline": re-apply the last status. if cfg.publishPresence { do { try applyPresence(entry.presence, index: entry.index) } catch { PJ.warn(error, "presence") } } - // A SUBSCRIBE that failed with the old settings would wait 300 s for pjsua's retry; after a - // move every subscription is made anew on the new transport. - if moving { resubscribePresence(accountIndex: entry.index) } + // A SUBSCRIBE that failed with the old settings would wait 300 s for pjsua's retry; on another + // transport every subscription is made anew. + if familyChanged { resubscribePresence(accountIndex: entry.index) } refreshPresenceSubscriptions(accountIndex: entry.index) - if cfg.registers { + guard cfg.registers else { return } + if lookupStarted { + accounts[cfg.id]?.registerDeadline = .now + Engine.lookupWait + bridge.setRegistration(cfg.id, .registering) + } else if entry.desired != nil && !accountHasCalls(entry.index) { + // The reconciler un-REGISTERs the binding on this family and registers on the other one. + reconcileFamilies() + } else { try applyRegistration(cfg.id, true) } } @@ -162,212 +185,6 @@ extension Engine { return settings } - /// DNS SRV is in effect: pjsua has a resolver and looks up SRV records of hosts without a port. - var srvInEffect: Bool { !dnsServers.isEmpty } - - /// The account's IP family (`IPFamilyPolicy`). Throws `.invalidArgument` when IPv4 only or IPv6 only - /// contradicts the server's IP literal: such an account could never register. A host name that is - /// not resolved within `familyLookupTimeout` counts as unresolved (IPv4). - func decideFamily(_ cfg: AccountConfig) throws -> IPFamily { - if let literal = IPFamilyPolicy.conflict(in: cfg) { - let host = IPFamilyPolicy.firstHop(of: cfg).host - throw EngineError.invalidArgument("server \(host) is an \(literal) address but the account is set to " - + "\(literal == .ipv6 ? "IPv4" : "IPv6") only") - } - return IPFamilyPolicy.decide(cfg, available: transports.families(for: cfg), srv: srvInEffect) { host in - lookupFamilies([host])[host] ?? [] - } - } - - /// The families of each host name, looked up concurrently off the engine queue (each host once) and - /// waited for at most `familyLookupTimeout` in all. A host missing from the result did not answer in - /// time; its lookup goes on and is discarded. Up to N lookups thus block the engine for one limit at - /// most, not N in a row. - func lookupFamilies(_ hosts: [String]) -> [String: [IPFamily]] { - let unique = Array(Set(hosts.filter { !$0.isEmpty })) - guard !unique.isEmpty else { return [:] } - let results = OSAllocatedUnfairLock(initialState: [String: [IPFamily]]()) - let group = DispatchGroup() - let resolve = resolveFamilies - for host in unique { - group.enter() - DispatchQueue.global(qos: .userInitiated).async { - let families = resolve(host) - results.withLock { $0[host] = families } - group.leave() - } - } - let limit = familyLookupTimeout.components - let seconds = Double(limit.seconds) + Double(limit.attoseconds) / 1e18 - if group.wait(timeout: .now() + seconds) == .timedOut { - emit(.log(level: 3, "engine: address lookup of \(unique.joined(separator: ", ")) not finished within \(seconds) s")) - } - return results.withLock { $0 } - } - - private func logFamily(_ cfg: AccountConfig, _ family: IPFamily) { - let how = cfg.ipProtocol == .auto ? "auto" : "\(cfg.ipProtocol.rawValue) only" - emit(.log(level: 4, "engine: account \(cfg.uri): \(family) (\(how), server \(IPFamilyPolicy.firstHop(of: cfg).host))")) - } - - /// The registrar holds a binding of the account (last REGISTER answered 2xx). - func hasBinding(_ id: AccountID) -> Bool { - if case .registered = bridge.registration(of: id) { return true } - return false - } - - /// The account has a call in any state (ringing, connecting, connected, held). - func accountHasCalls(_ index: pjsua_acc_id) -> Bool { - CallSnapshot.allSlots().contains { slot in - guard let snap = CallSnapshot.read(slot) else { return false } - return snap.accIndex == index && snap.state != .disconnected - } - } - - /// Sends the un-REGISTER of the account's current binding (Expires 0 on the old family) and marks - /// its result as no state of the account (the session is destroyed by the move right after, which - /// keeps the request going but drops its callback). - func unregisterBeforeMove(_ entry: AccountEntry) { - bridge.setIgnoringUnregister(entry.index, true) - PJ.warn(pjsua_acc_set_registration(entry.index, 0), "account \(entry.config.uri): un-REGISTER before the move") - } - - /// Moves the account to `family`'s transport: the old binding is un-REGISTERed, the account is - /// `pjsua_acc_modify`d without a REGISTER (`disable_reg_on_modify`), `allow_sdp_nat_rewrite` is set - /// (pjsua_acc_modify does not copy it), the MWI and presence subscriptions are made anew (their - /// dialogs keep the old transport), and the registrar's INVITEs are trusted again only after it - /// accepted a REGISTER. `register`: send that REGISTER now (outside a network-change round, which - /// registers the account itself). An account with a call is not moved: the move waits for the - /// calls to end (`runDeferredMoves`). Returns true when the account moved. - @discardableResult - func moveAccount(_ id: AccountID, to family: IPFamily, reason: String, register: Bool) -> Bool { - guard isStarted, PJ.registerThread(), var entry = accounts[id] else { return false } - guard entry.family != family else { - entry.pendingMove = nil - accounts[id] = entry - return false - } - if accountHasCalls(entry.index) { - if entry.pendingMove?.family != family { - emit(.log(level: 3, "engine: account \(entry.config.uri): move to \(family) (\(reason)) waits for its calls")) - } - entry.pendingMove = (family, reason) - accounts[id] = entry - return false - } - let settings: PJAccountSettings - do { - settings = try accountSettings(entry.config, password: entry.password, family: family) - } catch { - PJ.warn(error, "account \(entry.config.uri): move to \(family)") - return false - } - let unregisterFirst = hasBinding(id) - if unregisterFirst { unregisterBeforeMove(entry) } - defer { if unregisterFirst { bridge.setIgnoringUnregister(entry.index, false) } } - do { - try AccountMapping.withPJConfig(settings) { p in - p.pointee.disable_reg_on_modify = 1 - try PJ.check(pjsua_acc_modify(entry.index, p), "pjsua_acc_modify") - } - } catch { - PJ.warn(error, "account \(entry.config.uri): move to \(family)") - return false - } - cpjsua_acc_set_sdp_nat_rewrite(entry.index, settings.sdpNATRewrite ? 1 : 0) - cpjsua_acc_end_mwi_after_move(entry.index) - emit(.log(level: 3, "engine: account \(entry.config.uri): server now reached over \(family) " - + "(was \(entry.family), \(reason))")) - entry.family = family - entry.pendingMove = nil - accounts[id] = entry - bridge.setRegistrarSource(entry.index, nil) - resubscribePresence(accountIndex: entry.index) - if register, entry.wantsRegistration, !sleeping, networkStatus == .online, ipChange == nil { - do { try applyRegistration(id, true) } catch { PJ.warn(error, "account \(entry.config.uri): REGISTER after the move") } - } - return true - } - - /// Decides the family of Auto accounts with a host name again (network change, REGISTER retry, - /// IPv6 appearing) and moves those whose family changed. Each host is looked up once, all of them - /// together within `familyLookupTimeout`; an account whose lookup failed or did not finish keeps - /// its family (during a network change DNS often fails for a moment). Sticky accounts (Auto moved - /// them after a REGISTER got no answer) are left alone; the caller clears that at a network change. - func refreshAccountFamilies(_ ids: [AccountID], reason: String, register: Bool) { - guard isStarted, PJ.registerThread() else { return } - let srv = srvInEffect - let candidates = ids.compactMap { id -> (AccountID, AccountEntry, String)? in - guard let entry = accounts[id], !entry.familySticky, - IPFamilyPolicy.followsResolver(entry.config, srv: srv) else { return nil } - return (id, entry, IPFamilyPolicy.firstHop(of: entry.config).host) - } - guard !candidates.isEmpty else { return } - let resolved = lookupFamilies(candidates.map(\.2)) - for (id, entry, host) in candidates { - guard let families = resolved[host], !families.isEmpty else { continue } - let family = IPFamilyPolicy.decide(entry.config, available: transports.families(for: entry.config), - srv: srv) { _ in families } - moveAccount(id, to: family, reason: reason, register: register) - } - } - - /// Moves that waited for an account's calls, once its calls have ended (watchdog tick). - func runDeferredMoves() { - guard isStarted, ipChange == nil else { return } - for (id, entry) in accounts { - guard let move = entry.pendingMove, !accountHasCalls(entry.index) else { continue } - accounts[id]?.pendingMove = nil - moveAccount(id, to: move.family, reason: "\(move.reason), after the calls ended", register: true) - } - } - - /// Presence subscriptions of buddies watched through this account, anew (after a move). - func resubscribePresence(accountIndex index: pjsua_acc_id) { - guard isStarted, PJ.registerThread() else { return } - for (key, buddy) in buddies.sorted(by: { $0.key < $1.key }) { - let account = key.withCString { p -> pjsua_acc_id in - var uri = cpjsua_str(p) - return pjsua_acc_find_for_outgoing(&uri) - } - guard account == index else { continue } - PJ.warn(cpjsua_buddy_resubscribe(buddy.id), "resubscribe presence of \(key)") - } - } - - // MARK: test hooks - - func transportIDsForTests() -> TransportIDs { transports } - - func accountFamilyForTests(_ id: AccountID) -> IPFamily? { accounts[id]?.family } - - func setFamilyResolverForTests(_ resolve: @escaping @Sendable (String) -> [IPFamily]) { - resolveFamilies = resolve - } - - func setFamilyLookupTimeoutForTests(_ limit: Duration) { - familyLookupTimeout = limit - } - - func setIPv6AddressAssignedForTests(_ assigned: @escaping @Sendable (String) -> Bool) { - ipv6AddressAssigned = assigned - } - - /// The account's pjsua_acc_config as pjsua holds it now (pjsua_acc_get_config). - func liveAccountSettingsForTests(_ id: AccountID) -> PJAccountSettings? { - guard isStarted, PJ.registerThread(), let entry = accounts[id], - let pool = pjsua_pool_create("acc-read", 1024, 1024) else { return nil } - defer { pj_pool_release(pool) } - let cfg = UnsafeMutablePointer.allocate(capacity: 1) - cfg.initialize(to: pjsua_acc_config()) - defer { - cfg.deinitialize(count: 1) - cfg.deallocate() - } - guard pjsua_acc_get_config(entry.index, pool, cfg) == PJ.success else { return nil } - return AccountMapping.readBack(cfg) - } - private func verifyURI(_ uri: String, _ what: String) throws { guard pjsua_verify_sip_url(uri) == PJ.success else { throw EngineError.invalidArgument("\(what) \"\(uri)\" is not a valid SIP URI") diff --git a/Sources/MacroSIPCore/Engine/Engine+Families.swift b/Sources/MacroSIPCore/Engine/Engine+Families.swift new file mode 100644 index 0000000..f65e5c9 --- /dev/null +++ b/Sources/MacroSIPCore/Engine/Engine+Families.swift @@ -0,0 +1,336 @@ +internal import CPJSUA +import Foundation + +// The IP family of accounts (docs/ENGINE.md "IPv6"): the decision, lookups of host names, and the one +// reconciler that moves accounts between the IPv4 and IPv6 transports. Triggers (a network change, +// IPv6 coming or going, a lookup answer, a REGISTER without any answer, a changed IP protocol) only +// record `AccountEntry.desired`; `reconcileFamilies` alone moves an account, when nothing can be hurt +// by it: no network-change round running, no call on the account, no REGISTER in flight. + +/// The family an account should be moved to, recorded for the settings of `generation`. +struct FamilyDesire: Sendable, Equatable { + var family: IPFamily + var reason: String + var generation: UInt64 +} + +extension Engine { + /// The first REGISTER of an account whose family depends on a running lookup waits this long at most. + static let lookupWait: Duration = .seconds(2) + /// A move waits this long for the answer to the old binding's un-REGISTER, then goes on. + static let moveUnregisterTimeout: Duration = .seconds(5) + + /// DNS SRV is in effect: pjsua has a resolver and looks up SRV records of hosts without a port. + var srvInEffect: Bool { !dnsServers.isEmpty } + + // MARK: - decision + + /// The account's family now, without waiting: a literal, a fixed protocol, the only family with a + /// transport, the SRV case, or a cached lookup decide at once; otherwise a lookup is started + /// (`lookupStarted`) and the answer is `provisional` (an existing account keeps its family) or what + /// an unresolved name gives (IPv4). Throws `.invalidArgument` when IPv4 only or IPv6 only + /// contradicts the server's IP literal: such an account could never register. + func decideFamily(_ cfg: AccountConfig, provisional: IPFamily? = nil) throws -> (family: IPFamily, lookupStarted: Bool) { + let host = IPFamilyPolicy.firstHop(of: cfg).host + if let literal = IPFamilyPolicy.conflict(in: cfg) { + throw EngineError.invalidArgument("server \(host) is an \(literal) address but the account is set to " + + "\(literal == .ipv6 ? "IPv4" : "IPv6") only") + } + let cached = familyLookups.cached(host) + var needed = false + let family = IPFamilyPolicy.decide(cfg, available: transports.families(for: cfg), srv: srvInEffect) { _ in + if let cached { return cached } + needed = true + return [] + } + guard needed else { return (family, false) } + startLookup(host) + return (provisional ?? family, true) + } + + func logFamily(_ cfg: AccountConfig, _ family: IPFamily) { + let how = cfg.ipProtocol == .auto ? "auto" : "\(cfg.ipProtocol.rawValue) only" + emit(.log(level: 4, "engine: account \(cfg.uri): \(family) (\(how), server \(IPFamilyPolicy.firstHop(of: cfg).host))")) + } + + // MARK: - lookups + + /// A lookup of `host` off the engine queue (one in flight per host); the answer comes back through + /// `familiesResolved`. + func startLookup(_ host: String) { + familyLookups.start(host, resolve: resolveFamilies) { [weak self] host, families in + Task { await self?.familiesResolved(host, families) } + } + } + + /// A lookup answered: accounts of that host that wait for it record what it means (a desired family, + /// or the fallback it allows), and the reconciler runs. A failed lookup ([]) changes no family. + func familiesResolved(_ host: String, _ families: [IPFamily]) { + guard isStarted, PJ.registerThread() else { return } + let srv = srvInEffect + for id in Array(accounts.keys) { + guard var entry = accounts[id], IPFamilyPolicy.firstHop(of: entry.config).host == host else { continue } + if entry.registerDeadline != nil { entry.registerDeadline = .now } // answered: no more waiting + let other = entry.family.other + if entry.fallbackWaitsForLookup { + entry.fallbackWaitsForLookup = false + if families.contains(other) { wantFallback(&entry, to: other) } + } else if !entry.familySticky, !families.isEmpty, IPFamilyPolicy.followsResolver(entry.config, srv: srv) { + let decided = IPFamilyPolicy.decide(entry.config, available: transports.families(for: entry.config), + srv: srv) { _ in families } + entry.desired = decided == entry.family ? nil + : FamilyDesire(family: decided, reason: "\(host) resolves to \(decided) first", generation: entry.generation) + } + accounts[id] = entry + } + reconcileFamilies() + } + + // MARK: - triggers + + /// A network change (a round, or IPv6 coming or going): earlier answers no longer hold. Lookups are + /// dropped and made again, and every Auto account follows the system's order again: a family Auto + /// fell back to is forgotten, also in the DNS SRV case (back to IPv4 first). `abortMoves`: a round + /// re-registers every account, so a move whose un-REGISTER was sent starts again after it. + func familiesNetworkChanged(abortMoves: Bool) { + familyLookups.invalidate() + let srv = srvInEffect + for id in Array(accounts.keys) { + guard var entry = accounts[id] else { continue } + if abortMoves, entry.moveUnregisterSent != nil { + entry.moveUnregisterSent = nil + entry.moveUnregisterAnswered = false + } + entry.familyFallbackTried = false + entry.fallbackWaitsForLookup = false + let wasSticky = entry.familySticky + entry.familySticky = false + let hop = IPFamilyPolicy.firstHop(of: entry.config) + if IPFamilyPolicy.followsResolver(entry.config, srv: srv) { + entry.desired = nil // the new lookup decides + startLookup(hop.host) + } else if wasSticky { + // The SRV case: the order is IPv4 first, whatever Auto fell back to. + let decided = IPFamilyPolicy.decide(entry.config, available: transports.families(for: entry.config), + srv: srv) { _ in [] } + entry.desired = decided == entry.family ? nil + : FamilyDesire(family: decided, reason: "network change", generation: entry.generation) + } + accounts[id] = entry + } + } + + /// A REGISTER failed temporarily (`.reconnecting` is out); the backoff retry is scheduled. When it + /// got no answer at all (`noAnswer`: no response, i.e. a timeout, a refused or broken connection, no + /// address of the bound family), an Auto account with a host name wants the other family at once: + /// when the host has an address of it (a cached or a fresh lookup), or DNS SRV is in effect (the SRV + /// targets are unknown to the engine; the other family is the only chance). Once per series of + /// failures; the family then stays (`familySticky`) until the next network change. A result of + /// settings that changed meanwhile (`generation`) is not acted on. + func registrationRetryNeeded(_ id: AccountID, attempt: Int, after delay: TimeInterval, noAnswer: Bool, + generation: UInt64) { + scheduleRegistrationRetry(id, attempt: attempt, after: delay) + guard noAnswer, var entry = accounts[id], entry.generation == generation, entry.wantsRegistration, + !entry.familyFallbackTried, entry.config.ipProtocol == .auto else { return } + let hop = IPFamilyPolicy.firstHop(of: entry.config) + let other = entry.family.other + guard !hop.host.isEmpty, IPFamilyPolicy.literalFamily(hop.host) == nil, + transports.id(for: entry.config, family: other) != nil else { return } + entry.familyFallbackTried = true + if srvInEffect && hop.port == nil { + wantFallback(&entry, to: other) + } else if let cached = familyLookups.cached(hop.host) { + if cached.contains(other) { wantFallback(&entry, to: other) } + } else { + entry.fallbackWaitsForLookup = true + startLookup(hop.host) + } + accounts[id] = entry + reconcileFamilies() + } + + private func wantFallback(_ entry: inout AccountEntry, to other: IPFamily) { + emit(.log(level: 3, "engine: account \(entry.config.uri): no answer over \(entry.family); trying \(other)")) + entry.familySticky = true + entry.desired = FamilyDesire(family: other, reason: "no answer over \(entry.family)", generation: entry.generation) + } + + // MARK: - the reconciler + + /// Brings every account to its desired family, one step at a time; runs on the watchdog tick and + /// right after the events that matter (a desire recorded, a lookup answered, an un-REGISTER + /// answered, a round finished). A move starts only when no round runs, the account has no call in + /// any state and no REGISTER of it is in flight; it un-REGISTERs the old binding and waits for the + /// answer (at most `moveUnregisterTimeout`) before it moves and registers anew (`finishMove`). The + /// account shows `.registering` from the start of the move until the new REGISTER is answered. + func reconcileFamilies() { + guard isStarted, PJ.registerThread(), ipChange == nil, !sleeping, networkStatus == .online else { return } + let now = ContinuousClock.now + for id in Array(accounts.keys) { + guard let entry = accounts[id] else { continue } + if let sent = entry.moveUnregisterSent { + if entry.moveUnregisterAnswered || now - sent >= Engine.moveUnregisterTimeout { finishMove(id) } + continue + } + if let deadline = entry.registerDeadline, now < deadline { continue } + if let desired = entry.desired, desired.generation == entry.generation, desired.family != entry.family { + if !accountHasCalls(entry.index), !registrationBusy(entry) { + startMove(id) + continue + } + } else if entry.desired != nil { + accounts[id]?.desired = nil + } + if entry.registerDeadline != nil { + // No (usable) answer in time, or the move has to wait: register where the account is. + accounts[id]?.registerDeadline = nil + if entry.wantsRegistration { register(id) } + } + } + } + + /// A REGISTER or un-REGISTER of the account is in flight, or a request waits for one to end. + private func registrationBusy(_ entry: AccountEntry) -> Bool { + cpjsua_acc_reg_busy(entry.index) != 0 || bridge.pendingRegistration(entry.config.id) != nil + } + + private func startMove(_ id: AccountID) { + guard let entry = accounts[id], let desired = entry.desired else { return } + cancelRegistrationRetry(id) + accounts[id]?.registerDeadline = nil + guard hasBinding(id) else { + finishMove(id) + return + } + // The old binding must not stay at the registrar: a second Contact makes Kamailio fork calls, + // and Asterisk with max_contacts=1 and remove_existing=no refuses the new one with 403. + emit(.log(level: 3, "engine: account \(entry.config.uri): moving to \(desired.family) (\(desired.reason)); " + + "un-REGISTER over \(entry.family) first")) + bridge.setRegistration(id, .registering) + accounts[id]?.moveUnregisterSent = .now + accounts[id]?.moveUnregisterAnswered = false + if pjsua_acc_set_registration(entry.index, 0) != PJ.success { finishMove(id) } + } + + /// The answer to an un-REGISTER of an account that should stay registered (pjOnRegState2): the + /// move goes on. Outside a move, a registration requested meanwhile (PJSIP_EBUSY) is sent now. + func unregisterAnswered(_ id: AccountID, pendingOn: Bool) { + guard isStarted, PJ.registerThread(), accounts[id] != nil else { return } + if accounts[id]?.moveUnregisterSent != nil { + accounts[id]?.moveUnregisterAnswered = true + reconcileFamilies() + } else if pendingOn { + applyPendingRegistration(id, true) + } + } + + /// Moves the account to its desired family (the old binding is gone or given up on): the old + /// registration session is destroyed with `pjsua_acc_modify` (a late answer of it is dropped), the + /// live config gets `allow_sdp_nat_rewrite` (pjsua_acc_modify does not copy it), the MWI and + /// presence subscriptions are made anew on the new transport (their dialogs keep the old one), and + /// the account registers. A failure keeps the desire: the next tick tries again. A move that is no + /// longer wanted registers the account where it is. + private func finishMove(_ id: AccountID) { + guard var entry = accounts[id] else { return } + entry.moveUnregisterSent = nil + entry.moveUnregisterAnswered = false + guard let desired = entry.desired, desired.generation == entry.generation, desired.family != entry.family else { + entry.desired = nil + accounts[id] = entry + if entry.wantsRegistration { register(id) } + return + } + do { + let settings = try accountSettings(entry.config, password: entry.password, family: desired.family) + try AccountMapping.withPJConfig(settings) { p in + p.pointee.disable_reg_on_modify = 1 + try PJ.check(pjsua_acc_modify(entry.index, p), "pjsua_acc_modify") + } + cpjsua_acc_set_sdp_nat_rewrite(entry.index, settings.sdpNATRewrite ? 1 : 0) + } catch { + PJ.warn(error, "account \(entry.config.uri): move to \(desired.family)") + accounts[id] = entry + return + } + cpjsua_acc_end_mwi_after_move(entry.index) + emit(.log(level: 3, "engine: account \(entry.config.uri): server now reached over \(desired.family) " + + "(was \(entry.family), \(desired.reason))")) + entry.family = desired.family + entry.desired = nil + entry.generation &+= 1 + accounts[id] = entry + bridge.setAccountGeneration(entry.index, entry.generation) + bridge.setRegistrarSource(entry.index, nil) + resubscribePresence(accountIndex: entry.index) + if entry.wantsRegistration { register(id) } + } + + /// REGISTER now, shown as `.registering` until the answer. + private func register(_ id: AccountID) { + bridge.setRegistration(id, .registering) + do { try applyRegistration(id, true) } catch { PJ.warn(error, "register") } + } + + // MARK: - helpers + + /// The registrar holds a binding of the account (last REGISTER answered 2xx). + func hasBinding(_ id: AccountID) -> Bool { + if case .registered = bridge.registration(of: id) { return true } + return false + } + + /// The account has a call in any state (ringing, connecting, connected, held). + func accountHasCalls(_ index: pjsua_acc_id) -> Bool { + CallSnapshot.allSlots().contains { slot in + guard let snap = CallSnapshot.read(slot) else { return false } + return snap.accIndex == index && snap.state != .disconnected + } + } + + /// Presence subscriptions of buddies watched through this account, anew (after a move). + func resubscribePresence(accountIndex index: pjsua_acc_id) { + guard isStarted, PJ.registerThread() else { return } + for (key, buddy) in buddies.sorted(by: { $0.key < $1.key }) { + let account = key.withCString { p -> pjsua_acc_id in + var uri = cpjsua_str(p) + return pjsua_acc_find_for_outgoing(&uri) + } + guard account == index else { continue } + PJ.warn(cpjsua_buddy_resubscribe(buddy.id), "resubscribe presence of \(key)") + } + } + + // MARK: - test hooks + + func transportIDsForTests() -> TransportIDs { transports } + + func accountFamilyForTests(_ id: AccountID) -> IPFamily? { accounts[id]?.family } + + func setFamilyResolverForTests(_ resolve: @escaping @Sendable (String) -> [IPFamily]) { + resolveFamilies = resolve + familyLookups.invalidate() + } + + func setIPv6AddressAssignedForTests(_ assigned: @escaping @Sendable (String) -> Bool) { + ipv6AddressAssigned = assigned + } + + /// The account's pjsua_acc_config as pjsua holds it now (pjsua_acc_get_config). + func liveAccountSettingsForTests(_ id: AccountID) -> PJAccountSettings? { + guard isStarted, PJ.registerThread(), let entry = accounts[id], + let pool = pjsua_pool_create("acc-read", 1024, 1024) else { return nil } + defer { pj_pool_release(pool) } + let cfg = UnsafeMutablePointer.allocate(capacity: 1) + cfg.initialize(to: pjsua_acc_config()) + defer { + cfg.deinitialize(count: 1) + cfg.deallocate() + } + guard pjsua_acc_get_config(entry.index, pool, cfg) == PJ.success else { return nil } + return AccountMapping.readBack(cfg) + } +} + +extension IPFamily { + var other: IPFamily { self == .ipv4 ? .ipv6 : .ipv4 } +} diff --git a/Sources/MacroSIPCore/Engine/Engine+Network.swift b/Sources/MacroSIPCore/Engine/Engine+Network.swift index b5cb340..2f49875 100644 --- a/Sources/MacroSIPCore/Engine/Engine+Network.swift +++ b/Sources/MacroSIPCore/Engine/Engine+Network.swift @@ -263,9 +263,10 @@ extension Engine { + (kept.isEmpty ? "unknown" : kept.joined(separator: " ")))) } // IPv4: an IPv6-only network has no IPv4 route; keep the address we had. IPv6: keep it only - // while it is still assigned (the lookup failed for a moment); otherwise IPv6 is gone. + // while the path still routes IPv6 and the address is still assigned (the lookup failed for a + // moment); otherwise IPv6 is gone. if path.address.isEmpty { path.address = previous?.address ?? "" } - if path.address6.isEmpty, let kept = previous?.address6, !kept.isEmpty, ipv6AddressAssigned(kept) { + if path.address6.isEmpty, path.ipv6Route, let kept = previous?.address6, !kept.isEmpty, ipv6AddressAssigned(kept) { path.address6 = kept } handledPath = path @@ -281,7 +282,7 @@ extension Engine { let ipv6Accounts = accounts.values.contains { $0.family == .ipv6 } let oldV6 = previous?.address6 ?? "" let v6Changed = previous != nil && path.address6 != oldV6 - let v6Gone = v6Changed && !oldV6.isEmpty && !ipv6AddressAssigned(oldV6) + let v6Gone = v6Changed && !oldV6.isEmpty && (!path.ipv6Route || !ipv6AddressAssigned(oldV6)) let primary = (previous.map { path.primaryDiffers(from: $0, ipv6: false) } ?? true) || (ipv6Accounts && v6Gone) if wake { requestIPChange(IPChangeRequest(reason: "wake", registerFailed: true, primary: primary)) @@ -294,10 +295,9 @@ extension Engine { emit(.log(level: 3, "engine: IPv6 address \(oldV6.isEmpty ? "none" : oldV6) -> " + "\(path.address6.isEmpty ? "none" : path.address6); no account uses IPv6, no round")) // IPv6 appearing or going away may change what an Auto host name resolves to first; a new - // temporary address does not. A family Auto fell back to stays (no change of reachability). + // temporary address does not. The reconciler moves accounts (after a running round). if oldV6.isEmpty != path.address6.isEmpty { - refreshAccountFamilies(Array(accounts.keys), reason: "IPv6 \(path.address6.isEmpty ? "lost" : "appeared")", - register: true) + familiesNetworkChanged(abortMoves: false) } } } @@ -387,12 +387,8 @@ extension Engine { } // A host name may now resolve to the other family first (an IPv6-only network, IPv6 lost): - // move such accounts before pjsua re-registers them (an account whose registration was - // destroyed by the move is registered afresh: cpjsua_acc_prepare_ip_change below). The - // family Auto fell back to stays only until a network change. Accounts with calls keep - // their family until the calls end. - clearFamilyFallbacks() - refreshAccountFamilies(Array(accounts.keys), reason: "network change", register: false) + // Auto accounts look again; the reconciler moves them after this round. + familiesNetworkChanged(abortMoves: true) var pending: Set = [] for (id, entry) in accounts { let state = bridge.registration(of: id) @@ -463,6 +459,7 @@ extension Engine { queuedIPChange = nil requestIPChange(next) } + reconcileFamilies() // moves that waited for the round } /// Re-INVITE with a new media transport, Contact and Via for the round the call wants. @@ -699,7 +696,7 @@ extension Engine { for key in Array(reinviteAttempts.keys) where !live.contains(key) { reinviteAttempts[key] = nil } for key in Array(reinviteSince.keys) where !live.contains(key) { reinviteSince[key] = nil } expireStaleReinvites(now) - runDeferredMoves() + reconcileFamilies() if let postponed = postponedIPChange, ipChange == nil, !outgoingCallRinging() || now - postponed.since >= Engine.postponeLimit { postponedIPChange = nil @@ -764,8 +761,7 @@ extension Engine { } emit(.log(level: RegistrationBackoff.logLevel(attempt: attempt + 1), "engine: account \(entry.config.uri): REGISTER retry \(attempt + 1)")) - accounts[id]?.familyFallbackTried = false - refreshAccountFamilies([id], reason: "REGISTER retry", register: false) + accounts[id]?.familyFallbackTried = false // a new attempt may fall back once more do { try applyRegistration(id, true, retrying: true) } catch { @@ -775,56 +771,6 @@ extension Engine { } } - /// A REGISTER failed temporarily (`.reconnecting` is out). When it got no answer at all, an Auto - /// account may try the other family at once (`tryOtherFamily`); otherwise the backoff retry. - func registrationRetryNeeded(_ id: AccountID, attempt: Int, after delay: TimeInterval, noAnswer: Bool) { - if noAnswer, tryOtherFamily(id) { return } - scheduleRegistrationRetry(id, attempt: attempt, after: delay) - } - - /// Auto keeps the system's order for the first attempt; when a REGISTER over that family got no - /// answer at all (no response: a timeout, a refused or broken connection, no address of the - /// family), the account moves to the other family and registers at once, if the host name has an - /// address of it (or DNS SRV is in effect: the SRV targets are unknown here, the other family is - /// the only chance). Once per series of failures; the family then stays until the next network - /// change (`familySticky`). Not for literals, IPv4 only / IPv6 only, accounts with calls, during a - /// round, offline or asleep. - private func tryOtherFamily(_ id: AccountID) -> Bool { - guard isStarted, PJ.registerThread(), var entry = accounts[id], entry.wantsRegistration, - !entry.familyFallbackTried, !sleeping, networkStatus == .online, ipChange == nil, - entry.config.ipProtocol == .auto else { return false } - let hop = IPFamilyPolicy.firstHop(of: entry.config) - guard !hop.host.isEmpty, IPFamilyPolicy.literalFamily(hop.host) == nil else { return false } - let other: IPFamily = entry.family == .ipv4 ? .ipv6 : .ipv4 - guard transports.id(for: entry.config, family: other) != nil, !accountHasCalls(entry.index) else { return false } - if !(srvInEffect && hop.port == nil) { - guard lookupFamilies([hop.host])[hop.host]?.contains(other) == true else { return false } - } - let from = entry.family - entry.familyFallbackTried = true - accounts[id] = entry - emit(.log(level: 3, "engine: account \(entry.config.uri): no answer over \(from); trying \(other)")) - guard moveAccount(id, to: other, reason: "no answer over \(from)", register: false) else { return false } - accounts[id]?.familySticky = true - cancelRegistrationRetry(id) - do { - try applyRegistration(id, true, retrying: true) - } catch { - if let next = bridge.registrationFailedTemporarily(id, lastError: "\(error)") { - scheduleRegistrationRetry(id, attempt: next.attempt, after: next.delay) - } - } - return true - } - - /// A network change: Auto accounts follow the resolver again. - func clearFamilyFallbacks() { - for id in Array(accounts.keys) { - accounts[id]?.familySticky = false - accounts[id]?.familyFallbackTried = false - } - } - func cancelRegistrationRetry(_ id: AccountID) { registrationRetries.removeValue(forKey: id)?.cancel() } diff --git a/Sources/MacroSIPCore/Engine/Engine.swift b/Sources/MacroSIPCore/Engine/Engine.swift index cb94065..025ce07 100644 --- a/Sources/MacroSIPCore/Engine/Engine.swift +++ b/Sources/MacroSIPCore/Engine/Engine.swift @@ -51,16 +51,27 @@ public actor Engine { var index: pjsua_acc_id var config: AccountConfig var password: String - /// The IP family the account is bound to (`IPFamilyPolicy`); decided again on network - /// changes and REGISTER retries when it follows the resolver. + /// The IP family the account is bound to (docs/ENGINE.md "IPv6"). Only `reconcileFamilies` + /// moves an account to the other family; everything else records `desired`. var family: IPFamily = .ipv4 - /// Auto moved the account to the other family after a REGISTER got no answer; the family - /// that works stays until the next network change (no re-decision before retries). + /// Bumped by `updateAccount` and by every move: a desire, or a REGISTER result, of an older + /// generation belongs to settings that are gone. + var generation: UInt64 = 0 + /// The family the account should move to, and why. + var desired: FamilyDesire? + /// Auto moved the account after a REGISTER got no answer: the resolver's order is not + /// followed again until the next network change. var familySticky = false - /// The other family was tried at once in this series of failed REGISTERs. + /// The other family was wanted at once in this series of failed REGISTERs. var familyFallbackTried = false - /// A move to another family that waits for the account's calls to end. - var pendingMove: (family: IPFamily, reason: String)? + /// That fallback waits for a lookup of the host (does it have an address of the other family?). + var fallbackWaitsForLookup = false + /// The first REGISTER (after add, or after a change of server) waits for the host's lookup: + /// until its answer (the deadline becomes now) or this deadline, whichever comes first. + var registerDeadline: ContinuousClock.Instant? + /// A move's un-REGISTER of the old binding: when it was sent, and whether its answer came. + var moveUnregisterSent: ContinuousClock.Instant? + var moveUnregisterAnswered = false /// Last status given to `publishPresence` (re-applied when the account changes). var presence: PresenceStatus = .available /// Registration requested (cfg.registers or setRegistered): retried after temporary @@ -83,9 +94,8 @@ public actor Engine { /// The families of a host name in the system resolver's order (`IPFamilyResolver.system`; tests /// inject their own so they do not depend on real DNS). var resolveFamilies: @Sendable (String) -> [IPFamily] = { IPFamilyResolver.system($0) } - /// How long the engine waits for family lookups (they run concurrently off the engine queue; a - /// host not resolved in time keeps the account's family, or gives IPv4 for a new account). - var familyLookupTimeout: Duration = .seconds(2) + /// Lookups of host names off the engine queue: one in flight per host, answers cached briefly. + let familyLookups = FamilyLookups() /// Whether an IPv6 address is still assigned to an interface (`NetworkPath.isAssignedLocally`; /// tests inject their own). var ipv6AddressAssigned: @Sendable (String) -> Bool = { NetworkPath.isAssignedLocally($0) } diff --git a/Sources/MacroSIPCore/Engine/EngineBridge.swift b/Sources/MacroSIPCore/Engine/EngineBridge.swift index d039c50..eeddc60 100644 --- a/Sources/MacroSIPCore/Engine/EngineBridge.swift +++ b/Sources/MacroSIPCore/Engine/EngineBridge.swift @@ -90,6 +90,9 @@ final class EngineBridge: Sendable { /// `registers`, setRegistered). A REGISTER that pjsua sends on its own for an /// account that should not be registered is undone (see pjOnRegState2). var wantsRegistration = false + /// The engine's `AccountEntry.generation`: a REGISTER result carries it to the engine, which + /// drops a result of settings that changed meanwhile. + var generation: UInt64 = 0 } struct WatchedBuddy: Sendable { @@ -114,9 +117,6 @@ final class EngineBridge: Sendable { var pendingRegistration: [AccountID: Bool] = [:] /// Failed REGISTER attempts since the last success (temporary failures only). var retryAttempts: [AccountID: Int] = [:] - /// Accounts being moved to the other IP family: the result of the un-REGISTER of the old - /// binding sent just before the move is not a registration state of the account. - var ignoringUnregister: Set = [] /// Accounts with a repair of a missing binding going on, or given up (see `BindingRepair`). var bindingRepair: [AccountID: BindingRepair] = [:] /// Calls pjsua re-INVITEd in the current network change (by call serial). @@ -213,14 +213,19 @@ final class EngineBridge: Sendable { // MARK: accounts - func setAccount(_ index: Int32, _ id: AccountID, registrationInterval: Int, proxy: SignallingSource? = nil) { + func setAccount(_ index: Int32, _ id: AccountID, registrationInterval: Int, proxy: SignallingSource? = nil, + generation: UInt64 = 0) { state.withLock { st in let wants = st.accounts[index]?.id == id ? st.accounts[index]?.wantsRegistration ?? false : false st.accounts[index] = AccountSlot(id: id, registrationInterval: registrationInterval, proxy: proxy, - wantsRegistration: wants) + wantsRegistration: wants, generation: generation) } } + func setAccountGeneration(_ index: Int32, _ generation: UInt64) { + state.withLock { $0.accounts[index]?.generation = generation } + } + func setWantsRegistration(_ index: Int32, _ on: Bool) { state.withLock { $0.accounts[index]?.wantsRegistration = on } } @@ -229,14 +234,6 @@ final class EngineBridge: Sendable { state.withLock { $0.registrarSources[index] = source } } - func setIgnoringUnregister(_ index: Int32, _ on: Bool) { - state.withLock { if on { $0.ignoringUnregister.insert(index) } else { $0.ignoringUnregister.remove(index) } } - } - - func isIgnoringUnregister(_ index: Int32) -> Bool { - state.withLock { $0.ignoringUnregister.contains(index) } - } - /// The INVITE came from the server that accepted the account's REGISTER, or from its /// outbound proxy (IP literal). func isTrustedSource(_ source: SignallingSource, account index: Int32) -> Bool { @@ -984,9 +981,17 @@ private func pjOnRegStarted2(_ accID: pjsua_acc_id, _ info: UnsafeMutablePointer private func pjOnRegState2(_ accID: pjsua_acc_id, _ info: UnsafeMutablePointer?) { let bridge = EngineBridge.shared guard let account = bridge.account(for: accID) else { return } - // The un-REGISTER of the old binding before a move to the other IP family (Engine.moveAccount). - if let info, info.pointee.renew == 0, bridge.isIgnoringUnregister(accID) { return } let id = account.id + // An un-REGISTER of an account that should stay registered (the old binding of a move to the other + // IP family, or the un-REGISTER before sleep, whose state the engine set itself) is not a state of + // the account: whatever arrives late, it never shows `.unregistered` while the engine registers it. + if let info, info.pointee.renew == 0, account.wantsRegistration { + bridge.setRegistrarSource(accID, nil) + bridge.bindingRepairInterrupted(id) + let pendingOn = bridge.takePendingRegistration(id) == true + bridge.hop { await $0.unregisterAnswered(id, pendingOn: pendingOn) } + return + } var new: RegistrationState var source: SignallingSource? var transientError: String? @@ -1077,7 +1082,11 @@ private func pjOnRegState2(_ accID: pjsua_acc_id, _ info: UnsafeMutablePointer

= [] + var epoch: UInt64 = 0 + } + + private let state = OSAllocatedUnfairLock(initialState: State()) + let ttl: Duration + + init(ttl: Duration = .seconds(30)) { + self.ttl = ttl + } + + func cached(_ host: String) -> [IPFamily]? { + state.withLock { st in + guard let entry = st.cache[host], ContinuousClock.now - entry.at < ttl else { return nil } + return entry.families + } + } + + func invalidate() { + state.withLock { st in + st.cache = [:] + st.inFlight = [] + st.epoch &+= 1 + } + } + + /// Starts a lookup of `host` on a global queue unless one is running; `done` gets its answer ([] + /// when it failed), unless an `invalidate()` came in between. + func start(_ host: String, resolve: @escaping @Sendable (String) -> [IPFamily], + done: @escaping @Sendable (String, [IPFamily]) -> Void) { + let epoch: UInt64? = state.withLock { st in + guard !host.isEmpty, !st.inFlight.contains(host) else { return nil } + st.inFlight.insert(host) + return st.epoch + } + guard let epoch else { return } + DispatchQueue.global(qos: .userInitiated).async { [self] in + let families = resolve(host) + let current = state.withLock { st -> Bool in + guard st.epoch == epoch else { return false } + st.inFlight.remove(host) + if !families.isEmpty { st.cache[host] = (families, .now) } + return true + } + if current { done(host, families) } + } + } +} diff --git a/Sources/MacroSIPCore/Engine/NetworkPathMonitor.swift b/Sources/MacroSIPCore/Engine/NetworkPathMonitor.swift index 445e5d0..ca85e1b 100644 --- a/Sources/MacroSIPCore/Engine/NetworkPathMonitor.swift +++ b/Sources/MacroSIPCore/Engine/NetworkPathMonitor.swift @@ -19,17 +19,20 @@ struct NetworkPath: Sendable, Equatable { /// Source address of the default IPv6 route (a global address: link-local and loopback do not /// count), "" when there is none. var address6: String + /// The path can route IPv6 (`NWPath.supportsIPv6`). + var ipv6Route: Bool /// Default gateway, "" when unknown. var gateway: String /// Short text for the log. var summary: String init(satisfied: Bool, interface: String, address: String, address6: String = "", gateway: String, - summary: String? = nil) { + ipv6Route: Bool = true, summary: String? = nil) { self.satisfied = satisfied self.interface = interface self.address = address self.address6 = address6 + self.ipv6Route = ipv6Route self.gateway = gateway self.summary = summary ?? NetworkPath.describe(interface: interface, address: address, address6: address6, gateway: gateway) @@ -47,10 +50,11 @@ struct NetworkPath: Sendable, Equatable { } let name = primary?.name ?? "" let address = path.status == .satisfied ? (NetworkPath.defaultRouteSource() ?? "") : "" - let address6 = path.status == .satisfied ? (NetworkPath.defaultRouteSource6() ?? "") : "" + let ipv6Route = path.status == .satisfied && path.supportsIPv6 + let address6 = ipv6Route ? (NetworkPath.defaultRouteSource6() ?? "") : "" let gateway = path.gateways.first.map { "\($0)" } ?? "" self.init(satisfied: path.status == .satisfied, interface: name, address: address, address6: address6, - gateway: gateway, + gateway: gateway, ipv6Route: ipv6Route, summary: NetworkPath.describe(interface: name.isEmpty ? "" : "\(name)/\(type)", address: address, address6: address6, gateway: gateway)) } diff --git a/Tests/MacroSIPCoreTests/Engine262Tests.swift b/Tests/MacroSIPCoreTests/Engine262Tests.swift index 4638738..64318fe 100644 --- a/Tests/MacroSIPCoreTests/Engine262Tests.swift +++ b/Tests/MacroSIPCoreTests/Engine262Tests.swift @@ -8,13 +8,14 @@ import Testing // MARK: - DNS stub -/// A DNS server on 127.0.0.1 (one UDP socket, random port) that answers SRV and A queries +/// A DNS server on 127.0.0.1 (one UDP socket, random port) that answers SRV, A and AAAA queries /// from a fixed table and NXDOMAIN for everything else. Records every question as /// "SRV _sip._udp.example.test" / "A pbx.example.test". final class DNSStub: Sendable { enum Record: Sendable { case srv(target: String, port: UInt16) case a(String) + case aaaa(String) } let port: UInt16 @@ -103,6 +104,11 @@ final class DNSStub: Sendable { case let .a(address) where qtype == 1: let octets = address.split(separator: ".").compactMap { UInt8($0) } rr += DNSStub.u16(1) + DNSStub.u16(1) + [0, 0, 0, 60] + DNSStub.u16(4) + octets + case let .aaaa(address) where qtype == 28: + var v6 = in6_addr() + guard inet_pton(AF_INET6, address, &v6) == 1 else { continue } + let octets = withUnsafeBytes(of: &v6) { Array($0) } + rr += DNSStub.u16(28) + DNSStub.u16(1) + [0, 0, 0, 60] + DNSStub.u16(16) + octets default: continue } diff --git a/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift b/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift index 4463924..99b732a 100644 --- a/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift +++ b/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift @@ -11,7 +11,8 @@ import Testing /// A SIP stub on [::1]: one UDP socket and one TCP listener, and with `dualStack` a UDP socket on /// 127.0.0.1 with the same port number, so an account at "localhost:" reaches it over either -/// family. Answers REGISTER with 200 (Contacts listed; 403 on a family in `forbiddenFamilies`), +/// family. Answers REGISTER with 200 (Contacts listed; the status in `registerAnswers` for a family +/// that has one, e.g. "503 Service Unavailable"; an un-REGISTER `unregisterDelay` seconds late), /// INVITE with 200 and an answer in the offer's family (`IN IP6 ::1` or `IN IP4 127.0.0.1`; only 180 /// with `ringOnly`), everything else with 200; requests that arrive on a family in `silentFamilies` are /// recorded and left unanswered. Records every request with the family and transport it came over. Can send @@ -30,6 +31,7 @@ final class IPv6Stub: Sendable { var unregister = false /// The Event header ("message-summary", "presence"). var event = "" + var at = Date() } struct Response: Sendable { @@ -47,7 +49,8 @@ final class IPv6Stub: Sendable { private let rtp6: Int32 private let stopped = OSAllocatedUnfairLock(initialState: false) private let silent = OSAllocatedUnfairLock(initialState: Set()) - private let forbidden = OSAllocatedUnfairLock(initialState: Set()) + private let answers4REGISTER = OSAllocatedUnfairLock(initialState: [IPFamily: String]()) + private let unregisterLag = OSAllocatedUnfairLock(initialState: TimeInterval(0)) private let ringing = OSAllocatedUnfairLock(initialState: false) /// Headers of the INVITE left ringing (`ringOnly`), for the 487 after a CANCEL. private let ringingInvite = OSAllocatedUnfairLock<([String], String)?>(initialState: nil) @@ -65,9 +68,15 @@ final class IPv6Stub: Sendable { get { silent.withLock { $0 } } set { silent.withLock { $0 = newValue } } } - var forbiddenFamilies: Set { - get { forbidden.withLock { $0 } } - set { forbidden.withLock { $0 = newValue } } + /// REGISTER answers other than 200 per family ("503 Service Unavailable"). + var registerAnswers: [IPFamily: String] { + get { answers4REGISTER.withLock { $0 } } + set { answers4REGISTER.withLock { $0 = newValue } } + } + /// Seconds before an un-REGISTER is answered. + var unregisterDelay: TimeInterval { + get { unregisterLag.withLock { $0 } } + set { unregisterLag.withLock { $0 = newValue } } } var ringOnly: Bool { get { ringing.withLock { $0 } } @@ -288,9 +297,16 @@ final class IPv6Stub: Sendable { } switch method { case "REGISTER": - if forbiddenFamilies.contains(family) { reply("403 Forbidden"); return } + if let status = registerAnswers[family], !unregister { reply(status); return } let listed = expiresZero ? [] : contacts.map { "Contact: \($0);expires=299" } - reply("200 OK", extra: listed + ["Expires: \(expiresZero ? 0 : 300)"]) + let delay = unregister ? unregisterDelay : 0 + if delay > 0 { + DispatchQueue.global().asyncAfter(deadline: .now() + delay) { + reply("200 OK", extra: listed + ["Expires: \(expiresZero ? 0 : 300)"]) + } + } else { + reply("200 OK", extra: listed + ["Expires: \(expiresZero ? 0 : 300)"]) + } case "INVITE": if ringOnly && !inDialog { reply("100 Trying") @@ -908,9 +924,9 @@ extension EngineTests { /// An Auto account whose host name resolves to both families, registered over UDP. (`answer`: what /// the injected resolver returns.) func startAutoLocalhost(_ stub: IPv6Stub, answer: OSAllocatedUnfairLock<[IPFamily]>, transport: TransportKind = .udp, - mwi: Bool = false, publish: Bool = false) async throws -> (Engine, AccountConfig, EventLog, Task) { - let engine = await makeEngine(bindAddress: nil) - let log = EventLog() + mwi: Bool = false, bind: String? = nil) async throws -> (Engine, AccountConfig, TimedEventLog, Task) { + let engine = await makeEngine(bindAddress: bind) + let log = TimedEventLog() let consumer = log.consume(engine) await engine.setTestTimings(transactionTimeoutMs: 2000) await engine.setFamilyResolverForTests { _ in answer.withLock { $0 } } @@ -918,23 +934,63 @@ extension EngineTests { let port = transport == .tcp ? stub.tcpPort : stub.port // The domain carries the port, so MWI SUBSCRIBEs (to the account's own URI) reach the stub too. let account = AccountConfig(displayName: "L", username: "1009", domain: "localhost:\(port)", - transport: transport, publishPresence: publish, mwi: mwi) + transport: transport, mwi: mwi) try await engine.addAccount(account, password: "pw") return (engine, account, log, consumer) } - func logLines(_ log: EventLog, containing text: String) -> [String] { - log.all.compactMap { if case let .log(_, t) = $0, t.contains(text) { return t }; return nil } + /// Registered, and bound to `family`. + func registered(_ engine: Engine, _ id: AccountID, over family: IPFamily) async -> Bool { + let bound = await engine.accountFamilyForTests(id) + let state = await engine.registrationState(of: id) + return bound == family && state.isRegistered } - /// The family of an Auto host name is decided again on a network change; when it changed, the old - /// binding is removed (un-REGISTER over the old family) before the account registers over the new - /// one, and `allow_sdp_nat_rewrite` follows the family (pjsua_acc_modify does not copy it). + func logLines(_ log: TimedEventLog, containing text: String) -> [String] { + log.all.compactMap { if case let .log(_, t) = $0.1, t.contains(text) { return t }; return nil } + } + + /// A move as the registrar and the UI see it, after `since`: the old binding is un-REGISTERed over + /// `from` and answered, only then the account REGISTERs over `to` (at least `lag` later: the + /// un-REGISTER's answer is awaited), and the account shows `.registering` from the start of the move + /// and `.registered` only after that REGISTER; no `.unregistered` in between. + func expectMove(_ stub: IPv6Stub, _ log: TimedEventLog, _ id: AccountID, from: IPFamily, to: IPFamily, + since: Date, lag: TimeInterval = 0, unregisters: Bool = true, + sourceLocation: SourceLocation = #_sourceLocation) { + let after = stub.registers.filter { $0.at >= since } + let register = after.first { !$0.unregister && $0.family == to } + #expect(register != nil, "no REGISTER over \(to): \(after.map { "\($0.family) \($0.unregister)" })", + sourceLocation: sourceLocation) + guard let register else { return } + if unregisters { + let unregister = after.last { $0.unregister && $0.family == from && $0.at <= register.at } + #expect(unregister != nil, "no un-REGISTER over \(from) before it", sourceLocation: sourceLocation) + if let unregister { + #expect(register.at.timeIntervalSince(unregister.at) >= lag, "REGISTER \(register.at.timeIntervalSince(unregister.at)) s after the un-REGISTER", + sourceLocation: sourceLocation) + } + } + let states = log.registrations(id).filter { $0.0 >= since } + let moving = states.firstIndex { $0.1 == .registering } + let done = states.lastIndex { if case .registered = $0.1 { return true }; return false } + #expect(moving != nil && done != nil && moving! < done!, "states \(states.map(\.1))", sourceLocation: sourceLocation) + if let moving, let done { + #expect(states[done].0 >= register.at, "registered before the new REGISTER", sourceLocation: sourceLocation) + let between = states[moving.. started } }) + let v4 = try #require(stub.bindingRegisters.first { $0.family == .ipv4 && $0.at > started }) + // Round REGISTER timeout (2 s) and the move; the old path waited for a 2 s backoff and a + // second 2 s IPv6 timeout first. + #expect(v4.at.timeIntervalSince(started) < 3.5, "\(v4.at.timeIntervalSince(started)) s") + #expect(await waitUntil { await engine.registrationState(of: account.id).isRegistered }) + await engine.stop() + } + /// A TCP connection that is refused counts as no answer: the account moves to IPv6 at once. @Test func autoFallsBackWhenTheConnectionIsRefused() async throws { let stub = try IPv6Stub() // TCP on [::1] only @@ -1022,27 +1117,30 @@ extension EngineTests { await engine.stop() } - /// A server that answers (403) is not a reason to try the other family. + /// A server that answers is no reason to try the other family, even with a temporary failure it + /// sends itself (503: retried with backoff, on the same family). Only no answer at all is (the + /// REGISTER result has no rdata). @Test func autoKeepsTheFamilyWhenTheServerAnswers() async throws { let stub = try IPv6Stub(dualStack: true) defer { stub.stop() } - stub.forbiddenFamilies = [.ipv6] + stub.registerAnswers = [.ipv6: "503 Service Unavailable"] let answer = OSAllocatedUnfairLock(initialState: [IPFamily.ipv6, .ipv4]) let (engine, account, _, consumer) = try await startAutoLocalhost(stub, answer: answer) defer { consumer.cancel() } #expect(await waitUntil { - if case .failed(403, _) = await engine.registrationState(of: account.id) { return true } + if case .reconnecting = await engine.registrationState(of: account.id) { return true } return false }) - try await Task.sleep(for: .milliseconds(500)) - #expect(stub.registers.allSatisfy { $0.family == .ipv6 }) + // The first retry comes after 2 s: still IPv6. + #expect(await waitUntil(timeout: 4) { stub.bindingRegisters.count >= 2 }) + #expect(stub.registers.allSatisfy { $0.family == .ipv6 }, "\(stub.registers.map(\.family))") #expect(await engine.accountFamilyForTests(account.id) == .ipv6) await engine.stop() } - /// An account is never moved to the other family while it has a call (the dialog would keep - /// the old family's peer and lose its transport): the round keeps it, the move waits for the - /// call to end, then the account moves and registers. + /// An account is never moved to the other family while it has a call (the dialog would keep the + /// old family's peer and lose its transport): the round keeps it, the move waits for the call to + /// end, then the account moves (un-REGISTER, REGISTER) as any move does. @Test func familyMoveWaitsForTheAccountsCalls() async throws { let stub = try IPv6Stub(dualStack: true) defer { stub.stop() } @@ -1056,17 +1154,80 @@ extension EngineTests { answer.withLock { $0 = [.ipv6, .ipv4] } await engine.simulateNetworkChange() #expect(await waitUntil { await engine.ipChangeStateForTests().running == nil }) - try await Task.sleep(for: .milliseconds(500)) + try await Task.sleep(for: .milliseconds(1500)) #expect(await engine.accountFamilyForTests(account.id) == .ipv4) #expect(stub.bindingRegisters.allSatisfy { $0.family == .ipv4 }) #expect(await engine.calls().first { $0.id == call }?.state == .connected) - #expect(!logLines(log, containing: "waits for its calls").isEmpty) + let since = Date() try await engine.hangup(call) #expect(await waitUntil { await engine.calls().isEmpty }) - #expect(await waitUntil(timeout: 4) { stub.bindingRegisters.last?.family == .ipv6 }) + #expect(await waitUntil(timeout: 4) { await self.registered(engine, account.id, over: .ipv6) }) + expectMove(stub, log, account.id, from: .ipv4, to: .ipv6, since: since) + await engine.stop() + } + + /// IPv6 appearing while a round runs (here: its REGISTER waits for an answer) must not touch the + /// account until the round ends: the round completes on its own REGISTER result (not the 7 s safety + /// timer), and only then the account moves to IPv6 and ends up registered there. + @Test func ipv6AppearingDuringARoundWaitsForTheRound() async throws { + let stub = try IPv6Stub(dualStack: true) + defer { stub.stop() } + let answer = OSAllocatedUnfairLock(initialState: [IPFamily.ipv4, .ipv6]) + let (engine, account, log, consumer) = try await startAutoLocalhost(stub, answer: answer) + defer { consumer.cancel() } + await engine.setIPv6AddressAssignedForTests { $0 == "2001:db8::10" } + func path(_ v6: String) -> NetworkPath { + NetworkPath(satisfied: true, interface: "en0", address: "192.168.1.20", address6: v6, gateway: "192.168.1.1") + } #expect(await waitUntil { await engine.registrationState(of: account.id).isRegistered }) - #expect(await engine.accountFamilyForTests(account.id) == .ipv6) + await engine.applyPathForTests(path("")) + #expect(await waitUntil { await engine.ipChangeStateForTests().running == nil }) + #expect(await waitUntil { await engine.registrationState(of: account.id).isRegistered }) + + stub.registerAnswers = [.ipv4: "503 Service Unavailable"] // the round's REGISTER fails over IPv4... + stub.silentFamilies = [.ipv4] // ...after 2 s without an answer + let started = Date() + await engine.simulateNetworkChange() + #expect(await engine.ipChangeStateForTests().running != nil) + answer.withLock { $0 = [.ipv6, .ipv4] } + await engine.applyPathForTests(path("2001:db8::10")) // IPv6 appeared, no IPv6 account + try await Task.sleep(for: .milliseconds(300)) + #expect(await engine.accountFamilyForTests(account.id) == .ipv4) // not during the round + stub.silentFamilies = [] + stub.registerAnswers = [:] + #expect(await waitUntil(timeout: 5) { await engine.ipChangeStateForTests().running == nil }) + #expect(Date().timeIntervalSince(started) < 5, "the round ended by its safety timer") + #expect(logLines(log, containing: "no completion report").isEmpty) + #expect(await waitUntil(timeout: 6) { await self.registered(engine, account.id, over: .ipv6) }) + #expect(stub.bindingRegisters.last?.family == .ipv6) + await engine.stop() + } + + /// DNS SRV in effect, no port: Auto starts with IPv4; with no answer over IPv4 it falls back to + /// IPv6 (the only other chance), and a network change undoes that (back to IPv4 first). + @Test func srvFallbackIsUndoneAtANetworkChange() async throws { + let stub = try IPv6Stub(dualStack: true) + defer { stub.stop() } + let dns = try DNSStub(records: [ + "_sip._udp.example.test": [.srv(target: "pbx.example.test", port: stub.port)], + "pbx.example.test": [.a("127.0.0.1"), .aaaa("::1")], + ]) + defer { dns.stop() } + stub.silentFamilies = [.ipv4] + let engine = await makeEngine(bindAddress: nil) + await engine.setTestTimings(transactionTimeoutMs: 2000) + var net = Self.network + net.dnsSRV = true + net.nameserver = "127.0.0.1:\(dns.port)" + try await engine.start(network: net) + let account = AccountConfig(displayName: "S", username: "1001", domain: "example.test", mwi: false) + try await engine.addAccount(account, password: "pw") + #expect(await waitUntil(timeout: 6) { await self.registered(engine, account.id, over: .ipv6) }) + let mark = Date() + await engine.simulateNetworkChange() + #expect(await waitUntil(timeout: 6) { stub.bindingRegisters.contains { $0.family == .ipv4 && $0.at > mark } }, + "\(stub.registers.map { "\($0.family) \($0.unregister)" })") await engine.stop() } @@ -1094,47 +1255,56 @@ extension EngineTests { await engine.stop() } - /// Family lookups during a round are made once per host name, concurrently and off the engine - /// queue's critical path: a slow resolver delays the round by the lookup limit at most, and an - /// account whose lookup did not finish keeps its family. `addAccount` waits no longer either. - @Test func familyLookupsAreDedupedAndBounded() async throws { - let calls = OSAllocatedUnfairLock(initialState: [String: Int]()) - let slow = OSAllocatedUnfairLock(initialState: false) + /// Family lookups never block the engine: a slow resolver delays neither `addAccount` nor a round; + /// one lookup runs per host however many accounts or triggers want it, and its answer is cached + /// for a while. A new account waits for its lookup before its first REGISTER (at most the lookup + /// wait), then registers over what the lookup said. + @Test func familyLookupsDoNotBlockTheEngine() async throws { + let stub = try IPv6Stub(dualStack: true) + defer { stub.stop() } + let calls = OSAllocatedUnfairLock(initialState: 0) + let slow = OSAllocatedUnfairLock(initialState: 0.0) let engine = await makeEngine(bindAddress: nil) - await engine.setFamilyLookupTimeoutForTests(.milliseconds(300)) - await engine.setFamilyResolverForTests { host in - calls.withLock { $0[host, default: 0] += 1 } - if slow.withLock({ $0 }) { Thread.sleep(forTimeInterval: 1.5); return [.ipv6, .ipv4] } - return [.ipv4, .ipv6] + await engine.setFamilyResolverForTests { _ in + calls.withLock { $0 += 1 } + Thread.sleep(forTimeInterval: slow.withLock { $0 }) + return [.ipv6, .ipv4] } try await engine.start(network: Self.network) - let a = AccountConfig(displayName: "A", username: "1", domain: "localhost", registerWithServer: false, mwi: false) - let b = AccountConfig(displayName: "B", username: "2", domain: "localhost", registerWithServer: false, mwi: false) - try await engine.addAccount(a, password: "") - try await engine.addAccount(b, password: "") - #expect(await engine.accountFamilyForTests(a.id) == .ipv4) - - slow.withLock { $0 = true } - calls.withLock { $0 = [:] } + slow.withLock { $0 = 1 } + let a = AccountConfig(displayName: "A", username: "1", domain: "localhost:\(stub.port)", mwi: false) + let b = AccountConfig(displayName: "B", username: "2", domain: "localhost:\(stub.port)", mwi: false) let started = ContinuousClock.now - await engine.simulateNetworkChange() - #expect(ContinuousClock.now - started < .seconds(1.2)) - #expect(calls.withLock { $0["localhost"] } == 1) - #expect(await engine.accountFamilyForTests(a.id) == .ipv4) - #expect(await engine.accountFamilyForTests(b.id) == .ipv4) - - let c = AccountConfig(displayName: "C", username: "3", domain: "localhost", registerWithServer: false, mwi: false) - let added = ContinuousClock.now - try await engine.addAccount(c, password: "") - #expect(ContinuousClock.now - added < .seconds(1.2)) - #expect(await engine.accountFamilyForTests(c.id) == .ipv4) // not resolved in time: IPv4 + try await engine.addAccount(a, password: "pw") + try await engine.addAccount(b, password: "pw") + #expect(ContinuousClock.now - started < .milliseconds(500)) + #expect(stub.registers.isEmpty) // the first REGISTER waits for the lookup + #expect(await waitUntil(timeout: 4) { + let one = await engine.registrationState(of: a.id).isRegistered + let two = await engine.registrationState(of: b.id).isRegistered + return one && two + }) + #expect(stub.bindingRegisters.allSatisfy { $0.family == .ipv6 }, "\(stub.registers.map(\.family))") + #expect(calls.withLock { $0 } == 1) // one lookup for both accounts + + // Cached: an update that changes the server back to the same host asks nobody. + var moved = a + moved.registrar = "localhost:\(stub.port)" + try await engine.updateAccount(moved, password: nil) + #expect(calls.withLock { $0 } == 1) + + let round = ContinuousClock.now + await engine.simulateNetworkChange() // the cache is dropped; lookups again + #expect(ContinuousClock.now - round < .milliseconds(500)) + #expect(await waitUntil(timeout: 3) { calls.withLock { $0 } == 2 }) await engine.stop() } /// IPv6 address changes (pure rules through injected paths): IPv6 appearing or a new address - /// without IPv6 accounts starts no round (the family of Auto accounts is decided again without - /// one); with an IPv6 account a new temporary address whose predecessor is still assigned is a - /// non-primary change (it waits for a ringing outgoing call), while losing the address is primary. + /// without IPv6 accounts starts no round; with an IPv6 account a new temporary address whose + /// predecessor is still assigned is a non-primary change (it waits for a ringing outgoing call), + /// while losing the address is primary, also when the address stays assigned but the path has no + /// IPv6 route any more. @Test func ipv6AddressChangesStartRoundsOnlyWhenTheyMatter() async throws { let stub = try IPv6Stub() defer { stub.stop() } @@ -1142,8 +1312,9 @@ extension EngineTests { let engine = await makeEngine(bindAddress: nil) await engine.setIPv6AddressAssignedForTests { address in assigned.withLock { $0.contains(address) } } try await engine.start(network: Self.network) - func path(_ v6: String) -> NetworkPath { - NetworkPath(satisfied: true, interface: "en0", address: "192.168.1.20", address6: v6, gateway: "192.168.1.1") + func path(_ v6: String, route: Bool = true) -> NetworkPath { + NetworkPath(satisfied: true, interface: "en0", address: "192.168.1.20", address6: v6, gateway: "192.168.1.1", + ipv6Route: route) } func settle() async { _ = await waitUntil { await engine.ipChangeStateForTests().running == nil } } func rounds() async -> UInt64 { await engine.ipChangeStateForTests().rounds } @@ -1170,8 +1341,8 @@ extension EngineTests { #expect(await rounds() == count) #expect(await engine.calls().first { $0.id == call }?.state == .early) - assigned.withLock { $0 = [] } - await engine.applyPathForTests(path("")) // IPv6 lost: primary, at once + // The address stays assigned (an RA lifetime has not run out) but the path has no IPv6 route. + await engine.applyPathForTests(path("", route: false)) // IPv6 lost: primary, at once #expect(await waitUntil { await rounds() == count + 1 }) count += 1 await settle() diff --git a/docs/ENGINE.md b/docs/ENGINE.md index 7dafe3f..6f4bca9 100644 --- a/docs/ENGINE.md +++ b/docs/ENGINE.md @@ -344,7 +344,7 @@ Goal: a network drop, a Wi-Fi -> Ethernet/LTE switch, an IP change or sleep/wake **Path monitoring.** `NWPathMonitor` on its own queue (`macrosip.network`). `.satisfied` = online. A path is reduced to its primary route (`NetworkPath`): the first available interface (the one the system routes through), the source address of the default route (a UDP socket "connected" to 192.0.2.1 and read back with getsockname: the address pjsua's sockets use towards a server on the default route), the same for the default IPv6 route (2001:db8::1; a global address only, see "IPv6") and the first gateway. Secondary interfaces (bridge100 of Internet Sharing, a split-tunnel utun, a second Wi-Fi) coming and going change nothing; a full-tunnel VPN that takes the default route changes the interface and the address. The first update after `start` and every update while a wake is pending are applied at once; later ones are debounced by 2.5 s (the last one wins). Online -> offline: `.network(.offline)`, calls get `isReconnecting`. Offline -> online: `.network(.online)` and a round; a changed primary route while online: a round. A new local address on the same interface and gateway that produces no path update is not noticed (keep-alives, `allow_contact_rewrite` and the next REGISTER refresh deal with it). If no update arrives within 2 s after start, `.network(.online)` is emitted anyway. A satisfied path without a default route (the 192.0.2.1 lookup fails) keeps the previous address and counts as unchanged (logged); an IPv6-only network keeps the last IPv4 address the same way; the last IPv6 address is kept only while it is still assigned to an interface, so losing IPv6 is a change (the line is logged only when both are missing). IPv6 changes follow their own rules (see "IPv6": no round without IPv6 accounts, non-primary for a new temporary address). `Engine(monitorNetwork: false)` runs no NWPathMonitor: the network counts as online from `start` (a fixed path is reported at once) and only paths injected by tests change it; the engine tests use it so they do not depend on the host's network. -**Rounds (`requestIPChange` / `performIPChange`).** One round = one `pjsua_handle_ip_change`. Rounds never overlap: a request while a round runs is queued (the latest reason, flags merged) and started when the round completes. A request is "primary" when the interface or the local address changed (and for `simulateNetworkChange`); otherwise (gateway-only change, network back with the same address, wake with the same address) it is postponed while an outgoing call is still unanswered and runs when no outgoing call rings any more (checked every second, at most 90 s): pjsua hangs up an account's unconfirmed outgoing calls with 410 after that account's re-REGISTER (`pjsua_acc_handle_call_on_ip_change`; test `ringingCallOfReRegisteringAccountEndsOnAddressChange`), which is accepted only when the address really changed (such a call cannot complete then anyway). Steps: (1) every confirmed call gets `reinviteWanted = round` (`isReconnecting`). (2) Auto accounts with a host name decide their IP family again and move to the other family's transport when it changed, except accounts with calls, whose move waits (`refreshAccountFamilies`, see "IPv6"); then `cpjsua_acc_prepare_ip_change` per account decides whether pjsua re-REGISTERs it: pjsua's `handle_ip_change_on_acc` re-registers an account without a registration session only when its last REGISTER status was 200 or a temporary failure, and would therefore also REGISTER an account the user switched off (last code 200 after the un-REGISTER) and skip a working outgoing-only account's calls. The shim sets that internal status to 200 for accounts that should be registered (not while asleep; `.failed` ones only on wake) and to 0 for the rest, which pjsua then skips ("Permanent registration failure, IP change handling will stop for acc N" in PJSIP's log is this skip). A REGISTER that still arrives for an account that is off is undone. (3) `keep_inv_after_tsx_timeout` is switched on by the engine before pjsua sees it (pjsua then does not schedule its own timer that would switch it off one transaction timeout later, while re-INVITEs may still run) and off again when no round runs and no call waits for its re-INVITE, and after `pjsua_destroy`: a re-INVITE that times out does not end the call inside PJSIP; the engine decides. (4) `pjsua_handle_ip_change`: `shutdown_transport` (all TCP/TLS connections), `restart_listener` only when the engine is bound to all interfaces (a restart rebinds to 0.0.0.0 and recomputes the published address; with `bindAddress` set, as in the tests and the self-test, it would undo the binding), `restart_lis_delay` 100 ms. Account config: `ip_change_cfg.shutdown_tp = true`, `hangup_calls = false`, `reinvite_flags = PJSUA_CALL_REINIT_MEDIA | PJSUA_CALL_UPDATE_CONTACT | PJSUA_CALL_UPDATE_VIA`. pjsua re-REGISTERs (new Contact through `allow_contact_rewrite`) and after the 2xx re-INVITEs that account's confirmed calls. (5) On `PJSUA_IP_CHANGE_OP_COMPLETED` of this round (or after one transaction timeout + 5 s without it, so a late report cannot close the next round) the engine re-INVITEs every call of step 1 that pjsua did not (`PJSUA_IP_CHANGE_OP_ACC_REINVITE_CALLS` reports those), except calls whose account's re-REGISTER is still unanswered (pjsua re-INVITEs them after the answer; two re-INVITEs would reinitialise the media twice). Same flags, local hold kept (no UNHOLD flag, pjsua offers the hold SDP), audio only. Then a queued request runs. +**Rounds (`requestIPChange` / `performIPChange`).** One round = one `pjsua_handle_ip_change`. Rounds never overlap: a request while a round runs is queued (the latest reason, flags merged) and started when the round completes. A request is "primary" when the interface or the local address changed (and for `simulateNetworkChange`); otherwise (gateway-only change, network back with the same address, wake with the same address) it is postponed while an outgoing call is still unanswered and runs when no outgoing call rings any more (checked every second, at most 90 s): pjsua hangs up an account's unconfirmed outgoing calls with 410 after that account's re-REGISTER (`pjsua_acc_handle_call_on_ip_change`; test `ringingCallOfReRegisteringAccountEndsOnAddressChange`), which is accepted only when the address really changed (such a call cannot complete then anyway). Steps: (1) every confirmed call gets `reinviteWanted = round` (`isReconnecting`). (2) Auto accounts with a host name look again (`familiesNetworkChanged`, see "IPv6"; the reconciler moves them after the round); then `cpjsua_acc_prepare_ip_change` per account decides whether pjsua re-REGISTERs it: pjsua's `handle_ip_change_on_acc` re-registers an account without a registration session only when its last REGISTER status was 200 or a temporary failure, and would therefore also REGISTER an account the user switched off (last code 200 after the un-REGISTER) and skip a working outgoing-only account's calls. The shim sets that internal status to 200 for accounts that should be registered (not while asleep; `.failed` ones only on wake) and to 0 for the rest, which pjsua then skips ("Permanent registration failure, IP change handling will stop for acc N" in PJSIP's log is this skip). A REGISTER that still arrives for an account that is off is undone. (3) `keep_inv_after_tsx_timeout` is switched on by the engine before pjsua sees it (pjsua then does not schedule its own timer that would switch it off one transaction timeout later, while re-INVITEs may still run) and off again when no round runs and no call waits for its re-INVITE, and after `pjsua_destroy`: a re-INVITE that times out does not end the call inside PJSIP; the engine decides. (4) `pjsua_handle_ip_change`: `shutdown_transport` (all TCP/TLS connections), `restart_listener` only when the engine is bound to all interfaces (a restart rebinds to 0.0.0.0 and recomputes the published address; with `bindAddress` set, as in the tests and the self-test, it would undo the binding), `restart_lis_delay` 100 ms. Account config: `ip_change_cfg.shutdown_tp = true`, `hangup_calls = false`, `reinvite_flags = PJSUA_CALL_REINIT_MEDIA | PJSUA_CALL_UPDATE_CONTACT | PJSUA_CALL_UPDATE_VIA`. pjsua re-REGISTERs (new Contact through `allow_contact_rewrite`) and after the 2xx re-INVITEs that account's confirmed calls. (5) On `PJSUA_IP_CHANGE_OP_COMPLETED` of this round (or after one transaction timeout + 5 s without it, so a late report cannot close the next round) the engine re-INVITEs every call of step 1 that pjsua did not (`PJSUA_IP_CHANGE_OP_ACC_REINVITE_CALLS` reports those), except calls whose account's re-REGISTER is still unanswered (pjsua re-INVITEs them after the answer; two re-INVITEs would reinitialise the media twice). Same flags, local hold kept (no UNHOLD flag, pjsua offers the hold SDP), audio only. Then a queued request runs. **The engine's re-INVITE.** `reinviteInFlight = round` is set before `pjsua_call_reinvite2` is called (on loopback the answer can arrive before it returns) and put back if the call fails synchronously. A transaction in flight (hold, the remote's re-INVITE, an older round's re-INVITE) is waited for in 250 ms steps for up to one transaction timeout. Retry and busy tasks are kept per call and cancelled when a new round starts. @@ -354,7 +354,7 @@ Goal: a network drop, a Wi-Fi -> Ethernet/LTE switch, an IP change or sleep/wake **Media watchdog** (1 s tick, `ContinuousClock`, so wall-clock jumps do not count): per confirmed call the RTP packet count and the number of RTCP reports received (`rtcp.tx.update_cnt`). Clocks pause while the media is not active (local or remote hold), the network is offline or the Mac sleeps; a counter that goes back (new stream after a re-INVITE) restarts them and disarms the watchdog until RTCP arrives on the new stream. Armed only after at least one RTCP report on the stream (a peer without RTCP is never ended by it). No RTP and no RTCP for 60 s while online: an in-dialog OPTIONS probe; 408 or 481 -> the call ends as connection lost (PJSIP ends the dialog on these itself; the bridge maps that end the same way); any other answer (200, 405, 501) -> the call stays and the next probe is one period later. Offline calls are never ended by the engine. -**REGISTER retry with backoff.** pjsua's own retry is off (`reg_retry_interval = 0`, `drop_calls_on_reg_fail = false`). `RegistrationMapping.isTemporary`: 408, 480, 500, 502, 503, 504, no code, or a local failure (status other than PJ_SUCCESS: transport error, DNS failure, `PJSIP_ETPNOTAVAIL`, a refresh that could not be sent) -> temporary; 401/403/404/407/423 and every other 4xx-6xx -> `.failed`, no retry. Also permanent: TLS certificate and TLS configuration errors (the reason contains the text of `PJSIP_TLS_ECERTVERIF`, `ECACERT`, `ECERTFILE`, `EKEYFILE`, `EINVMETHOD`, `ECIPHER`, or "certificate"), and a host name that does not resolve (`PJ_ERESOLVE`, `PJLIB_UTIL_EDNS_NXDOMAIN`) after the network has been online for 10 s (a typo in the server name; right after a change DNS may not work yet, so then it is retried). A temporary failure of an account that should be registered emits `.reconnecting(attempt: n, nextRetryIn: d, lastError:)` with d = 2, 4, 8, 16, 32, then 60 s (`RegistrationBackoff`), and a timer sends the REGISTER again after d (an Auto account with a host name first decides its IP family again unless Auto moved it after a REGISTER without any answer, which also happens at once, without waiting for d; see "IPv6"). While a retry runs the state stays `.reconnecting` (no `.registering` in between). Success resets the count. A request that met `PJSIP_EBUSY` (a REGISTER in flight) is remembered and repeated when that transaction ends, except when its result is a temporary failure: then only the backoff retry sends the next REGISTER (26.0.1 sent both, so every retry met EBUSY and a REGISTER left after each transaction timeout without backoff). A REGISTER that cannot even be sent (without a network DNS and sendto fail inside `pjsua_acc_set_registration`; pjsua reports it through `on_reg_state2` before returning the error) is such a temporary failure too: `addAccount`, `updateAccount` and `setRegistered` do not throw or roll back for it (deviation from milestone 2.1's "addAccount rolls back if the registration cannot start", which still holds for other errors), the account stays and is retried, so the app can start offline. A retry that falls due while offline or asleep is not sent (the network coming back or wake re-registers through a round); during a round it waits for it. `setRegistered(true)`, `updateAccount` and wake start a fresh series; switching off cancels it. TCP/TLS: `on_transport_state` DISCONNECTED/SHUTDOWN of the transport an account's registration uses (pjsua's own registration bookkeeping, read in the callback before pjsua releases it) counts as a temporary failure ("TLS connection to ... disconnected") -> the same backoff; ignored during a round (it closes them on purpose). Keep-alives are unchanged. +**REGISTER retry with backoff.** pjsua's own retry is off (`reg_retry_interval = 0`, `drop_calls_on_reg_fail = false`). `RegistrationMapping.isTemporary`: 408, 480, 500, 502, 503, 504, no code, or a local failure (status other than PJ_SUCCESS: transport error, DNS failure, `PJSIP_ETPNOTAVAIL`, a refresh that could not be sent) -> temporary; 401/403/404/407/423 and every other 4xx-6xx -> `.failed`, no retry. Also permanent: TLS certificate and TLS configuration errors (the reason contains the text of `PJSIP_TLS_ECERTVERIF`, `ECACERT`, `ECERTFILE`, `EKEYFILE`, `EINVMETHOD`, `ECIPHER`, or "certificate"), and a host name that does not resolve (`PJ_ERESOLVE`, `PJLIB_UTIL_EDNS_NXDOMAIN`) after the network has been online for 10 s (a typo in the server name; right after a change DNS may not work yet, so then it is retried). A temporary failure of an account that should be registered emits `.reconnecting(attempt: n, nextRetryIn: d, lastError:)` with d = 2, 4, 8, 16, 32, then 60 s (`RegistrationBackoff`), and a timer sends the REGISTER again after d (after a REGISTER without any answer an Auto account may move to the other family at once instead, see "IPv6"). While a retry runs the state stays `.reconnecting` (no `.registering` in between). Success resets the count. A request that met `PJSIP_EBUSY` (a REGISTER in flight) is remembered and repeated when that transaction ends, except when its result is a temporary failure: then only the backoff retry sends the next REGISTER (26.0.1 sent both, so every retry met EBUSY and a REGISTER left after each transaction timeout without backoff). A REGISTER that cannot even be sent (without a network DNS and sendto fail inside `pjsua_acc_set_registration`; pjsua reports it through `on_reg_state2` before returning the error) is such a temporary failure too: `addAccount`, `updateAccount` and `setRegistered` do not throw or roll back for it (deviation from milestone 2.1's "addAccount rolls back if the registration cannot start", which still holds for other errors), the account stays and is retried, so the app can start offline. A retry that falls due while offline or asleep is not sent (the network coming back or wake re-registers through a round); during a round it waits for it. `setRegistered(true)`, `updateAccount` and wake start a fresh series; switching off cancels it. TCP/TLS: `on_transport_state` DISCONNECTED/SHUTDOWN of the transport an account's registration uses (pjsua's own registration bookkeeping, read in the callback before pjsua releases it) counts as a temporary failure ("TLS connection to ... disconnected") -> the same backoff; ignored during a round (it closes them on purpose). Keep-alives are unchanged. **A 2xx that leaves out our Contact.** A 2xx to a REGISTER lists the bindings the server holds. Behind NAT with Asterisk's `rewrite_contact=yes`, PJSIP's Contact rewrite (`PJSUA_CONTACT_REWRITE_NO_UNREG`) sends the new Contact and the old one at expires=0 in one request; the server rewrites both to the source address, adds and removes the same binding, and answers 200 with no Contact. Until the next refresh, up to the registration interval, no incoming call arrives. `pjOnRegState2` checks the answer (`cpjsua_regc_lists_our_contact`, other devices on the extension do not count) and sends the REGISTER again, now with one Contact; the account shows as registered only after that. A server that leaves it out again is believed from then on (`BindingRepair`), so it gets one extra REGISTER and not one per refresh. @@ -377,22 +377,22 @@ Code: `Model/NetworkSettings.swift` (fields, decoding, `isValidRTPRange`, `effec - **No STUN for private servers** (`stunServer` is global; `PrivateServer.allHopsPrivate`). An account whose every signalling hop is a private or local IP literal does not use STUN: `sip_stun_use` and `media_stun_use` are `PJSUA_STUN_USE_DISABLED`. Hops: the registrar, and the outbound proxy when one is set, otherwise the domain (INVITE, SUBSCRIBE and PUBLISH go there). Private: 10/8, 172.16/12, 192.168/16, 100.64/10 (RFC 6598 shared space: carrier NAT, Tailscale; never routed on the internet), 127/8, 169.254/16, ::1, fc00::/7, fe80::/10 (and IPv4-mapped forms). Host names are not resolved and keep STUN, and so does an account with one public or named hop. Why: such a server is reached on the LAN or over a VPN, where the STUN-mapped public address is wrong; the first REGISTER carried it in Contact and Via, PJSIP learnt the real address only from the 401's `received`/`rport` and registered again ("IP address change detected ... Updating registration (using method 2)"), and a server that does not rewrite Contact would send incoming calls to the public address. The flag alone does not change Contact and Via: for an account bound to the UDP transport pjsua takes both from the transport's published address, which STUN set at start (`pjsua_acc_get_uac_addr` -> `pjsip_tpmgr_find_local_addr2`, which ignores `local_if` under a `PJSIP_TPSELECTOR_TRANSPORT` selector, sip_transport.c). So while a STUN server is set, a UDP account of a private IPv4 server is not bound to the transport (`transport_id = PJSUA_INVALID_ID`): pjsua then takes the local address of the route to the server (`get_net_interface`) with the transport's port, and requests still go out through the one UDP transport (large ones stay on UDP through `disable_tcp_switch`, so the milestone 4 reason against unbinding no longer holds). An IPv6 server (also `[::ffff:a.b.c.d]`) makes the account an IPv6 account since 26.3.1: bound to the IPv6 twin of its transport, STUN off for every server (see "IPv6"); before, it stayed bound to the IPv4 transport and could never register. TCP/TLS listeners are never published with a STUN address and stay bound, as does every account when no STUN server is set. Media: a call asks no STUN from its RTP sockets, and `allow_sdp_nat_rewrite` is on, so the SDP takes the address the registrar reported in the REGISTER answer's Via (`received`, else our sent-by), which is what Contact ends up with too; without it pjsua offers the default route's address (`pj_gethostip`), which over a split-tunnel VPN is another interface than the one towards the server, and a PBX without symmetric RTP would send its audio there. Remaining: until the first REGISTER answer, and for an account that does not register, the SDP still has the default route's address. `allow_contact_rewrite`/`allow_via_rewrite` stay on: a server behind a VPN hub can still see another source address than the Mac's own (VPN NAT), and the rewrite after the first answer repairs the Contact then. Accepted follow-ups: an unbound account has `tp_type` UNSPECIFIED and so gets the transport-match score for incoming TCP/TLS requests too (pjsua_acc.c:523 and 3595), which can attribute an incoming TLS INVITE to a private UDP account instead of a TLS provider account with the same To host (the fix would be an `on_acc_find_for_incoming` that prefers the account whose transport matches); after `updateAccount` moves an account from a public to a private server, `destroy_regc` clears `acc->contact` but not `acc->via_addr`, so the first REGISTER's Via keeps the old address until the first answer (harmless with rport). ## IPv6 -Dual stack since 26.3.1 ([#11](https://github.com/HSMM/MacroSIP/issues/11), ADR 0014). Code: `IPFamily.swift` (`IPFamily`, `IPFamilyPolicy`, `IPFamilyResolver`, `SIPHop`), `transportFamilies` and `createTransports` in `Engine.swift`, `decideFamily` and `refreshAccountFamily` in `Engine+Accounts.swift`, `TransportIDs` and `AccountMapping.settings(... family:)`, `NetworkPath.address6`; C helpers `cpjsua_tls_transport_create(type, ...)` and `cpjsua_call_local_rtp_addr`. Setting: `AccountConfig.ipProtocol` (account editor › Advanced › Connection › IP protocol: Auto, IPv4 only, IPv6 only). +Dual stack since 26.3.1 ([#11](https://github.com/HSMM/MacroSIP/issues/11), ADR 0014). Code: `IPFamily.swift` (`IPFamily`, `IPFamilyPolicy`, `IPFamilyResolver`, `SIPHop`, `FamilyLookups`), `Engine+Families.swift` (`decideFamily`, the triggers that record `AccountEntry.desired`, and `reconcileFamilies`, the only code that moves an account), `transportFamilies` and `createTransports` in `Engine.swift`, `TransportIDs` and `AccountMapping.settings(... family:)`, `NetworkPath.address6` / `ipv6Route`; C helpers `cpjsua_tls_transport_create(type, ...)`, `cpjsua_call_local_rtp_addr`, `cpjsua_acc_reg_busy`, `cpjsua_acc_set_sdp_nat_rewrite`, `cpjsua_acc_end_mwi_after_move`, `cpjsua_buddy_resubscribe`; PJSIP patch `scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch`. Setting: `AccountConfig.ipProtocol` (account editor › Advanced › Connection › IP protocol: Auto, IPv4 only, IPv6 only). - **Transports.** Every transport has an IPv6 twin: UDP6, TCP6, TLS6 verifying and TLS6 non-verifying (`TransportIDs.udp6`, `tcp6`, `tls6`, `tls6NoVerify`). pjlib sets `IPV6_V6ONLY` on every IPv6 socket (`PJ_SOCK_HAS_IPV6_V6ONLY` is 1 in our build, `pj_sock_socket`), so `[::]:P` and `0.0.0.0:P` coexist and both families listen on the configured `localPort` (TLS on a random port, as before; with port 0 each family gets its own random port). The IPv4 UDP transport is required as before; the IPv6 ones are best effort: a failure is logged ("UDP over IPv6 transport on port P: ...") and only the accounts that would need that transport are refused (`EngineError.transportUnavailable(kind, ipv6: true)`). Without a global IPv6 address pjsua publishes the UDP6 transport with a link-local or loopback address (`pj_gethostip`), which only a server on the same link or on loopback can use. `localPort(of:family:)` reports the ports; `localPort(of:)` stays IPv4. pjsua keeps transports in a fixed table of 8 (`pjsua_var.tpdata[8]` in pjsua_internal.h, not a configurable macro): two families of four fill it exactly, so another transport needs a PJSIP patch (`createTransports` asserts it, `cpjsua_transport_slots`). - **Bind address** (`Engine(bindAddress:)`, `macrosip-cli --bind`; brackets are dropped, "[::1]" is "::1"). An address of one family creates that family's transports only, and its UDP is the required one; accounts of the other family are refused with `transportUnavailable`. No bind address: both families on all interfaces. RTP binds to the bind address only for accounts of its family (`AccountMapping`), which with a bind address are the only ones. A bind address that is not an IP literal counts as IPv4 (pjsua resolves it for an IPv4 socket). - **Accounts stay bound.** `pjsua_init_tpselector` turns `transport_id` into a TRANSPORT selector (UDP) or a LISTENER selector (TCP/TLS), which fixes the family; `ipv6_sip_use` (`PJSIP_TPSELECTOR_IP_VER`) only applies to unbound accounts. Unbinding would change Contact and Via under STUN and lose the choice between the verifying and the non-verifying TLS listener, so every account is bound to the transport of its family. pjsua then takes Contact and Via from that transport (`pjsua_acc_get_uac_addr` adds the IPv6 flag for an account whose `tp_type` is IPv6), and an incoming request over UDP6, TCP6 or TLS6 scores the transport match only for the accounts bound to that transport type (`pjsua_acc_find_for_incoming`). The unbound exception of "No STUN for private servers" is IPv4 only. -- **Which family** (`IPFamilyPolicy.decide`). The server is the first hop: the outbound proxy when one is set, otherwise the registrar (or the domain). An IP literal picks its own family; IPv4 only and IPv6 only with a host name use that family. Auto with a host name: when only one family has a transport for the account's kind (a bind address, a failed IPv6 transport), that family without a lookup; with DNS SRV in effect (pjsua has a resolver) and no explicit port, IPv4 first, because `getaddrinfo` cannot follow SRV records (pjsua resolves the SRV targets itself, A and AAAA, and skips entries of the other family; when nothing of IPv4 answers, the fallback below moves the account to IPv6); otherwise the first family that `getaddrinfo(host, AF_UNSPEC)` returns (`IPFamilyResolver.system`, with `pj_getaddrinfo`'s hints: no socket type, no flags) and that has a transport. That is the order PJSIP itself tries when it resolves a host name without its DNS resolver; it is not what PJSIP does with DNS SRV on (its own A/AAAA queries), and for an account that does not register the INVITEs go to the dialled URI's host, which may differ from the first hop. Nothing resolved (offline): IPv4, decided again later. Lookups run concurrently off the engine queue (`lookupFamilies`: each host once, one wait of at most `familyLookupTimeout`, 2 s, for all of them); a host not resolved in time gives IPv4 for a new account and keeps the family of an existing one. Tests inject a resolver (`setFamilyResolverForTests`). A host name that lacks the chosen family (IPv6 only, no AAAA) fails to register with a DNS error like any unknown host. +- **Which family** (`IPFamilyPolicy.decide`). The server is the first hop: the outbound proxy when one is set, otherwise the registrar (or the domain). An IP literal picks its own family; IPv4 only and IPv6 only with a host name use that family. Auto with a host name: when only one family has a transport for the account's kind (a bind address, a failed IPv6 transport), that family without a lookup; with DNS SRV in effect (pjsua has a resolver) and no explicit port, IPv4 first, because `getaddrinfo` cannot follow SRV records (pjsua resolves the SRV targets itself, A and AAAA, and skips entries of the other family; when nothing of IPv4 answers, the fallback below moves the account to IPv6); otherwise the first family that `getaddrinfo(host, AF_UNSPEC)` returns (`IPFamilyResolver.system`, with `pj_getaddrinfo`'s hints: no socket type, no flags) and that has a transport. That is the order PJSIP itself tries when it resolves a host name without its DNS resolver; it is not what PJSIP does with DNS SRV on (its own A/AAAA queries), and for an account that does not register the INVITEs go to the dialled URI's host, which may differ from the first hop. Nothing resolved (offline): IPv4, decided again later. Lookups never block the engine queue (`FamilyLookups`): they run on a global queue, at most one per host at a time (every account and trigger that wants that host gets the same answer), answers are cached for 30 s (failures are not), and a network change drops the cache and the lookups still running. A new account whose family depends on a running lookup is added at once, but its first REGISTER waits for the answer (at most `lookupWait`, 2 s; then it registers over what it has, IPv4 for a name that is not resolved yet); the same after `updateAccount` changed the server. A lookup that fails or does not answer never moves an existing account. Tests inject a resolver (`setFamilyResolverForTests`). A host name that lacks the chosen family (IPv6 only, no AAAA) fails to register with a DNS error like any unknown host. - **Contradictions.** IPv4 only with an IPv6 literal server (or IPv6 only with an IPv4 literal) can never register: `addAccount` and `updateAccount` throw `.invalidArgument("server 2001:db8::1 is an IPv6 address but the account is set to IPv4 only")`, and the account editor shows "The server's address is an IPv6 address. Choose Auto or IPv6 only." under Connection with Save and Test off (`IPFamilyPolicy.conflict`, also used by the editor). An IPv4-mapped literal (`[::ffff:a.b.c.d]`) is an IPv6 literal. -- **Decided again** (`refreshAccountFamilies`) for Auto accounts with a host name (not the SRV case) at the start of every network-change round (before `cpjsua_acc_prepare_ip_change`), when IPv6 appears or goes away while no account uses IPv6 (without a round), and before every REGISTER retry (not for a sticky account, see below). A lookup that fails or does not finish keeps the account's family (DNS often fails for a moment during a network change). A changed IP protocol in the editor goes through `updateAccount`, without a restart. -- **Fallback when there is no answer** (`tryOtherFamily`). Auto keeps the system's order for the first REGISTER. When a REGISTER gets no response at all (no `rdata` in `on_reg_state2`: a local timeout, a refused or broken connection, PJSIP_ETPNOTSUITABLE when the host has no address of the bound family), the account moves to the other family and registers at once, if the host name has an address of it (or DNS SRV is in effect: the SRV targets are unknown to the engine, the other family is the only chance); a log line says "no answer over IPv6; trying IPv4". Once per series of failures (`familyFallbackTried`, cleared by the next backoff retry and by a network change), so two silent families alternate at the backoff pace, not in a loop. The family that is moved to stays (`familySticky`) until the next network change: backoff retries do not decide again from the resolver. A server that answers (401, 403, 404, a 408 or 503 it sends itself) is no reason to switch. In 26.3.0 an account bound to IPv4 reached a dual-stack server over IPv4 whatever the order (PJSIP skipped the IPv6 entries with ETPNOTSUITABLE); without this fallback, Auto would have kept retrying the family that does not answer (an Asterisk listening on 0.0.0.0 only, an IPv6 firewall). -- **Moving an account** (`moveAccount`). Never while the account has a call in any state: the call's dialog keeps its peer of the old family, and `pjsua_acc_modify` plus a re-INVITE with `UPDATE_CONTACT` would give it the new family's selector, so in-dialog requests would fail with ETPNOTSUITABLE. The move waits (`pendingMove`, a log line "move to IPv6 ... waits for its calls"); the round keeps the account on its family, and the watchdog tick runs the move once the calls have ended (`runDeferredMoves`), with a REGISTER. A move un-REGISTERs the current binding first (Expires 0 over the old family): `pjsua_acc_modify` with `disable_reg_on_modify` destroys the registration session without one (pjsua_acc.c, `unreg_first`), and a lingering old Contact makes Kamailio fork calls to both, and Asterisk with `max_contacts=1`, `remove_existing=no` refuse the new one with 403, which is never retried. The session is destroyed right after (pjsip_regc_destroy2 with force keeps the request going and drops its callback), and the bridge ignores an un-REGISTER result that arrives in between (`setIgnoringUnregister`). Then: `allow_sdp_nat_rewrite` is set on the live config (`cpjsua_acc_set_sdp_nat_rewrite`: pjsua_acc_modify copies every field we set but this one), the MWI subscription is ended (`cpjsua_acc_end_mwi_after_move`; pjsua subscribes again after the REGISTER) and the presence subscriptions of the account's buddies are made anew (`cpjsua_buddy_resubscribe`), because their dialogs keep the transport selector they were created with (pjsua_pres.c); PUBLISH has no selector (`pjsip_publishc`) and needs nothing. The registrar's requests are trusted again only after it accepted a REGISTER (`setRegistrarSource(nil)`). The same applies to `updateAccount` when the family changes. +- **Decided again** for Auto accounts with a host name (not the SRV case): at every network change (a round, or IPv6 appearing or going away without one) and when a lookup answers (not for a sticky account, see below). Any of these only records the desired family (`AccountEntry.desired`, stamped with the account's `generation`); the reconciler moves the account. `updateAccount`: another server (registrar, proxy or transport) is configured over its own family at once, as there is no binding of this account there to remove (as before for any change of server, the binding at the old server expires there); a changed IP protocol for the same server becomes a desired family (the binding on this server is removed by the move); anything else keeps the family, a family Auto fell back to included, and sends no un-REGISTER (the app calls `updateAccount` with unchanged settings, e.g. when the default account changes). A network change makes every Auto account follow the system again: a family Auto fell back to is forgotten (in the DNS SRV case too: back to IPv4 first), and the lookups are made anew. +- **Fallback when there is no answer** (`registrationRetryNeeded`). Auto keeps the system's order for the first REGISTER. When a REGISTER gets no response at all (no `rdata` in `on_reg_state2`: a local timeout, a refused or broken connection, PJSIP_ETPNOTSUITABLE when the host has no address of the bound family), the account wants the other family at once, if the host name has an address of it (a cached lookup, or one started now) or DNS SRV is in effect (the SRV targets are unknown to the engine, the other family is the only chance); a log line says "no answer over IPv6; trying IPv4". This is recorded also during a round (the round's own REGISTER is reported before the round ends), and the move happens as soon as the round is over, not a backoff later. Once per series of failures (`familyFallbackTried`, cleared by the next backoff retry and by a network change), so two silent families alternate at the backoff pace, not in a loop. The family moved to stays (`familySticky`) until the next network change: lookup answers and unchanged updates do not move it back. A server that answers (401, 403, 404, a 408 or 503 it sends itself) is no reason to switch. The result carries the account's `generation` from the bridge; a result of settings that changed meanwhile is not acted on. In 26.3.0 an account bound to IPv4 reached a dual-stack server over IPv4 whatever the order (PJSIP skipped the IPv6 entries with ETPNOTSUITABLE); without this fallback, Auto would have kept retrying the family that does not answer (an Asterisk listening on 0.0.0.0 only, an IPv6 firewall). +- **Moving an account** (`reconcileFamilies`, on the watchdog tick and right after a desire, a lookup answer, an un-REGISTER answer or the end of a round). A move starts only when no network-change round runs, the account has no call in any state (the call's dialog keeps its peer of the old family, and `pjsua_acc_modify` plus a re-INVITE with `UPDATE_CONTACT` would give it the new family's selector, so in-dialog requests would fail with ETPNOTSUITABLE), no REGISTER of the account is in flight (`cpjsua_acc_reg_busy`, or a request waiting for one) and the desire belongs to the current settings. Then: (1) the old binding is un-REGISTERed (Expires 0 over the old family) and the move waits for the answer, at most `moveUnregisterTimeout` (5 s): `pjsua_acc_modify` with `disable_reg_on_modify` would destroy the registration session without one (pjsua_acc.c, `unreg_first`), and a lingering old Contact makes Kamailio fork calls to both, and Asterisk with `max_contacts=1`, `remove_existing=no` refuse the new one with 403, which is never retried; (2) `pjsua_acc_modify` onto the new family's transport, which destroys the old session (pjsip_regc_destroy2 with force: a late answer of it is dropped), `allow_sdp_nat_rewrite` set on the live config (`cpjsua_acc_set_sdp_nat_rewrite`: pjsua_acc_modify copies every field we set but this one), the MWI subscription ended (`cpjsua_acc_end_mwi_after_move`; pjsua subscribes again after the REGISTER) and the presence subscriptions of the account's buddies made anew (`cpjsua_buddy_resubscribe`), because their dialogs keep the transport selector they were created with (pjsua_pres.c), the registrar trusted again only after it accepted a REGISTER (`setRegistrarSource(nil)`); (3) REGISTER over the new family. The account shows `.registering` from the start of the move until that REGISTER is answered. A failure in (2) keeps the desire, and the next tick tries again; a move whose desire went away meanwhile registers the account where it is. An un-REGISTER answer of an account that should stay registered never shows `.unregistered` (`pjOnRegState2` hands it to the engine instead), so neither a move's nor a late one can make the UI say the account is off while the engine registers it. A round that starts during step (1) aborts the move; it starts again after the round (the round registers the account on its old family first). PUBLISH has no transport selector (`pjsip_publishc`) and needs nothing. Known limitation: subscriptions other phones made to our presence (server side, pjsua_pres.c `pres_on_rx_request`) keep their dialog's transport until they end; a watcher reached only over the old family stops getting NOTIFYs until it subscribes anew. - **Media.** IPv6 accounts set `ipv6_media_use = PJSUA_IPV6_ENABLED_USE_IPV6_ONLY`: `get_media_ip_version` (pjsua_media.c) counts `::1`, link-local and a missing global address as "available" but not "usable", so PREFER_IPV6 would offer IPv4 on loopback and on a Mac without a global IPv6 address. The offer is `c=IN IP6` with IPv6 RTP sockets. An incoming offer is answered in its own family: an `IN IP4` offer to an IPv6 account gets an IPv4 answer and IPv4 RTP (with an IPv6 bind address that socket cannot be bound and the call fails). IPv4 accounts keep pjsua's default (PREFER_IPV4): IPv4 offers, and an `IN IP6` offer is answered with IPv6, as before. `localRTPAddress(of:)` reports the RTP address (diagnostics, tests). - **No STUN over IPv6.** IPv6 accounts have `sip_stun_use` and `media_stun_use` disabled (STUN and TURN over IPv6 are out of scope; pjsua maps IPv4 only) and `allow_sdp_nat_rewrite` on, so after the first REGISTER answer the SDP carries the address the registrar saw (with temporary addresses, the one actually used) instead of `pj_gethostip`'s pick. - **ICE over IPv6** (with a PJSIP patch). pjsua gives an IPv6 call an IPv6 ICE component (`create_ice_media_transport`: `ice_cfg.af = AF_INET6` and a second STUN transport of family IPv6) bound to the string "0" (`IN6_ADDR_ANY`). macOS `getaddrinfo` turns "0" into `::ffff:0.0.0.0`, and binding a V6ONLY socket to that fails ("Failed creating STUN transport #1 for comp 1: Can't assign requested address"): the offer then had IPv4 candidates and `c=IN IP4` only, and an IPv6 answer failed the call (`pjmedia_stream_info_from_sdp`: PJ_EAFNOTSUP). pjsua also ignored the account's bound address for the IPv6 components (only the IPv4 ones use `rtp_cfg.bound_addr`). `scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch` (applied by `build-pjsip.sh`, see scripts/README-build.md) binds the IPv6 STUN and TURN components like the IPv4 ones: to the account's bound address when it is an IPv6 address, else to "::"; and a STUN component bound to a loopback address keeps its host candidate (`loop_addr`), which pjnath leaves out by default. An IPv6 call with ICE now offers `c=IN IP6` with the IPv6 default candidate, IPv6 and IPv4 host candidates (pjsua adds an IPv4 STUN transport as well), and connects. On all interfaces pjnath leaves out `::1` and every link-local address but the default one, so on a Mac without a global IPv6 address the only IPv6 candidate is link-local (`fe80::…`, its zone is not carried in SDP), and between two ICE endpoints its checks fail and ICE nominates an IPv4 pair. With the bind address `::1` the only candidates are `::1` (the IPv4 component cannot bind an IPv6 address and is left out), and two ICE legs negotiate ICE over IPv6 and carry RTP (tested). An IPv6 pair winning over a real network needs a global IPv6 address: not verified. - **Incoming.** Requests over UDP6, TCP6 and TLS6 reach the account bound to that transport: an IPv4 and an IPv6 account with the same user and domain each get the calls and messages of their own family. `SignallingSource` compares IPv6 addresses in any spelling (`[2001:DB8:0::1]` is `2001:db8::1`), so the registrar-source trust (answer-after) works over IPv6. -- **Network changes.** `NetworkPath.address6` is the source address of the default IPv6 route (a UDP socket connected to 2001:db8::1, nothing sent; link-local and loopback do not count). With an account bound to IPv6, a new address starts a round (see "Network resilience"): a primary one (at once, even while an outgoing call rings) when the address those accounts used is no longer assigned to any interface (`NetworkPath.isAssignedLocally`, getifaddrs; IPv6 lost, or replaced and gone), a non-primary one when it is still assigned, as a deprecated temporary address stays for days after a new one takes over (the round waits for a ringing outgoing call like a gateway change; it restarts the listeners and re-REGISTERs, so Contact moves to the new address before the old one expires). Without IPv6 accounts an IPv6 change starts no round at all, so IPv4 accounts and their calls are not disturbed; when IPv6 appears or goes away, Auto host names are decided again (a family Auto fell back to stays) and moved accounts register; a new temporary address alone changes nothing for them. An empty IPv6 lookup keeps the previous address only while it is still assigned, so losing IPv6 is noticed. `pjsua_handle_ip_change` with `restart_listener` restarts every listener, the IPv6 ones included (all `tpdata`), and recomputes their published addresses. -- **Tests.** `EngineIPv6Tests.swift` with `IPv6Stub` (UDP and TCP on `[::1]`, optionally UDP on 127.0.0.1 with the same port; answers REGISTER and INVITE with `IN IP6 ::1`, records family, transport, Via, Contact and bodies; sends INVITE with an IPv6 or IPv4 offer and MESSAGE). Values: old JSON decodes as Auto (unknown values too), literals, first hop, contradictions, the decision with a fake resolver (literals, fixed families, resolver order, offline, availability, SRV), `IPFamilyResolver.system` against `getaddrinfo`, mapping by family and its read-back from `pjsua_acc_config` (transport id, `ipv6_media_use`, STUN, bind address), transport ids, IPv6 registrar-source comparison, `NetworkPath.address6`. pjsua: `bindAddressDecidesTransportFamilies`; `ipv6TransportFailureIsNotFatal` (`[::]:P` held by another socket: the engine starts with IPv4 UDP and TCP6 on P and refuses IPv6 UDP accounts; released, both UDP transports use P); `contradictoryIPProtocolIsRefused` (`.invalidArgument`); `ipv6AccountRegistersOverUDP6` (Via and Contact `[::1]`, the live config, a MESSAGE out over UDP6); `ipv6AccountRegistersOverTCP6`; `ipv6CallOffersIPv6MediaAndCarriesRTP` (`c=IN IP6 ::1`, RTP address `::1`, a loopback call over `[::1]` with RTP both ways); `incomingOverIPv6ReachesTheIPv6Account` (account by family, answers per offer family, MESSAGE); `autoFollowsSystemResolverForHostNames` ("localhost": Auto follows getaddrinfo's first family, IPv4 only and IPv6 only keep theirs); `familyIsDecidedAgainOnNetworkChange` (un-REGISTER over IPv4 before the IPv6 REGISTER, `allow_sdp_nat_rewrite` read back both ways); `ipProtocolChangeMovesTheAccount`; `autoFallsBackToTheOtherFamilyWithoutAnswer` (IPv6 side silent: IPv4 at once; then sticky: a retry stays on IPv4 before moving back); `autoFallsBackWhenTheConnectionIsRefused` (TCP refused over IPv4: TCP6 at once); `autoKeepsTheFamilyWhenTheServerAnswers` (403: no switch); `familyMoveWaitsForTheAccountsCalls`; `subscriptionsFollowAFamilyMove` (MWI and presence SUBSCRIBE anew over IPv6); `familyLookupsAreDedupedAndBounded` (one lookup per host, a slow resolver delays a round and `addAccount` by the limit only, families kept); `ipv6AddressChangesStartRoundsOnlyWhenTheyMatter` (no round without IPv6 accounts; with one, a rotation with the old address assigned waits for a ringing call, a loss runs at once); `networkChangeRestartsIPv6Listeners`; `iceGathersIPv6CandidatesOverIPv6` (ICE on: `c=IN IP6`, IPv6 host candidates including the default one, RTP to a peer without ICE); `iceOverIPv6HonoursTheBindAddress` (bind address `::1`: the only IPv6 candidate is `::1`, and a call between two ICE legs carries RTP over IPv6). In `Engine262Tests.swift`, `privateIPv6ServerAccountIsAdded` now registers over UDP6 with STUN on, and `privateServerAccountDoesNotUseSTUN` sets IPv4 only for its "localhost" account. +- **Network changes.** `NetworkPath.address6` is the source address of the default IPv6 route (a UDP socket connected to 2001:db8::1, nothing sent; link-local and loopback do not count). With an account bound to IPv6, a new address starts a round (see "Network resilience"): a primary one (at once, even while an outgoing call rings) when the address those accounts used is no longer assigned to any interface (`NetworkPath.isAssignedLocally`, getifaddrs; IPv6 lost, or replaced and gone) or the path has no IPv6 route, a non-primary one when it is still assigned, as a deprecated temporary address stays for days after a new one takes over (the round waits for a ringing outgoing call like a gateway change; it restarts the listeners and re-REGISTERs, so Contact moves to the new address before the old one expires). Without IPv6 accounts an IPv6 change starts no round at all, so IPv4 accounts and their calls are not disturbed; when IPv6 appears or goes away, Auto host names are decided again and the reconciler moves the accounts whose family changed (after a round that may be running); a new temporary address alone changes nothing for them. An empty IPv6 lookup keeps the previous address only while the path still routes IPv6 (`NWPath.supportsIPv6`, `NetworkPath.ipv6Route`) and the address is still assigned, so losing IPv6 is noticed, also when the router stops advertising IPv6 while the SLAAC address stays assigned until its lifetime runs out. `pjsua_handle_ip_change` with `restart_listener` restarts every listener, the IPv6 ones included (all `tpdata`), and recomputes their published addresses. +- **Tests.** `EngineIPv6Tests.swift` with `IPv6Stub` (UDP and TCP on `[::1]`, optionally UDP on 127.0.0.1 with the same port; answers REGISTER and INVITE with `IN IP6 ::1`, records family, transport, Via, Contact and bodies; sends INVITE with an IPv6 or IPv4 offer and MESSAGE). Values: old JSON decodes as Auto (unknown values too), literals, first hop, contradictions, the decision with a fake resolver (literals, fixed families, resolver order, offline, availability, SRV), `IPFamilyResolver.system` against `getaddrinfo`, mapping by family and its read-back from `pjsua_acc_config` (transport id, `ipv6_media_use`, STUN, bind address), transport ids, IPv6 registrar-source comparison, `NetworkPath.address6`. pjsua: `bindAddressDecidesTransportFamilies`; `ipv6TransportFailureIsNotFatal` (`[::]:P` held by another socket: the engine starts with IPv4 UDP and TCP6 on P and refuses IPv6 UDP accounts; released, both UDP transports use P); `contradictoryIPProtocolIsRefused` (`.invalidArgument`); `ipv6AccountRegistersOverUDP6` (Via and Contact `[::1]`, the live config, a MESSAGE out over UDP6); `ipv6AccountRegistersOverTCP6`; `ipv6CallOffersIPv6MediaAndCarriesRTP` (`c=IN IP6 ::1`, RTP address `::1`, a loopback call over `[::1]` with RTP both ways); `incomingOverIPv6ReachesTheIPv6Account` (account by family, answers per offer family, MESSAGE); `autoFollowsSystemResolverForHostNames` ("localhost": Auto follows getaddrinfo's first family, IPv4 only and IPv6 only keep theirs); moves are checked as the registrar and the UI see them (`expectMove`: the un-REGISTER over the old family is answered, the REGISTER over the new one follows it, at least the stub's delay of the un-REGISTER answer later, and the account goes `.registering` → `.registered` only after that REGISTER, never `.unregistered` in between): `familyIsDecidedAgainOnNetworkChange` (both ways, `allow_sdp_nat_rewrite` read back); `ipProtocolChangeMovesTheAccount` (and an unchanged update moves nothing); `familyMoveWaitsForTheAccountsCalls`; `ipv6AppearingDuringARoundWaitsForTheRound` (the round ends on its REGISTER, not on its safety timer, then the move); `autoFallsBackToTheOtherFamilyWithoutAnswer` (IPv6 side silent: IPv4 at once; an unchanged update keeps IPv4; a retry stays on IPv4 before moving back); `fallbackAfterARoundMovesWhenTheRoundEnds`; `autoFallsBackWhenTheConnectionIsRefused` (TCP refused over IPv4: TCP6 at once); `autoKeepsTheFamilyWhenTheServerAnswers` (a 503 from the server: retried on IPv6, no switch); `srvFallbackIsUndoneAtANetworkChange` (DNS stub with SRV, A and AAAA); `subscriptionsFollowAFamilyMove` (MWI and presence SUBSCRIBE anew over IPv6); `familyLookupsDoNotBlockTheEngine` (a slow resolver delays neither `addAccount` nor a round, one lookup per host, cached; the first REGISTER waits for the lookup); `ipv6AddressChangesStartRoundsOnlyWhenTheyMatter` (no round without IPv6 accounts; with one, a rotation with the old address assigned waits for a ringing call, a loss runs at once, also with the address assigned but no IPv6 route); `networkChangeRestartsIPv6Listeners`; `iceGathersIPv6CandidatesOverIPv6` (ICE on: `c=IN IP6`, IPv6 host candidates including the default one, RTP to a peer without ICE); `iceOverIPv6HonoursTheBindAddress` (bind address `::1`: the only IPv6 candidate is `::1`, and a call between two ICE legs carries RTP over IPv6). In `Engine262Tests.swift`, `privateIPv6ServerAccountIsAdded` now registers over UDP6 with STUN on, and `privateServerAccountDoesNotUseSTUN` sets IPv4 only for its "localhost" account. - **Only a real network can verify:** a real IPv6 PBX over UDP, TCP and TLS (a certificate for an AAAA name), a dual-stack server by host name, an IPv6-only network, router-advertised and temporary addresses (whether NWPathMonitor reports a new temporary address at all, and the Contact after a rotation), moving between IPv4-only, dual-stack and IPv6-only networks with calls in progress, SRV targets with AAAA records only, IPv6 firewalls without NAT, and RTP through them. ## Deny incoming calls diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index a93c7a7..1f7e7c8 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -77,7 +77,7 @@ App: - Messages are off until switched on in Settings › General ([#8](https://github.com/HSMM/MacroSIP/issues/8)): with the switch off there is no Messages tab, no Send Message item, no notification and no sound, and incoming `MESSAGE` requests are dropped with a log line. - The ringtone chosen in Settings › Audio reaches the engine ([#7](https://github.com/HSMM/MacroSIP/issues/7)): Classic, Digital and Soft are three different melodies, a custom AIFF, M4A or MP3 file is converted to WAV once and reused, a file that cannot be read keeps the previous choice and says why, and the preview plays the real choice at the chosen volume. -`26.3.1` (not released yet): IPv6 ([#11](https://github.com/HSMM/MacroSIP/issues/11)). SIP over UDP, TCP and TLS and the audio over IPv6 next to IPv4, for a server given by an IPv6 address or by a host name with AAAA records; an account at `[2001:db8::1]` no longer retries forever. Account editor › Advanced › IP protocol: Auto (an IP address picks its own protocol, a host name follows the order macOS returns and falls back to the other protocol at once when the server does not answer; decided again after a network change, never during a call), IPv4 only, IPv6 only. IPv6 accounts use no STUN; ICE gathers IPv6 candidates with a PJSIP patch (pjsua bound its IPv6 ICE socket to "0", which macOS cannot bind; `scripts/pjsip-patches/`). Tested on loopback only; a real IPv6 PBX and network are not verified. +`26.3.1` (not released yet): IPv6 ([#11](https://github.com/HSMM/MacroSIP/issues/11)). SIP over UDP, TCP and TLS and the audio over IPv6 next to IPv4, for a server given by an IPv6 address or by a host name with AAAA records; an account at `[2001:db8::1]` no longer retries forever. Account editor › Advanced › IP protocol: Auto (an IP address picks its own protocol, a host name follows the order macOS returns and falls back to the other protocol at once when the server does not answer; decided again after a network change; the move removes the old registration first and never happens during a call), IPv4 only, IPv6 only. IPv6 accounts use no STUN; ICE gathers IPv6 candidates with a PJSIP patch (pjsua bound its IPv6 ICE socket to "0", which macOS cannot bind; `scripts/pjsip-patches/`). Tested on loopback only; a real IPv6 PBX and network are not verified. ## Later diff --git a/docs/adr/0014-ipv6-dual-stack.md b/docs/adr/0014-ipv6-dual-stack.md index fc11d56..d0ee941 100644 --- a/docs/adr/0014-ipv6-dual-stack.md +++ b/docs/adr/0014-ipv6-dual-stack.md @@ -29,21 +29,28 @@ loses the choice between the verifying and the non-verifying TLS listener (miles account that does not register sends its INVITEs to the dialled host, so it is the system's order, not always PJSIP's. With DNS SRV in effect and no explicit port the name cannot be asked that way, so Auto starts with IPv4 there; a host name that does not resolve (offline) also gives IPv4. Lookups - run concurrently off the engine queue, each host once, with one bounded wait (2 s); a host not - resolved in time keeps the account's family. + never block the engine: they run off its queue, one per host at a time, with a short cache; a new + account's first REGISTER waits for its lookup (2 s at most), and a lookup that fails or is late + never moves an existing account. - **Auto falls back.** The system order is only the first attempt: a REGISTER that gets no answer at - all (timeout, refused or broken connection, no address of the bound family) moves the account to + all (timeout, refused or broken connection, no address of the bound family) makes the account want the other family at once when the host has an address of it (or DNS SRV makes the other family the - only chance), and that family then stays until the next network change. A server that answers + only chance), also when it happens during a network-change round (the move follows the round), and + that family then stays until the next network change, through retries and unchanged updates. A server that answers (401, 403, its own 503) is not a reason to switch. Without this, a dual-stack name whose server does not answer over the first family (Asterisk listening on 0.0.0.0 only, an IPv6 firewall) would retry forever where 26.3.0 registered over IPv4. -- **Decided again** at every network change, when IPv6 comes or goes, and before REGISTER retries - (not after a fallback). An account whose family changed is moved: its old binding is - un-REGISTERed first (a lingering Contact forks calls or makes a `max_contacts=1` server refuse the - new one), its subscriptions are made anew on the new transport, and it registers there. **Never - while the account has a call**: the call's dialog would keep a peer of the old family on a - transport of the new one; the move waits for the calls to end. +- **Decided again** at every network change, when IPv6 comes or goes, and when a lookup answers + (not after a fallback). **One reconciler does every move**: the triggers only + record a desired family for the account's current settings (a generation number), and the + reconciler moves the account when nothing can be hurt by it: no network-change round running, + **no call on the account in any state** (the call's dialog would keep a peer of the old family on a + transport of the new one), no REGISTER of it in flight. A move un-REGISTERs the old binding and + waits for the answer (5 s at most: a lingering Contact forks calls or makes a `max_contacts=1` + server refuse the new one with 403), then moves the account to the other transport, makes its + subscriptions anew there and registers; the account shows "registering" throughout, and a failed + step is tried again on the next tick. Moving from several places at once had raced with rounds, + REGISTERs in flight and late answers. - **IPv6 address changes** count only for accounts that use IPv6. A new temporary address while the old one is still assigned is a non-primary change (it waits for a ringing outgoing call); losing the address is primary. Without IPv6 accounts IPv6 coming, going or rotating starts no round, so From de0ef196cf185ae845ca0b1aadc8168b0e4fb278 Mon Sep 17 00:00:00 2001 From: HSMM Date: Mon, 9 Nov 2026 18:09:31 +0300 Subject: [PATCH 09/12] Drop line-ending noise from the IPv6 ICE PJSIP patch --- .../0001-ipv6-ice-bind-any.patch | 46 ------------------- 1 file changed, 46 deletions(-) diff --git a/scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch b/scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch index f213079..726210a 100644 --- a/scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch +++ b/scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch @@ -19,33 +19,6 @@ MacroSIP: applied by scripts/build-pjsip.sh (ADR 0014). --- a/pjsip/src/pjsua-lib/pjsua_media.c +++ b/pjsip/src/pjsua-lib/pjsua_media.c -@@ -33,16 +33,16 @@ - - static void stop_media_stream(pjsua_call *call, unsigned med_idx); - --char *pjsua_get_basename(const char* path, unsigned len) --{ -- char* p = ((char*)path) + len; -- -- if (len == 0) -- return p; -- -- for (--p; p != path && *p != '/' && *p != '\\'; ) --p; -- -- return (p == path) ? p : p + 1; -+char *pjsua_get_basename(const char* path, unsigned len) -+{ -+ char* p = ((char*)path) + len; -+ -+ if (len == 0) -+ return p; -+ -+ for (--p; p != path && *p != '/' && *p != '\\'; ) --p; -+ -+ return (p == path) ? p : p + 1; - } - - static void pjsua_media_config_dup(pj_pool_t *pool, @@ -1230,7 +1230,11 @@ } @@ -97,22 +70,3 @@ MacroSIP: applied by scripts/build-pjsip.sh (ADR 0014). (pj_uint16_t)cfg->port); ice_cfg.turn_tp[i].cfg.port_range = (pj_uint16_t)cfg->port_range; if (cfg->port != 0 && ice_cfg.turn_tp[i].cfg.port_range == 0) -@@ -1977,12 +1991,12 @@ - goto on_return; - } - -- /* Check if media is deinitializing */ -- if (call_med->call->async_call.med_ch_deinit || !call_med->tp) { -- status = PJ_ECANCELLED; -- goto on_return; -- } -- -+ /* Check if media is deinitializing */ -+ if (call_med->call->async_call.med_ch_deinit || !call_med->tp) { -+ status = PJ_ECANCELLED; -+ goto on_return; -+ } -+ - pjmedia_transport_simulate_lost(call_med->tp, PJMEDIA_DIR_ENCODING, - pjsua_var.media_cfg.tx_drop_pct); - From ad00808bc88e022b9fe1dac991d1f97054076e9c Mon Sep 17 00:00:00 2001 From: HSMM Date: Mon, 9 Nov 2026 18:11:13 +0300 Subject: [PATCH 10/12] IPv6: moves keep the old binding, refuse missing transports and survive dropped sessions --- Sources/CPJSUA/include/CPJSUA.h | 8 + Sources/CPJSUA/shim.c | 26 +++ .../MacroSIPCore/Engine/Engine+Accounts.swift | 18 +- .../MacroSIPCore/Engine/Engine+Families.swift | 61 +++-- Sources/MacroSIPCore/Engine/IPFamily.swift | 9 +- Tests/MacroSIPCoreTests/EngineIPv6Tests.swift | 217 ++++++++++++++++++ docs/ENGINE.md | 8 +- docs/adr/0014-ipv6-dual-stack.md | 11 +- 8 files changed, 325 insertions(+), 33 deletions(-) diff --git a/Sources/CPJSUA/include/CPJSUA.h b/Sources/CPJSUA/include/CPJSUA.h index e1c5c71..e60939f 100644 --- a/Sources/CPJSUA/include/CPJSUA.h +++ b/Sources/CPJSUA/include/CPJSUA.h @@ -475,6 +475,14 @@ void cpjsua_acc_prepare_ip_change(pjsua_acc_id acc_id, int register_it); * not a configurable macro): the engine creates at most this many transports. */ unsigned cpjsua_transport_slots(void); +/** 1 when the registrar holds a binding of the account as PJSIP knows it: a registration session + * exists and its last REGISTER was answered 2xx (pjsua destroys the session after a failure and + * after a successful un-REGISTER). */ +int cpjsua_acc_has_binding(pjsua_acc_id acc_id); + +/** 1 while the account has a registration session (pjsua_acc_modify drops it for some changes). */ +int cpjsua_acc_has_regc(pjsua_acc_id acc_id); + /** 1 while the account's registration session has a REGISTER (or un-REGISTER) transaction in flight. */ int cpjsua_acc_reg_busy(pjsua_acc_id acc_id); diff --git a/Sources/CPJSUA/shim.c b/Sources/CPJSUA/shim.c index fe5d74a..f52d5f1 100644 --- a/Sources/CPJSUA/shim.c +++ b/Sources/CPJSUA/shim.c @@ -1640,6 +1640,32 @@ unsigned cpjsua_transport_slots(void) return (unsigned)PJ_ARRAY_SIZE(pjsua_var.tpdata); } +int cpjsua_acc_has_binding(pjsua_acc_id acc_id) +{ + int bound = 0; + if (acc_id < 0 || acc_id >= (int)PJ_ARRAY_SIZE(pjsua_var.acc)) + return 0; + PJSUA_LOCK(); + if (pjsua_var.acc[acc_id].valid && pjsua_var.acc[acc_id].regc && + pjsua_var.acc[acc_id].reg_last_code / 100 == 2) + { + bound = 1; + } + PJSUA_UNLOCK(); + return bound; +} + +int cpjsua_acc_has_regc(pjsua_acc_id acc_id) +{ + int has; + if (acc_id < 0 || acc_id >= (int)PJ_ARRAY_SIZE(pjsua_var.acc)) + return 0; + PJSUA_LOCK(); + has = pjsua_var.acc[acc_id].valid && pjsua_var.acc[acc_id].regc != NULL; + PJSUA_UNLOCK(); + return has; +} + int cpjsua_acc_reg_busy(pjsua_acc_id acc_id) { pjsip_regc_info info; diff --git a/Sources/MacroSIPCore/Engine/Engine+Accounts.swift b/Sources/MacroSIPCore/Engine/Engine+Accounts.swift index b05c105..6d4ae0c 100644 --- a/Sources/MacroSIPCore/Engine/Engine+Accounts.swift +++ b/Sources/MacroSIPCore/Engine/Engine+Accounts.swift @@ -52,7 +52,8 @@ extension Engine { /// IP family (docs/ENGINE.md "IPv6"): another server is configured over its own family at once (no /// binding of this account there to remove); a changed IP protocol for the same server becomes a /// desired family that `reconcileFamilies` moves the account to; anything else keeps the family, - /// including one Auto fell back to. + /// including one Auto fell back to. A family without a transport for the account's kind throws + /// `.transportUnavailable`. public func updateAccount(_ cfg: AccountConfig, password: String?) throws { try requireStarted() guard var entry = accounts[cfg.id] else { throw EngineError.unknownAccount(cfg.id) } @@ -69,6 +70,9 @@ extension Engine { entry.familyFallbackTried = false entry.fallbackWaitsForLookup = false let decided = try decideFamily(cfg, provisional: serverChanged ? nil : entry.family) + guard transports.id(for: cfg, family: decided.family) != nil else { + throw EngineError.transportUnavailable(cfg.transport, ipv6: decided.family == .ipv6) + } lookupStarted = decided.lookupStarted if serverChanged && !accountHasCalls(entry.index) { family = decided.family @@ -85,6 +89,8 @@ extension Engine { // New settings start a new series of attempts. cancelRegistrationRetry(cfg.id) bridge.resetRetryAttempts(cfg.id) + // The registrar holds a binding on this server (a move must un-REGISTER it). + let hadBinding = !serverChanged && hasBinding(entry) entry.wantsRegistration = cfg.registers accounts[cfg.id]?.wantsRegistration = cfg.registers bridge.setWantsRegistration(entry.index, cfg.registers) @@ -101,6 +107,8 @@ extension Engine { try PJ.check(pjsua_acc_modify(entry.index, p), "pjsua_acc_modify") } cpjsua_acc_set_sdp_nat_rewrite(entry.index, settings.sdpNATRewrite ? 1 : 0) // not copied by modify + // New credentials (among others) make pjsua drop the registration session without un-REGISTER. + let sessionDropped = dropPendingIfSessionGone(entry) if familyChanged { cpjsua_acc_end_mwi_after_move(entry.index) } if cfg.isDefaultOutgoing { PJ.warn(pjsua_acc_set_default(entry.index), "set default account") @@ -128,9 +136,13 @@ extension Engine { if familyChanged { resubscribePresence(accountIndex: entry.index) } refreshPresenceSubscriptions(accountIndex: entry.index) guard cfg.registers else { return } - if lookupStarted { + if hadBinding && sessionDropped { + // The binding is still at the registrar: renew it where the account is, so a move can + // un-REGISTER it before it registers on the other family. + try applyRegistration(cfg.id, true) + } else if lookupStarted { accounts[cfg.id]?.registerDeadline = .now + Engine.lookupWait - bridge.setRegistration(cfg.id, .registering) + if !hasBinding(entry) { bridge.setRegistration(cfg.id, .registering) } } else if entry.desired != nil && !accountHasCalls(entry.index) { // The reconciler un-REGISTERs the binding on this family and registers on the other one. reconcileFamilies() diff --git a/Sources/MacroSIPCore/Engine/Engine+Families.swift b/Sources/MacroSIPCore/Engine/Engine+Families.swift index f65e5c9..ed7215a 100644 --- a/Sources/MacroSIPCore/Engine/Engine+Families.swift +++ b/Sources/MacroSIPCore/Engine/Engine+Families.swift @@ -58,15 +58,16 @@ extension Engine { /// A lookup of `host` off the engine queue (one in flight per host); the answer comes back through /// `familiesResolved`. func startLookup(_ host: String) { - familyLookups.start(host, resolve: resolveFamilies) { [weak self] host, families in - Task { await self?.familiesResolved(host, families) } + familyLookups.start(host, resolve: resolveFamilies) { [weak self] host, families, epoch in + Task { await self?.familiesResolved(host, families, epoch: epoch) } } } /// A lookup answered: accounts of that host that wait for it record what it means (a desired family, /// or the fallback it allows), and the reconciler runs. A failed lookup ([]) changes no family. - func familiesResolved(_ host: String, _ families: [IPFamily]) { - guard isStarted, PJ.registerThread() else { return } + func familiesResolved(_ host: String, _ families: [IPFamily], epoch: UInt64) { + // An answer from before a network change, delivered after it, no longer holds. + guard isStarted, PJ.registerThread(), epoch == familyLookups.epoch else { return } let srv = srvInEffect for id in Array(accounts.keys) { guard var entry = accounts[id], IPFamilyPolicy.firstHop(of: entry.config).host == host else { continue } @@ -91,7 +92,8 @@ extension Engine { /// A network change (a round, or IPv6 coming or going): earlier answers no longer hold. Lookups are /// dropped and made again, and every Auto account follows the system's order again: a family Auto /// fell back to is forgotten, also in the DNS SRV case (back to IPv4 first). `abortMoves`: a round - /// re-registers every account, so a move whose un-REGISTER was sent starts again after it. + /// re-registers every account, so a move whose un-REGISTER was sent starts again after it; without + /// a round such a move finishes with its desire (a later answer may move the account back). func familiesNetworkChanged(abortMoves: Bool) { familyLookups.invalidate() let srv = srvInEffect @@ -106,10 +108,11 @@ extension Engine { let wasSticky = entry.familySticky entry.familySticky = false let hop = IPFamilyPolicy.firstHop(of: entry.config) + let moving = entry.moveUnregisterSent != nil if IPFamilyPolicy.followsResolver(entry.config, srv: srv) { - entry.desired = nil // the new lookup decides + if !moving { entry.desired = nil } // the new lookup decides startLookup(hop.host) - } else if wasSticky { + } else if wasSticky, !moving { // The SRV case: the order is IPv4 first, whatever Auto fell back to. let decided = IPFamilyPolicy.decide(entry.config, available: transports.families(for: entry.config), srv: srv) { _ in [] } @@ -173,7 +176,8 @@ extension Engine { continue } if let deadline = entry.registerDeadline, now < deadline { continue } - if let desired = entry.desired, desired.generation == entry.generation, desired.family != entry.family { + if let desired = entry.desired, desired.generation == entry.generation, desired.family != entry.family, + transports.id(for: entry.config, family: desired.family) != nil { if !accountHasCalls(entry.index), !registrationBusy(entry) { startMove(id) continue @@ -182,9 +186,10 @@ extension Engine { accounts[id]?.desired = nil } if entry.registerDeadline != nil { - // No (usable) answer in time, or the move has to wait: register where the account is. + // No (usable) answer in time, or the move has to wait: register where the account is, + // unless it is registered there already (or a REGISTER is on its way, e.g. a round's). accounts[id]?.registerDeadline = nil - if entry.wantsRegistration { register(id) } + if entry.wantsRegistration, !hasBinding(entry), !registrationBusy(entry) { register(id) } } } } @@ -198,7 +203,7 @@ extension Engine { guard let entry = accounts[id], let desired = entry.desired else { return } cancelRegistrationRetry(id) accounts[id]?.registerDeadline = nil - guard hasBinding(id) else { + guard hasBinding(entry) else { finishMove(id) return } @@ -228,8 +233,9 @@ extension Engine { /// registration session is destroyed with `pjsua_acc_modify` (a late answer of it is dropped), the /// live config gets `allow_sdp_nat_rewrite` (pjsua_acc_modify does not copy it), the MWI and /// presence subscriptions are made anew on the new transport (their dialogs keep the old one), and - /// the account registers. A failure keeps the desire: the next tick tries again. A move that is no - /// longer wanted registers the account where it is. + /// the account registers. A move that is no longer wanted, or that a call started meanwhile now + /// stops (the desire waits for the calls), registers the account where it is; so does a failure, + /// which drops the desire until the next trigger. private func finishMove(_ id: AccountID) { guard var entry = accounts[id] else { return } entry.moveUnregisterSent = nil @@ -240,6 +246,11 @@ extension Engine { if entry.wantsRegistration { register(id) } return } + if accountHasCalls(entry.index) { + accounts[id] = entry + if entry.wantsRegistration { register(id) } + return + } do { let settings = try accountSettings(entry.config, password: entry.password, family: desired.family) try AccountMapping.withPJConfig(settings) { p in @@ -248,10 +259,14 @@ extension Engine { } cpjsua_acc_set_sdp_nat_rewrite(entry.index, settings.sdpNATRewrite ? 1 : 0) } catch { - PJ.warn(error, "account \(entry.config.uri): move to \(desired.family)") + emit(.log(level: 2, "engine: account \(entry.config.uri): cannot move to \(desired.family) (\(error)); " + + "stays on \(entry.family)")) + entry.desired = nil accounts[id] = entry + if entry.wantsRegistration { register(id) } return } + dropPendingIfSessionGone(entry) cpjsua_acc_end_mwi_after_move(entry.index) emit(.log(level: 3, "engine: account \(entry.config.uri): server now reached over \(desired.family) " + "(was \(entry.family), \(desired.reason))")) @@ -273,10 +288,20 @@ extension Engine { // MARK: - helpers - /// The registrar holds a binding of the account (last REGISTER answered 2xx). - func hasBinding(_ id: AccountID) -> Bool { - if case .registered = bridge.registration(of: id) { return true } - return false + /// The registrar holds a binding of the account, as PJSIP knows it: a registration session whose + /// last REGISTER was answered 2xx (not the UI state, which shows intents too). + func hasBinding(_ entry: AccountEntry) -> Bool { + cpjsua_acc_has_binding(entry.index) != 0 + } + + /// After `pjsua_acc_modify`: when it dropped the registration session, a request that waited for that + /// session's REGISTER (PJSIP_EBUSY) would wait forever (the late answer is dropped); it is cleared. + /// True when the session is gone. + @discardableResult + func dropPendingIfSessionGone(_ entry: AccountEntry) -> Bool { + guard cpjsua_acc_has_regc(entry.index) == 0 else { return false } + _ = bridge.takePendingRegistration(entry.config.id) + return true } /// The account has a call in any state (ringing, connecting, connected, held). diff --git a/Sources/MacroSIPCore/Engine/IPFamily.swift b/Sources/MacroSIPCore/Engine/IPFamily.swift index 80c74cd..930c0ca 100644 --- a/Sources/MacroSIPCore/Engine/IPFamily.swift +++ b/Sources/MacroSIPCore/Engine/IPFamily.swift @@ -157,6 +157,9 @@ final class FamilyLookups: Sendable { } } + /// The lookups' generation: `invalidate()` starts a new one. + var epoch: UInt64 { state.withLock { $0.epoch } } + func invalidate() { state.withLock { st in st.cache = [:] @@ -166,9 +169,9 @@ final class FamilyLookups: Sendable { } /// Starts a lookup of `host` on a global queue unless one is running; `done` gets its answer ([] - /// when it failed), unless an `invalidate()` came in between. + /// when it failed) and the epoch it was started in, unless an `invalidate()` came in between. func start(_ host: String, resolve: @escaping @Sendable (String) -> [IPFamily], - done: @escaping @Sendable (String, [IPFamily]) -> Void) { + done: @escaping @Sendable (String, [IPFamily], UInt64) -> Void) { let epoch: UInt64? = state.withLock { st in guard !host.isEmpty, !st.inFlight.contains(host) else { return nil } st.inFlight.insert(host) @@ -183,7 +186,7 @@ final class FamilyLookups: Sendable { if !families.isEmpty { st.cache[host] = (families, .now) } return true } - if current { done(host, families) } + if current { done(host, families, epoch) } } } } diff --git a/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift b/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift index 99b732a..ed6f119 100644 --- a/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift +++ b/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift @@ -1300,6 +1300,223 @@ extension EngineTests { await engine.stop() } + /// An account that is registered and switched from a fixed protocol to Auto: the host is not + /// cached, so the family waits for the lookup. The account stays `.registered` meanwhile (nothing + /// changed for the registrar yet), and when the lookup says IPv6 the move un-REGISTERs the IPv4 + /// binding first, which the registration session still holds. The same with a password change at + /// the same time, which makes pjsua drop that session: the account registers again over IPv4 at + /// once, and the move removes that binding before it registers over IPv6. + @Test(arguments: [false, true]) + func switchToAutoRemovesTheOldBinding(newPassword: Bool) async throws { + let stub = try IPv6Stub(dualStack: true) + defer { stub.stop() } + let answer = OSAllocatedUnfairLock(initialState: [IPFamily.ipv6, .ipv4]) + let slow = OSAllocatedUnfairLock(initialState: 0.0) + let engine = await makeEngine(bindAddress: nil) + let log = TimedEventLog() + let consumer = log.consume(engine) + defer { consumer.cancel() } + await engine.setTestTimings(transactionTimeoutMs: 2000) + await engine.setFamilyResolverForTests { _ in + Thread.sleep(forTimeInterval: slow.withLock { $0 }) + return answer.withLock { $0 } + } + try await engine.start(network: Self.network) + var account = AccountConfig(displayName: "L", username: "1011", domain: "localhost:\(stub.port)", mwi: false, + ipProtocol: .ipv4) + try await engine.addAccount(account, password: "pw") + #expect(await waitUntil { await self.registered(engine, account.id, over: .ipv4) }) + + slow.withLock { $0 = 0.5 } + account.ipProtocol = .auto + let since = Date() + try await engine.updateAccount(account, password: newPassword ? "pw2" : nil) + if !newPassword { + #expect(await engine.registrationState(of: account.id).isRegistered) // not "registering" + } + #expect(await waitUntil(timeout: 6) { await self.registered(engine, account.id, over: .ipv6) }) + var moveSince = since + if newPassword { + let renewed = stub.registers.first { !$0.unregister && $0.family == .ipv4 && $0.at >= since } + #expect(renewed != nil, "the IPv4 binding is renewed with the new password first") + moveSince = renewed?.at ?? since + } + expectMove(stub, log, account.id, from: .ipv4, to: .ipv6, since: moveSince) + await engine.stop() + } + + /// The same switch to Auto, when the lookup keeps the family: nothing goes to the registrar (the + /// binding is there) and the account shows `.registered` throughout. + @Test func switchToAutoOnTheSameFamilySendsNothing() async throws { + let stub = try IPv6Stub(dualStack: true) + defer { stub.stop() } + let engine = await makeEngine(bindAddress: nil) + let log = TimedEventLog() + let consumer = log.consume(engine) + defer { consumer.cancel() } + await engine.setFamilyResolverForTests { _ in + Thread.sleep(forTimeInterval: 0.3) + return [.ipv4, .ipv6] + } + try await engine.start(network: Self.network) + var account = AccountConfig(displayName: "L", username: "1014", domain: "localhost:\(stub.port)", mwi: false, + ipProtocol: .ipv4) + try await engine.addAccount(account, password: "pw") + #expect(await waitUntil { await self.registered(engine, account.id, over: .ipv4) }) + account.ipProtocol = .auto + let since = Date() + try await engine.updateAccount(account, password: nil) + try await Task.sleep(for: .milliseconds(1500)) + #expect(stub.registers.filter { $0.at >= since }.isEmpty, "\(stub.registers.filter { $0.at >= since }.map { "\($0.family) \($0.unregister)" })") + #expect(log.registrations(account.id).filter { $0.0 >= since }.allSatisfy { if case .registered = $0.1 { return true }; return false }) + #expect(await self.registered(engine, account.id, over: .ipv4)) + await engine.stop() + } + + /// A family without a transport for the account's kind is refused by `updateAccount`, as before the + /// reconciler: here the IPv6 UDP port is taken by another socket. + @Test func ipv6OnlyWithoutAnIPv6TransportIsRefused() async throws { + let stub = try IPv6Stub(dualStack: true) + defer { stub.stop() } + let blocker = socket(AF_INET6, SOCK_DGRAM, 0) + var one: Int32 = 1 + setsockopt(blocker, IPPROTO_IPV6, IPV6_V6ONLY, &one, socklen_t(MemoryLayout.size)) + var addr = sockaddr_in6() + addr.sin6_len = UInt8(MemoryLayout.size) + addr.sin6_family = sa_family_t(AF_INET6) + addr.sin6_addr = in6addr_any + var len = socklen_t(MemoryLayout.size) + _ = withUnsafeMutablePointer(to: &addr) { + $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(blocker, $0, len) == 0 && getsockname(blocker, $0, &len) == 0 } + } + defer { close(blocker) } + var net = Self.network + net.localPort = UInt16(bigEndian: addr.sin6_port) + let engine = await makeEngine(bindAddress: nil) + try await engine.start(network: net) + #expect(await engine.transportIDsForTests().udp6 == nil) + var account = AccountConfig(displayName: "L", username: "1012", domain: "localhost:\(stub.port)", mwi: false, + ipProtocol: .ipv4) + try await engine.addAccount(account, password: "pw") + #expect(await waitUntil { await engine.registrationState(of: account.id).isRegistered }) + account.ipProtocol = .ipv6 + await #expect(throws: EngineError.transportUnavailable(.udp, ipv6: true)) { + try await engine.updateAccount(account, password: nil) + } + try await Task.sleep(for: .milliseconds(1500)) + #expect(await engine.registrationState(of: account.id).isRegistered) + #expect(stub.registers.allSatisfy { !$0.unregister }) + await engine.stop() + } + + /// A REGISTER requested while another is in flight waits for it (PJSIP_EBUSY); when an update drops + /// that busy session (new credentials), nothing is left waiting: the account still moves to its new + /// family. + @Test func updateDroppingABusySessionDoesNotBlockTheMove() async throws { + let stub = try IPv6Stub(dualStack: true) + defer { stub.stop() } + stub.silentFamilies = [.ipv4] + let engine = await makeEngine(bindAddress: nil) + await engine.setTestTimings(transactionTimeoutMs: 2000) + try await engine.start(network: Self.network) + var account = AccountConfig(displayName: "L", username: "1013", domain: "localhost:\(stub.port)", mwi: false, + ipProtocol: .ipv4) + try await engine.addAccount(account, password: "pw") // REGISTER in flight, no answer + #expect(await waitUntil { stub.registers.contains { $0.family == .ipv4 } }) + try await engine.setRegistered(account.id, true) // EBUSY: waits for it + account.ipProtocol = .ipv6 + try await engine.updateAccount(account, password: "other") // pjsua drops the busy session + #expect(await waitUntil(timeout: 6) { await self.registered(engine, account.id, over: .ipv6) }) + await engine.stop() + } + + /// A call that starts while a move waits for its un-REGISTER answer stops the move: the account + /// registers again over its family, and moves once the call has ended. + @Test func callDuringTheMoveWaitKeepsTheFamily() async throws { + let stub = try IPv6Stub(dualStack: true) + defer { stub.stop() } + let answer = OSAllocatedUnfairLock(initialState: [IPFamily.ipv4, .ipv6]) + let (engine, account, log, consumer) = try await startAutoLocalhost(stub, answer: answer) + defer { consumer.cancel() } + #expect(await waitUntil { await engine.registrationState(of: account.id).isRegistered }) + stub.unregisterDelay = 1.0 + var six = account + six.ipProtocol = .ipv6 + try await engine.updateAccount(six, password: nil) + #expect(await waitUntil { stub.registers.contains { $0.unregister && $0.family == .ipv4 } }) + let call = try await engine.makeCall(to: DialString(uri: "sip:300@localhost:\(stub.port)", display: "300"), from: account.id) + #expect(await waitUntil { await engine.calls().first { $0.id == call }?.state == .connected }) + try await Task.sleep(for: .milliseconds(1500)) // the un-REGISTER was answered meanwhile + #expect(await engine.accountFamilyForTests(account.id) == .ipv4) + #expect(await waitUntil { await self.registered(engine, account.id, over: .ipv4) }) + #expect(await engine.calls().first { $0.id == call }?.state == .connected) + + stub.unregisterDelay = 0 + let since = Date() + try await engine.hangup(call) + #expect(await waitUntil { await engine.calls().isEmpty }) + #expect(await waitUntil(timeout: 4) { await self.registered(engine, account.id, over: .ipv6) }) + expectMove(stub, log, account.id, from: .ipv4, to: .ipv6, since: since) + await engine.stop() + } + + /// A lookup answer from before a network change is not acted on, also when it reaches the engine + /// after the change. + @Test func lookupAnswerFromBeforeANetworkChangeIsDropped() async throws { + let stub = try IPv6Stub(dualStack: true) + defer { stub.stop() } + let answer = OSAllocatedUnfairLock(initialState: [IPFamily.ipv4, .ipv6]) + let (engine, account, _, consumer) = try await startAutoLocalhost(stub, answer: answer) + defer { consumer.cancel() } + #expect(await waitUntil { await engine.registrationState(of: account.id).isRegistered }) + let before = await engine.familyLookups.epoch + await engine.simulateNetworkChange() + #expect(await waitUntil { await engine.ipChangeStateForTests().running == nil }) + await engine.familiesResolved("localhost", [.ipv6, .ipv4], epoch: before) + try await Task.sleep(for: .milliseconds(700)) + #expect(await engine.accountFamilyForTests(account.id) == .ipv4) + await engine.stop() + } + + /// IPv6 coming or going while a move waits for its un-REGISTER answer lets the move finish (its + /// desire is kept until the new lookup answers): one un-REGISTER over IPv4, and no REGISTER over IPv4 + /// in between, although the new lookup answers only after the move. + @Test func ipv6ChangeDuringAMoveLetsItFinish() async throws { + let stub = try IPv6Stub(dualStack: true) + defer { stub.stop() } + let answer = OSAllocatedUnfairLock(initialState: [IPFamily.ipv4, .ipv6]) + let slow = OSAllocatedUnfairLock(initialState: 0.0) + let (engine, account, log, consumer) = try await startAutoLocalhost(stub, answer: answer) + defer { consumer.cancel() } + await engine.setFamilyResolverForTests { _ in + Thread.sleep(forTimeInterval: slow.withLock { $0 }) + return answer.withLock { $0 } + } + await engine.setIPv6AddressAssignedForTests { $0 == "2001:db8::10" } + func path(_ v6: String) -> NetworkPath { + NetworkPath(satisfied: true, interface: "en0", address: "192.168.1.20", address6: v6, gateway: "192.168.1.1") + } + await engine.applyPathForTests(path("")) + #expect(await waitUntil { await engine.ipChangeStateForTests().running == nil }) + #expect(await waitUntil { await self.registered(engine, account.id, over: .ipv4) }) + stub.unregisterDelay = 1.0 + answer.withLock { $0 = [.ipv6, .ipv4] } + let since = Date() + await engine.applyPathForTests(path("2001:db8::10")) // IPv6 appeared: IPv6 first now + #expect(await waitUntil { stub.registers.contains { $0.unregister && $0.family == .ipv4 && $0.at >= since } }) + slow.withLock { $0 = 1.5 } + await engine.applyPathForTests(NetworkPath(satisfied: true, interface: "en0", address: "192.168.1.20", + gateway: "192.168.1.1", ipv6Route: false)) // gone, during the move + #expect(await waitUntil(timeout: 6) { await self.registered(engine, account.id, over: .ipv6) }) + try await Task.sleep(for: .milliseconds(1200)) // the second lookup has answered + #expect(await self.registered(engine, account.id, over: .ipv6)) + let after = stub.registers.filter { $0.at >= since } + #expect(after.filter { $0.unregister }.count == 1, "\(after.map { "\($0.family) \($0.unregister)" })") + #expect(!after.contains { !$0.unregister && $0.family == .ipv4 }, "\(after.map { "\($0.family) \($0.unregister)" })") + expectMove(stub, log, account.id, from: .ipv4, to: .ipv6, since: since, lag: 0.9) + await engine.stop() + } + /// IPv6 address changes (pure rules through injected paths): IPv6 appearing or a new address /// without IPv6 accounts starts no round; with an IPv6 account a new temporary address whose /// predecessor is still assigned is a non-primary change (it waits for a ringing outgoing call), diff --git a/docs/ENGINE.md b/docs/ENGINE.md index 6f4bca9..70c6aa2 100644 --- a/docs/ENGINE.md +++ b/docs/ENGINE.md @@ -382,17 +382,17 @@ Dual stack since 26.3.1 ([#11](https://github.com/HSMM/MacroSIP/issues/11), ADR - **Transports.** Every transport has an IPv6 twin: UDP6, TCP6, TLS6 verifying and TLS6 non-verifying (`TransportIDs.udp6`, `tcp6`, `tls6`, `tls6NoVerify`). pjlib sets `IPV6_V6ONLY` on every IPv6 socket (`PJ_SOCK_HAS_IPV6_V6ONLY` is 1 in our build, `pj_sock_socket`), so `[::]:P` and `0.0.0.0:P` coexist and both families listen on the configured `localPort` (TLS on a random port, as before; with port 0 each family gets its own random port). The IPv4 UDP transport is required as before; the IPv6 ones are best effort: a failure is logged ("UDP over IPv6 transport on port P: ...") and only the accounts that would need that transport are refused (`EngineError.transportUnavailable(kind, ipv6: true)`). Without a global IPv6 address pjsua publishes the UDP6 transport with a link-local or loopback address (`pj_gethostip`), which only a server on the same link or on loopback can use. `localPort(of:family:)` reports the ports; `localPort(of:)` stays IPv4. pjsua keeps transports in a fixed table of 8 (`pjsua_var.tpdata[8]` in pjsua_internal.h, not a configurable macro): two families of four fill it exactly, so another transport needs a PJSIP patch (`createTransports` asserts it, `cpjsua_transport_slots`). - **Bind address** (`Engine(bindAddress:)`, `macrosip-cli --bind`; brackets are dropped, "[::1]" is "::1"). An address of one family creates that family's transports only, and its UDP is the required one; accounts of the other family are refused with `transportUnavailable`. No bind address: both families on all interfaces. RTP binds to the bind address only for accounts of its family (`AccountMapping`), which with a bind address are the only ones. A bind address that is not an IP literal counts as IPv4 (pjsua resolves it for an IPv4 socket). - **Accounts stay bound.** `pjsua_init_tpselector` turns `transport_id` into a TRANSPORT selector (UDP) or a LISTENER selector (TCP/TLS), which fixes the family; `ipv6_sip_use` (`PJSIP_TPSELECTOR_IP_VER`) only applies to unbound accounts. Unbinding would change Contact and Via under STUN and lose the choice between the verifying and the non-verifying TLS listener, so every account is bound to the transport of its family. pjsua then takes Contact and Via from that transport (`pjsua_acc_get_uac_addr` adds the IPv6 flag for an account whose `tp_type` is IPv6), and an incoming request over UDP6, TCP6 or TLS6 scores the transport match only for the accounts bound to that transport type (`pjsua_acc_find_for_incoming`). The unbound exception of "No STUN for private servers" is IPv4 only. -- **Which family** (`IPFamilyPolicy.decide`). The server is the first hop: the outbound proxy when one is set, otherwise the registrar (or the domain). An IP literal picks its own family; IPv4 only and IPv6 only with a host name use that family. Auto with a host name: when only one family has a transport for the account's kind (a bind address, a failed IPv6 transport), that family without a lookup; with DNS SRV in effect (pjsua has a resolver) and no explicit port, IPv4 first, because `getaddrinfo` cannot follow SRV records (pjsua resolves the SRV targets itself, A and AAAA, and skips entries of the other family; when nothing of IPv4 answers, the fallback below moves the account to IPv6); otherwise the first family that `getaddrinfo(host, AF_UNSPEC)` returns (`IPFamilyResolver.system`, with `pj_getaddrinfo`'s hints: no socket type, no flags) and that has a transport. That is the order PJSIP itself tries when it resolves a host name without its DNS resolver; it is not what PJSIP does with DNS SRV on (its own A/AAAA queries), and for an account that does not register the INVITEs go to the dialled URI's host, which may differ from the first hop. Nothing resolved (offline): IPv4, decided again later. Lookups never block the engine queue (`FamilyLookups`): they run on a global queue, at most one per host at a time (every account and trigger that wants that host gets the same answer), answers are cached for 30 s (failures are not), and a network change drops the cache and the lookups still running. A new account whose family depends on a running lookup is added at once, but its first REGISTER waits for the answer (at most `lookupWait`, 2 s; then it registers over what it has, IPv4 for a name that is not resolved yet); the same after `updateAccount` changed the server. A lookup that fails or does not answer never moves an existing account. Tests inject a resolver (`setFamilyResolverForTests`). A host name that lacks the chosen family (IPv6 only, no AAAA) fails to register with a DNS error like any unknown host. -- **Contradictions.** IPv4 only with an IPv6 literal server (or IPv6 only with an IPv4 literal) can never register: `addAccount` and `updateAccount` throw `.invalidArgument("server 2001:db8::1 is an IPv6 address but the account is set to IPv4 only")`, and the account editor shows "The server's address is an IPv6 address. Choose Auto or IPv6 only." under Connection with Save and Test off (`IPFamilyPolicy.conflict`, also used by the editor). An IPv4-mapped literal (`[::ffff:a.b.c.d]`) is an IPv6 literal. +- **Which family** (`IPFamilyPolicy.decide`). The server is the first hop: the outbound proxy when one is set, otherwise the registrar (or the domain). An IP literal picks its own family; IPv4 only and IPv6 only with a host name use that family. Auto with a host name: when only one family has a transport for the account's kind (a bind address, a failed IPv6 transport), that family without a lookup; with DNS SRV in effect (pjsua has a resolver) and no explicit port, IPv4 first, because `getaddrinfo` cannot follow SRV records (pjsua resolves the SRV targets itself, A and AAAA, and skips entries of the other family; when nothing of IPv4 answers, the fallback below moves the account to IPv6); otherwise the first family that `getaddrinfo(host, AF_UNSPEC)` returns (`IPFamilyResolver.system`, with `pj_getaddrinfo`'s hints: no socket type, no flags) and that has a transport. That is the order PJSIP itself tries when it resolves a host name without its DNS resolver; it is not what PJSIP does with DNS SRV on (its own A/AAAA queries), and for an account that does not register the INVITEs go to the dialled URI's host, which may differ from the first hop. Nothing resolved (offline): IPv4, decided again later. Lookups never block the engine queue (`FamilyLookups`): they run on a global queue, at most one per host at a time (every account and trigger that wants that host gets the same answer), answers are cached for 30 s (failures are not), and a network change drops the cache and the lookups still running (an answer that reaches the engine after the change is dropped too: `familiesResolved` compares the lookups' epoch on the engine queue). A new account whose family depends on a running lookup is added at once, but its first REGISTER waits for the answer (at most `lookupWait`, 2 s; then it registers over what it has, IPv4 for a name that is not resolved yet); the same after `updateAccount` changed the server. After `updateAccount` changed only the IP protocol of an account that is registered, nothing is sent while the lookup runs and the account stays `.registered`: the answer moves it, or leaves it where it is without a REGISTER (the binding is there; the same for a REGISTER held through a round, which registered the account anyway). A lookup that fails or does not answer never moves an existing account. Tests inject a resolver (`setFamilyResolverForTests`). A host name that lacks the chosen family (IPv6 only, no AAAA) fails to register with a DNS error like any unknown host. +- **Contradictions.** IPv4 only with an IPv6 literal server (or IPv6 only with an IPv4 literal) can never register: `addAccount` and `updateAccount` throw `.invalidArgument("server 2001:db8::1 is an IPv6 address but the account is set to IPv4 only")`, and the account editor shows "The server's address is an IPv6 address. Choose Auto or IPv6 only." under Connection with Save and Test off (`IPFamilyPolicy.conflict`, also used by the editor). An IPv4-mapped literal (`[::ffff:a.b.c.d]`) is an IPv6 literal. A family without a transport for the account's kind (IPv6 only while the IPv6 UDP port is taken, IPv4 only with an IPv6 bind address) is refused by `addAccount` and `updateAccount` with `.transportUnavailable(kind, ipv6:)`, which the editor shows; the account stays as it was. The reconciler drops a desire for a family that has no transport (transports can go away at a network change). - **Decided again** for Auto accounts with a host name (not the SRV case): at every network change (a round, or IPv6 appearing or going away without one) and when a lookup answers (not for a sticky account, see below). Any of these only records the desired family (`AccountEntry.desired`, stamped with the account's `generation`); the reconciler moves the account. `updateAccount`: another server (registrar, proxy or transport) is configured over its own family at once, as there is no binding of this account there to remove (as before for any change of server, the binding at the old server expires there); a changed IP protocol for the same server becomes a desired family (the binding on this server is removed by the move); anything else keeps the family, a family Auto fell back to included, and sends no un-REGISTER (the app calls `updateAccount` with unchanged settings, e.g. when the default account changes). A network change makes every Auto account follow the system again: a family Auto fell back to is forgotten (in the DNS SRV case too: back to IPv4 first), and the lookups are made anew. - **Fallback when there is no answer** (`registrationRetryNeeded`). Auto keeps the system's order for the first REGISTER. When a REGISTER gets no response at all (no `rdata` in `on_reg_state2`: a local timeout, a refused or broken connection, PJSIP_ETPNOTSUITABLE when the host has no address of the bound family), the account wants the other family at once, if the host name has an address of it (a cached lookup, or one started now) or DNS SRV is in effect (the SRV targets are unknown to the engine, the other family is the only chance); a log line says "no answer over IPv6; trying IPv4". This is recorded also during a round (the round's own REGISTER is reported before the round ends), and the move happens as soon as the round is over, not a backoff later. Once per series of failures (`familyFallbackTried`, cleared by the next backoff retry and by a network change), so two silent families alternate at the backoff pace, not in a loop. The family moved to stays (`familySticky`) until the next network change: lookup answers and unchanged updates do not move it back. A server that answers (401, 403, 404, a 408 or 503 it sends itself) is no reason to switch. The result carries the account's `generation` from the bridge; a result of settings that changed meanwhile is not acted on. In 26.3.0 an account bound to IPv4 reached a dual-stack server over IPv4 whatever the order (PJSIP skipped the IPv6 entries with ETPNOTSUITABLE); without this fallback, Auto would have kept retrying the family that does not answer (an Asterisk listening on 0.0.0.0 only, an IPv6 firewall). -- **Moving an account** (`reconcileFamilies`, on the watchdog tick and right after a desire, a lookup answer, an un-REGISTER answer or the end of a round). A move starts only when no network-change round runs, the account has no call in any state (the call's dialog keeps its peer of the old family, and `pjsua_acc_modify` plus a re-INVITE with `UPDATE_CONTACT` would give it the new family's selector, so in-dialog requests would fail with ETPNOTSUITABLE), no REGISTER of the account is in flight (`cpjsua_acc_reg_busy`, or a request waiting for one) and the desire belongs to the current settings. Then: (1) the old binding is un-REGISTERed (Expires 0 over the old family) and the move waits for the answer, at most `moveUnregisterTimeout` (5 s): `pjsua_acc_modify` with `disable_reg_on_modify` would destroy the registration session without one (pjsua_acc.c, `unreg_first`), and a lingering old Contact makes Kamailio fork calls to both, and Asterisk with `max_contacts=1`, `remove_existing=no` refuse the new one with 403, which is never retried; (2) `pjsua_acc_modify` onto the new family's transport, which destroys the old session (pjsip_regc_destroy2 with force: a late answer of it is dropped), `allow_sdp_nat_rewrite` set on the live config (`cpjsua_acc_set_sdp_nat_rewrite`: pjsua_acc_modify copies every field we set but this one), the MWI subscription ended (`cpjsua_acc_end_mwi_after_move`; pjsua subscribes again after the REGISTER) and the presence subscriptions of the account's buddies made anew (`cpjsua_buddy_resubscribe`), because their dialogs keep the transport selector they were created with (pjsua_pres.c), the registrar trusted again only after it accepted a REGISTER (`setRegistrarSource(nil)`); (3) REGISTER over the new family. The account shows `.registering` from the start of the move until that REGISTER is answered. A failure in (2) keeps the desire, and the next tick tries again; a move whose desire went away meanwhile registers the account where it is. An un-REGISTER answer of an account that should stay registered never shows `.unregistered` (`pjOnRegState2` hands it to the engine instead), so neither a move's nor a late one can make the UI say the account is off while the engine registers it. A round that starts during step (1) aborts the move; it starts again after the round (the round registers the account on its old family first). PUBLISH has no transport selector (`pjsip_publishc`) and needs nothing. Known limitation: subscriptions other phones made to our presence (server side, pjsua_pres.c `pres_on_rx_request`) keep their dialog's transport until they end; a watcher reached only over the old family stops getting NOTIFYs until it subscribes anew. +- **Moving an account** (`reconcileFamilies`, on the watchdog tick and right after a desire, a lookup answer, an un-REGISTER answer or the end of a round). A move starts only when no network-change round runs, the account has no call in any state (the call's dialog keeps its peer of the old family, and `pjsua_acc_modify` plus a re-INVITE with `UPDATE_CONTACT` would give it the new family's selector, so in-dialog requests would fail with ETPNOTSUITABLE), no REGISTER of the account is in flight (`cpjsua_acc_reg_busy`, or a request waiting for one; such a request is cleared when `pjsua_acc_modify` drops the session it waited for, whose answer never comes) and the desire belongs to the current settings. Then: (1) when the registrar holds a binding as PJSIP knows it (`cpjsua_acc_has_binding`: a registration session whose last REGISTER was answered 2xx; not the UI state, which also shows intents), it is un-REGISTERed (Expires 0 over the old family) and the move waits for the answer, at most `moveUnregisterTimeout` (5 s): `pjsua_acc_modify` with `disable_reg_on_modify` would destroy the registration session without one (pjsua_acc.c, `unreg_first`), and a lingering old Contact makes Kamailio fork calls to both, and Asterisk with `max_contacts=1`, `remove_existing=no` refuse the new one with 403, which is never retried; (2) `pjsua_acc_modify` onto the new family's transport, which destroys the old session (pjsip_regc_destroy2 with force: a late answer of it is dropped), `allow_sdp_nat_rewrite` set on the live config (`cpjsua_acc_set_sdp_nat_rewrite`: pjsua_acc_modify copies every field we set but this one), the MWI subscription ended (`cpjsua_acc_end_mwi_after_move`; pjsua subscribes again after the REGISTER) and the presence subscriptions of the account's buddies made anew (`cpjsua_buddy_resubscribe`), because their dialogs keep the transport selector they were created with (pjsua_pres.c), the registrar trusted again only after it accepted a REGISTER (`setRegistrarSource(nil)`); (3) REGISTER over the new family. The account shows `.registering` from the start of the move until that REGISTER is answered. A call that started during (1) stops the move before (2): the account registers again on the old family, and the desire waits for the calls. A failure in (2) drops the desire until the next trigger (one log line: "cannot move to IPv6 (...); stays on IPv4") and registers the account where it is; so does a move whose desire went away meanwhile. `updateAccount` with a new IP protocol and new credentials (or another change for which pjsua drops the registration session without an un-REGISTER, pjsua_acc.c `unreg_first`) first registers again on the old family, so the move that follows can remove that binding. An un-REGISTER answer of an account that should stay registered never shows `.unregistered` (`pjOnRegState2` hands it to the engine instead), so neither a move's nor a late one can make the UI say the account is off while the engine registers it. A round that starts during step (1) aborts the move; it starts again after the round (the round registers the account on its old family first). IPv6 coming or going without a round lets the move finish with its desire (the new lookup's answer may move the account back later). PUBLISH has no transport selector (`pjsip_publishc`) and needs nothing. Known limitation: subscriptions other phones made to our presence (server side, pjsua_pres.c `pres_on_rx_request`) keep their dialog's transport until they end; a watcher reached only over the old family stops getting NOTIFYs until it subscribes anew. - **Media.** IPv6 accounts set `ipv6_media_use = PJSUA_IPV6_ENABLED_USE_IPV6_ONLY`: `get_media_ip_version` (pjsua_media.c) counts `::1`, link-local and a missing global address as "available" but not "usable", so PREFER_IPV6 would offer IPv4 on loopback and on a Mac without a global IPv6 address. The offer is `c=IN IP6` with IPv6 RTP sockets. An incoming offer is answered in its own family: an `IN IP4` offer to an IPv6 account gets an IPv4 answer and IPv4 RTP (with an IPv6 bind address that socket cannot be bound and the call fails). IPv4 accounts keep pjsua's default (PREFER_IPV4): IPv4 offers, and an `IN IP6` offer is answered with IPv6, as before. `localRTPAddress(of:)` reports the RTP address (diagnostics, tests). - **No STUN over IPv6.** IPv6 accounts have `sip_stun_use` and `media_stun_use` disabled (STUN and TURN over IPv6 are out of scope; pjsua maps IPv4 only) and `allow_sdp_nat_rewrite` on, so after the first REGISTER answer the SDP carries the address the registrar saw (with temporary addresses, the one actually used) instead of `pj_gethostip`'s pick. - **ICE over IPv6** (with a PJSIP patch). pjsua gives an IPv6 call an IPv6 ICE component (`create_ice_media_transport`: `ice_cfg.af = AF_INET6` and a second STUN transport of family IPv6) bound to the string "0" (`IN6_ADDR_ANY`). macOS `getaddrinfo` turns "0" into `::ffff:0.0.0.0`, and binding a V6ONLY socket to that fails ("Failed creating STUN transport #1 for comp 1: Can't assign requested address"): the offer then had IPv4 candidates and `c=IN IP4` only, and an IPv6 answer failed the call (`pjmedia_stream_info_from_sdp`: PJ_EAFNOTSUP). pjsua also ignored the account's bound address for the IPv6 components (only the IPv4 ones use `rtp_cfg.bound_addr`). `scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch` (applied by `build-pjsip.sh`, see scripts/README-build.md) binds the IPv6 STUN and TURN components like the IPv4 ones: to the account's bound address when it is an IPv6 address, else to "::"; and a STUN component bound to a loopback address keeps its host candidate (`loop_addr`), which pjnath leaves out by default. An IPv6 call with ICE now offers `c=IN IP6` with the IPv6 default candidate, IPv6 and IPv4 host candidates (pjsua adds an IPv4 STUN transport as well), and connects. On all interfaces pjnath leaves out `::1` and every link-local address but the default one, so on a Mac without a global IPv6 address the only IPv6 candidate is link-local (`fe80::…`, its zone is not carried in SDP), and between two ICE endpoints its checks fail and ICE nominates an IPv4 pair. With the bind address `::1` the only candidates are `::1` (the IPv4 component cannot bind an IPv6 address and is left out), and two ICE legs negotiate ICE over IPv6 and carry RTP (tested). An IPv6 pair winning over a real network needs a global IPv6 address: not verified. - **Incoming.** Requests over UDP6, TCP6 and TLS6 reach the account bound to that transport: an IPv4 and an IPv6 account with the same user and domain each get the calls and messages of their own family. `SignallingSource` compares IPv6 addresses in any spelling (`[2001:DB8:0::1]` is `2001:db8::1`), so the registrar-source trust (answer-after) works over IPv6. - **Network changes.** `NetworkPath.address6` is the source address of the default IPv6 route (a UDP socket connected to 2001:db8::1, nothing sent; link-local and loopback do not count). With an account bound to IPv6, a new address starts a round (see "Network resilience"): a primary one (at once, even while an outgoing call rings) when the address those accounts used is no longer assigned to any interface (`NetworkPath.isAssignedLocally`, getifaddrs; IPv6 lost, or replaced and gone) or the path has no IPv6 route, a non-primary one when it is still assigned, as a deprecated temporary address stays for days after a new one takes over (the round waits for a ringing outgoing call like a gateway change; it restarts the listeners and re-REGISTERs, so Contact moves to the new address before the old one expires). Without IPv6 accounts an IPv6 change starts no round at all, so IPv4 accounts and their calls are not disturbed; when IPv6 appears or goes away, Auto host names are decided again and the reconciler moves the accounts whose family changed (after a round that may be running); a new temporary address alone changes nothing for them. An empty IPv6 lookup keeps the previous address only while the path still routes IPv6 (`NWPath.supportsIPv6`, `NetworkPath.ipv6Route`) and the address is still assigned, so losing IPv6 is noticed, also when the router stops advertising IPv6 while the SLAAC address stays assigned until its lifetime runs out. `pjsua_handle_ip_change` with `restart_listener` restarts every listener, the IPv6 ones included (all `tpdata`), and recomputes their published addresses. -- **Tests.** `EngineIPv6Tests.swift` with `IPv6Stub` (UDP and TCP on `[::1]`, optionally UDP on 127.0.0.1 with the same port; answers REGISTER and INVITE with `IN IP6 ::1`, records family, transport, Via, Contact and bodies; sends INVITE with an IPv6 or IPv4 offer and MESSAGE). Values: old JSON decodes as Auto (unknown values too), literals, first hop, contradictions, the decision with a fake resolver (literals, fixed families, resolver order, offline, availability, SRV), `IPFamilyResolver.system` against `getaddrinfo`, mapping by family and its read-back from `pjsua_acc_config` (transport id, `ipv6_media_use`, STUN, bind address), transport ids, IPv6 registrar-source comparison, `NetworkPath.address6`. pjsua: `bindAddressDecidesTransportFamilies`; `ipv6TransportFailureIsNotFatal` (`[::]:P` held by another socket: the engine starts with IPv4 UDP and TCP6 on P and refuses IPv6 UDP accounts; released, both UDP transports use P); `contradictoryIPProtocolIsRefused` (`.invalidArgument`); `ipv6AccountRegistersOverUDP6` (Via and Contact `[::1]`, the live config, a MESSAGE out over UDP6); `ipv6AccountRegistersOverTCP6`; `ipv6CallOffersIPv6MediaAndCarriesRTP` (`c=IN IP6 ::1`, RTP address `::1`, a loopback call over `[::1]` with RTP both ways); `incomingOverIPv6ReachesTheIPv6Account` (account by family, answers per offer family, MESSAGE); `autoFollowsSystemResolverForHostNames` ("localhost": Auto follows getaddrinfo's first family, IPv4 only and IPv6 only keep theirs); moves are checked as the registrar and the UI see them (`expectMove`: the un-REGISTER over the old family is answered, the REGISTER over the new one follows it, at least the stub's delay of the un-REGISTER answer later, and the account goes `.registering` → `.registered` only after that REGISTER, never `.unregistered` in between): `familyIsDecidedAgainOnNetworkChange` (both ways, `allow_sdp_nat_rewrite` read back); `ipProtocolChangeMovesTheAccount` (and an unchanged update moves nothing); `familyMoveWaitsForTheAccountsCalls`; `ipv6AppearingDuringARoundWaitsForTheRound` (the round ends on its REGISTER, not on its safety timer, then the move); `autoFallsBackToTheOtherFamilyWithoutAnswer` (IPv6 side silent: IPv4 at once; an unchanged update keeps IPv4; a retry stays on IPv4 before moving back); `fallbackAfterARoundMovesWhenTheRoundEnds`; `autoFallsBackWhenTheConnectionIsRefused` (TCP refused over IPv4: TCP6 at once); `autoKeepsTheFamilyWhenTheServerAnswers` (a 503 from the server: retried on IPv6, no switch); `srvFallbackIsUndoneAtANetworkChange` (DNS stub with SRV, A and AAAA); `subscriptionsFollowAFamilyMove` (MWI and presence SUBSCRIBE anew over IPv6); `familyLookupsDoNotBlockTheEngine` (a slow resolver delays neither `addAccount` nor a round, one lookup per host, cached; the first REGISTER waits for the lookup); `ipv6AddressChangesStartRoundsOnlyWhenTheyMatter` (no round without IPv6 accounts; with one, a rotation with the old address assigned waits for a ringing call, a loss runs at once, also with the address assigned but no IPv6 route); `networkChangeRestartsIPv6Listeners`; `iceGathersIPv6CandidatesOverIPv6` (ICE on: `c=IN IP6`, IPv6 host candidates including the default one, RTP to a peer without ICE); `iceOverIPv6HonoursTheBindAddress` (bind address `::1`: the only IPv6 candidate is `::1`, and a call between two ICE legs carries RTP over IPv6). In `Engine262Tests.swift`, `privateIPv6ServerAccountIsAdded` now registers over UDP6 with STUN on, and `privateServerAccountDoesNotUseSTUN` sets IPv4 only for its "localhost" account. +- **Tests.** `EngineIPv6Tests.swift` with `IPv6Stub` (UDP and TCP on `[::1]`, optionally UDP on 127.0.0.1 with the same port; answers REGISTER and INVITE with `IN IP6 ::1`, records family, transport, Via, Contact and bodies; sends INVITE with an IPv6 or IPv4 offer and MESSAGE). Values: old JSON decodes as Auto (unknown values too), literals, first hop, contradictions, the decision with a fake resolver (literals, fixed families, resolver order, offline, availability, SRV), `IPFamilyResolver.system` against `getaddrinfo`, mapping by family and its read-back from `pjsua_acc_config` (transport id, `ipv6_media_use`, STUN, bind address), transport ids, IPv6 registrar-source comparison, `NetworkPath.address6`. pjsua: `bindAddressDecidesTransportFamilies`; `ipv6TransportFailureIsNotFatal` (`[::]:P` held by another socket: the engine starts with IPv4 UDP and TCP6 on P and refuses IPv6 UDP accounts; released, both UDP transports use P); `contradictoryIPProtocolIsRefused` (`.invalidArgument`); `ipv6AccountRegistersOverUDP6` (Via and Contact `[::1]`, the live config, a MESSAGE out over UDP6); `ipv6AccountRegistersOverTCP6`; `ipv6CallOffersIPv6MediaAndCarriesRTP` (`c=IN IP6 ::1`, RTP address `::1`, a loopback call over `[::1]` with RTP both ways); `incomingOverIPv6ReachesTheIPv6Account` (account by family, answers per offer family, MESSAGE); `autoFollowsSystemResolverForHostNames` ("localhost": Auto follows getaddrinfo's first family, IPv4 only and IPv6 only keep theirs); moves are checked as the registrar and the UI see them (`expectMove`: the un-REGISTER over the old family is answered, the REGISTER over the new one follows it, at least the stub's delay of the un-REGISTER answer later, and the account goes `.registering` → `.registered` only after that REGISTER, never `.unregistered` in between): `familyIsDecidedAgainOnNetworkChange` (both ways, `allow_sdp_nat_rewrite` read back); `ipProtocolChangeMovesTheAccount` (and an unchanged update moves nothing); `familyMoveWaitsForTheAccountsCalls`; `callDuringTheMoveWaitKeepsTheFamily` (a call made while the un-REGISTER waits: registered again over IPv4, moved after the hang-up); `switchToAutoRemovesTheOldBinding` (IPv4 only to Auto with an uncached host: `.registered` while the lookup runs, then the IPv4 binding un-REGISTERed before the IPv6 REGISTER; with a new password too, after the IPv4 binding is renewed); `switchToAutoOnTheSameFamilySendsNothing`; `ipv6OnlyWithoutAnIPv6TransportIsRefused` (`.transportUnavailable(.udp, ipv6: true)`, the account stays registered); `updateDroppingABusySessionDoesNotBlockTheMove` (a REGISTER waiting behind an unanswered one, then new credentials: the move still happens); `ipv6AppearingDuringARoundWaitsForTheRound` (the round ends on its REGISTER, not on its safety timer, then the move); `ipv6ChangeDuringAMoveLetsItFinish` (IPv6 gone while the un-REGISTER waits and the new lookup is slow: one un-REGISTER, no IPv4 REGISTER in between); `lookupAnswerFromBeforeANetworkChangeIsDropped`; `autoFallsBackToTheOtherFamilyWithoutAnswer` (IPv6 side silent: IPv4 at once; an unchanged update keeps IPv4; a retry stays on IPv4 before moving back); `fallbackAfterARoundMovesWhenTheRoundEnds`; `autoFallsBackWhenTheConnectionIsRefused` (TCP refused over IPv4: TCP6 at once); `autoKeepsTheFamilyWhenTheServerAnswers` (a 503 from the server: retried on IPv6, no switch); `srvFallbackIsUndoneAtANetworkChange` (DNS stub with SRV, A and AAAA); `subscriptionsFollowAFamilyMove` (MWI and presence SUBSCRIBE anew over IPv6); `familyLookupsDoNotBlockTheEngine` (a slow resolver delays neither `addAccount` nor a round, one lookup per host, cached; the first REGISTER waits for the lookup); `ipv6AddressChangesStartRoundsOnlyWhenTheyMatter` (no round without IPv6 accounts; with one, a rotation with the old address assigned waits for a ringing call, a loss runs at once, also with the address assigned but no IPv6 route); `networkChangeRestartsIPv6Listeners`; `iceGathersIPv6CandidatesOverIPv6` (ICE on: `c=IN IP6`, IPv6 host candidates including the default one, RTP to a peer without ICE); `iceOverIPv6HonoursTheBindAddress` (bind address `::1`: the only IPv6 candidate is `::1`, and a call between two ICE legs carries RTP over IPv6). In `Engine262Tests.swift`, `privateIPv6ServerAccountIsAdded` now registers over UDP6 with STUN on, and `privateServerAccountDoesNotUseSTUN` sets IPv4 only for its "localhost" account. - **Only a real network can verify:** a real IPv6 PBX over UDP, TCP and TLS (a certificate for an AAAA name), a dual-stack server by host name, an IPv6-only network, router-advertised and temporary addresses (whether NWPathMonitor reports a new temporary address at all, and the Contact after a rotation), moving between IPv4-only, dual-stack and IPv6-only networks with calls in progress, SRV targets with AAAA records only, IPv6 firewalls without NAT, and RTP through them. ## Deny incoming calls diff --git a/docs/adr/0014-ipv6-dual-stack.md b/docs/adr/0014-ipv6-dual-stack.md index d0ee941..4d4fa16 100644 --- a/docs/adr/0014-ipv6-dual-stack.md +++ b/docs/adr/0014-ipv6-dual-stack.md @@ -45,11 +45,12 @@ loses the choice between the verifying and the non-verifying TLS listener (miles record a desired family for the account's current settings (a generation number), and the reconciler moves the account when nothing can be hurt by it: no network-change round running, **no call on the account in any state** (the call's dialog would keep a peer of the old family on a - transport of the new one), no REGISTER of it in flight. A move un-REGISTERs the old binding and - waits for the answer (5 s at most: a lingering Contact forks calls or makes a `max_contacts=1` - server refuse the new one with 403), then moves the account to the other transport, makes its - subscriptions anew there and registers; the account shows "registering" throughout, and a failed - step is tried again on the next tick. Moving from several places at once had raced with rounds, + transport of the new one), no REGISTER of it in flight. A move un-REGISTERs the old binding (as + PJSIP knows it, not as the UI shows it) and waits for the answer (5 s at most: a lingering Contact + forks calls or makes a `max_contacts=1` server refuse the new one with 403), then moves the account + to the other transport, makes its subscriptions anew there and registers; the account shows + "registering" throughout. A call that starts meanwhile, or a failed step, leaves the account + registered where it is; a family without a transport is refused, not wanted. Moving from several places at once had raced with rounds, REGISTERs in flight and late answers. - **IPv6 address changes** count only for accounts that use IPv6. A new temporary address while the old one is still assigned is a non-primary change (it waits for a ringing outgoing call); losing From f581fbf5908b609e3016abf9dd7f98072ee85a01 Mon Sep 17 00:00:00 2001 From: HSMM Date: Mon, 9 Nov 2026 18:11:26 +0300 Subject: [PATCH 11/12] IPv6 tests: hit the lookup cache and assert ICE negotiation --- Sources/CPJSUA/include/CPJSUA.h | 5 ++++ Sources/CPJSUA/shim.c | 27 +++++++++++++++++++ .../MacroSIPCore/Engine/Engine+Families.swift | 9 +++++++ Tests/MacroSIPCoreTests/EngineIPv6Tests.swift | 16 +++++++++-- docs/ENGINE.md | 4 +-- 5 files changed, 57 insertions(+), 4 deletions(-) diff --git a/Sources/CPJSUA/include/CPJSUA.h b/Sources/CPJSUA/include/CPJSUA.h index e60939f..928f8ae 100644 --- a/Sources/CPJSUA/include/CPJSUA.h +++ b/Sources/CPJSUA/include/CPJSUA.h @@ -328,6 +328,11 @@ int cpjsua_call_local_rtp_port(pjsua_call_id call_id); * "192.0.2.10", no brackets, no port) into `buf`; returns its length, 0 if none. */ int cpjsua_call_local_rtp_addr(pjsua_call_id call_id, char *buf, unsigned len); +/** ICE of the call's first audio stream: 1 when ICE is in use and its negotiation completed (session + * running), with the addresses of component 1's nominated pair in `local` and `remote` (no + * brackets, no port); 0 otherwise. */ +int cpjsua_call_ice_pair(pjsua_call_id call_id, char *local, char *remote, unsigned len); + /* ----------------------------------------------------- packet source --- */ /** Where a received message came from (rdata->pkt_info, rdata->tp_info). */ diff --git a/Sources/CPJSUA/shim.c b/Sources/CPJSUA/shim.c index f52d5f1..1a80d8f 100644 --- a/Sources/CPJSUA/shim.c +++ b/Sources/CPJSUA/shim.c @@ -1140,6 +1140,33 @@ int cpjsua_call_local_rtp_port(pjsua_call_id call_id) return pj_sockaddr_get_port(&tpinfo.sock_info.rtp_addr_name); } +int cpjsua_call_ice_pair(pjsua_call_id call_id, char *local, char *remote, unsigned len) +{ + pjsua_call_info ci; + pjmedia_transport_info tpinfo; + pjmedia_ice_transport_info *ice; + int aud; + + if (!local || !remote || len == 0) + return 0; + local[0] = remote[0] = '\0'; + if (pjsua_call_get_info(call_id, &ci) != PJ_SUCCESS) + return 0; + aud = first_audio_index(&ci); + if (aud < 0) + return 0; + pjmedia_transport_info_init(&tpinfo); + if (pjsua_call_get_med_transport_info(call_id, (unsigned)aud, &tpinfo) != PJ_SUCCESS) + return 0; + ice = (pjmedia_ice_transport_info *) + pjmedia_transport_info_get_spc_info(&tpinfo, PJMEDIA_TRANSPORT_TYPE_ICE); + if (!ice || !ice->active || ice->sess_state != PJ_ICE_STRANS_STATE_RUNNING) + return 0; + pj_sockaddr_print(&ice->comp[0].lcand_addr, local, len, 0); + pj_sockaddr_print(&ice->comp[0].rcand_addr, remote, len, 0); + return 1; +} + int cpjsua_call_local_rtp_addr(pjsua_call_id call_id, char *buf, unsigned len) { pjsua_call_info ci; diff --git a/Sources/MacroSIPCore/Engine/Engine+Families.swift b/Sources/MacroSIPCore/Engine/Engine+Families.swift index ed7215a..ecbc007 100644 --- a/Sources/MacroSIPCore/Engine/Engine+Families.swift +++ b/Sources/MacroSIPCore/Engine/Engine+Families.swift @@ -329,6 +329,15 @@ extension Engine { func transportIDsForTests() -> TransportIDs { transports } + /// The nominated ICE pair of a call (component 1), nil while ICE is not used or not negotiated. + func iceSelectedPairForTests(_ id: CallID) -> (local: String, remote: String)? { + guard let slot = try? liveSlot(id) else { return nil } + var local = [CChar](repeating: 0, count: 64), remote = [CChar](repeating: 0, count: 64) + guard cpjsua_call_ice_pair(slot, &local, &remote, UInt32(local.count)) != 0 else { return nil } + func text(_ b: [CChar]) -> String { String(decoding: b.prefix { $0 != 0 }.map { UInt8(bitPattern: $0) }, as: UTF8.self) } + return (text(local), text(remote)) + } + func accountFamilyForTests(_ id: AccountID) -> IPFamily? { accounts[id]?.family } func setFamilyResolverForTests(_ resolve: @escaping @Sendable (String) -> [IPFamily]) { diff --git a/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift b/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift index ed6f119..1f38128 100644 --- a/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift +++ b/Tests/MacroSIPCoreTests/EngineIPv6Tests.swift @@ -1287,11 +1287,14 @@ extension EngineTests { #expect(stub.bindingRegisters.allSatisfy { $0.family == .ipv6 }, "\(stub.registers.map(\.family))") #expect(calls.withLock { $0 } == 1) // one lookup for both accounts - // Cached: an update that changes the server back to the same host asks nobody. + // Cached: an update that changes the server (now through an outbound proxy on the same host) + // decides from the cache, asks nobody and keeps IPv6. var moved = a - moved.registrar = "localhost:\(stub.port)" + moved.outboundProxy = "sip:localhost:\(stub.port);lr" try await engine.updateAccount(moved, password: nil) #expect(calls.withLock { $0 } == 1) + #expect(await engine.accountFamilyForTests(a.id) == .ipv6) + #expect(await waitUntil { await engine.registrationState(of: a.id).isRegistered }) let round = ContinuousClock.now await engine.simulateNetworkChange() // the cache is dropped; lookups again @@ -1640,6 +1643,15 @@ extension EngineTests { let a = try? await engine.mediaStats(out), b = try? await engine.mediaStats(inc.id) return (a?.rxPackets ?? 0) > 10 && (b?.rxPackets ?? 0) > 10 }) + // ICE itself completed on both legs, with the ::1 pair nominated (RTP alone would also flow to + // the default candidate after a failed negotiation). + let incID = inc.id + #expect(await waitUntil { + let a = await engine.iceSelectedPairForTests(out), b = await engine.iceSelectedPairForTests(incID) + return a != nil && b != nil + }) + let pair = await engine.iceSelectedPairForTests(out) + #expect(pair?.local == "::1" && pair?.remote == "::1", "\(String(describing: pair))") #expect(await engine.localRTPAddress(of: out) == "::1") try await engine.hangup(out) #expect(await waitUntil { await engine.calls().isEmpty }) diff --git a/docs/ENGINE.md b/docs/ENGINE.md index 70c6aa2..4ba83c2 100644 --- a/docs/ENGINE.md +++ b/docs/ENGINE.md @@ -389,10 +389,10 @@ Dual stack since 26.3.1 ([#11](https://github.com/HSMM/MacroSIP/issues/11), ADR - **Moving an account** (`reconcileFamilies`, on the watchdog tick and right after a desire, a lookup answer, an un-REGISTER answer or the end of a round). A move starts only when no network-change round runs, the account has no call in any state (the call's dialog keeps its peer of the old family, and `pjsua_acc_modify` plus a re-INVITE with `UPDATE_CONTACT` would give it the new family's selector, so in-dialog requests would fail with ETPNOTSUITABLE), no REGISTER of the account is in flight (`cpjsua_acc_reg_busy`, or a request waiting for one; such a request is cleared when `pjsua_acc_modify` drops the session it waited for, whose answer never comes) and the desire belongs to the current settings. Then: (1) when the registrar holds a binding as PJSIP knows it (`cpjsua_acc_has_binding`: a registration session whose last REGISTER was answered 2xx; not the UI state, which also shows intents), it is un-REGISTERed (Expires 0 over the old family) and the move waits for the answer, at most `moveUnregisterTimeout` (5 s): `pjsua_acc_modify` with `disable_reg_on_modify` would destroy the registration session without one (pjsua_acc.c, `unreg_first`), and a lingering old Contact makes Kamailio fork calls to both, and Asterisk with `max_contacts=1`, `remove_existing=no` refuse the new one with 403, which is never retried; (2) `pjsua_acc_modify` onto the new family's transport, which destroys the old session (pjsip_regc_destroy2 with force: a late answer of it is dropped), `allow_sdp_nat_rewrite` set on the live config (`cpjsua_acc_set_sdp_nat_rewrite`: pjsua_acc_modify copies every field we set but this one), the MWI subscription ended (`cpjsua_acc_end_mwi_after_move`; pjsua subscribes again after the REGISTER) and the presence subscriptions of the account's buddies made anew (`cpjsua_buddy_resubscribe`), because their dialogs keep the transport selector they were created with (pjsua_pres.c), the registrar trusted again only after it accepted a REGISTER (`setRegistrarSource(nil)`); (3) REGISTER over the new family. The account shows `.registering` from the start of the move until that REGISTER is answered. A call that started during (1) stops the move before (2): the account registers again on the old family, and the desire waits for the calls. A failure in (2) drops the desire until the next trigger (one log line: "cannot move to IPv6 (...); stays on IPv4") and registers the account where it is; so does a move whose desire went away meanwhile. `updateAccount` with a new IP protocol and new credentials (or another change for which pjsua drops the registration session without an un-REGISTER, pjsua_acc.c `unreg_first`) first registers again on the old family, so the move that follows can remove that binding. An un-REGISTER answer of an account that should stay registered never shows `.unregistered` (`pjOnRegState2` hands it to the engine instead), so neither a move's nor a late one can make the UI say the account is off while the engine registers it. A round that starts during step (1) aborts the move; it starts again after the round (the round registers the account on its old family first). IPv6 coming or going without a round lets the move finish with its desire (the new lookup's answer may move the account back later). PUBLISH has no transport selector (`pjsip_publishc`) and needs nothing. Known limitation: subscriptions other phones made to our presence (server side, pjsua_pres.c `pres_on_rx_request`) keep their dialog's transport until they end; a watcher reached only over the old family stops getting NOTIFYs until it subscribes anew. - **Media.** IPv6 accounts set `ipv6_media_use = PJSUA_IPV6_ENABLED_USE_IPV6_ONLY`: `get_media_ip_version` (pjsua_media.c) counts `::1`, link-local and a missing global address as "available" but not "usable", so PREFER_IPV6 would offer IPv4 on loopback and on a Mac without a global IPv6 address. The offer is `c=IN IP6` with IPv6 RTP sockets. An incoming offer is answered in its own family: an `IN IP4` offer to an IPv6 account gets an IPv4 answer and IPv4 RTP (with an IPv6 bind address that socket cannot be bound and the call fails). IPv4 accounts keep pjsua's default (PREFER_IPV4): IPv4 offers, and an `IN IP6` offer is answered with IPv6, as before. `localRTPAddress(of:)` reports the RTP address (diagnostics, tests). - **No STUN over IPv6.** IPv6 accounts have `sip_stun_use` and `media_stun_use` disabled (STUN and TURN over IPv6 are out of scope; pjsua maps IPv4 only) and `allow_sdp_nat_rewrite` on, so after the first REGISTER answer the SDP carries the address the registrar saw (with temporary addresses, the one actually used) instead of `pj_gethostip`'s pick. -- **ICE over IPv6** (with a PJSIP patch). pjsua gives an IPv6 call an IPv6 ICE component (`create_ice_media_transport`: `ice_cfg.af = AF_INET6` and a second STUN transport of family IPv6) bound to the string "0" (`IN6_ADDR_ANY`). macOS `getaddrinfo` turns "0" into `::ffff:0.0.0.0`, and binding a V6ONLY socket to that fails ("Failed creating STUN transport #1 for comp 1: Can't assign requested address"): the offer then had IPv4 candidates and `c=IN IP4` only, and an IPv6 answer failed the call (`pjmedia_stream_info_from_sdp`: PJ_EAFNOTSUP). pjsua also ignored the account's bound address for the IPv6 components (only the IPv4 ones use `rtp_cfg.bound_addr`). `scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch` (applied by `build-pjsip.sh`, see scripts/README-build.md) binds the IPv6 STUN and TURN components like the IPv4 ones: to the account's bound address when it is an IPv6 address, else to "::"; and a STUN component bound to a loopback address keeps its host candidate (`loop_addr`), which pjnath leaves out by default. An IPv6 call with ICE now offers `c=IN IP6` with the IPv6 default candidate, IPv6 and IPv4 host candidates (pjsua adds an IPv4 STUN transport as well), and connects. On all interfaces pjnath leaves out `::1` and every link-local address but the default one, so on a Mac without a global IPv6 address the only IPv6 candidate is link-local (`fe80::…`, its zone is not carried in SDP), and between two ICE endpoints its checks fail and ICE nominates an IPv4 pair. With the bind address `::1` the only candidates are `::1` (the IPv4 component cannot bind an IPv6 address and is left out), and two ICE legs negotiate ICE over IPv6 and carry RTP (tested). An IPv6 pair winning over a real network needs a global IPv6 address: not verified. +- **ICE over IPv6** (with a PJSIP patch). pjsua gives an IPv6 call an IPv6 ICE component (`create_ice_media_transport`: `ice_cfg.af = AF_INET6` and a second STUN transport of family IPv6) bound to the string "0" (`IN6_ADDR_ANY`). macOS `getaddrinfo` turns "0" into `::ffff:0.0.0.0`, and binding a V6ONLY socket to that fails ("Failed creating STUN transport #1 for comp 1: Can't assign requested address"): the offer then had IPv4 candidates and `c=IN IP4` only, and an IPv6 answer failed the call (`pjmedia_stream_info_from_sdp`: PJ_EAFNOTSUP). pjsua also ignored the account's bound address for the IPv6 components (only the IPv4 ones use `rtp_cfg.bound_addr`). `scripts/pjsip-patches/0001-ipv6-ice-bind-any.patch` (applied by `build-pjsip.sh`, see scripts/README-build.md) binds the IPv6 STUN and TURN components like the IPv4 ones: to the account's bound address when it is an IPv6 address, else to "::"; and a STUN component bound to a loopback address keeps its host candidate (`loop_addr`), which pjnath leaves out by default. An IPv6 call with ICE now offers `c=IN IP6` with the IPv6 default candidate, IPv6 and IPv4 host candidates (pjsua adds an IPv4 STUN transport as well), and connects. On all interfaces pjnath leaves out `::1` and every link-local address but the default one, so on a Mac without a global IPv6 address the only IPv6 candidate is link-local (`fe80::…`, its zone is not carried in SDP), and between two ICE endpoints its checks fail and ICE nominates an IPv4 pair. With the bind address `::1` the only candidates are `::1` (the IPv4 component cannot bind an IPv6 address and is left out), and two ICE legs complete ICE over IPv6, with the `::1` pair nominated on both, and carry RTP (tested; `cpjsua_call_ice_pair` reads the session state and the nominated pair of component 1 from `pjmedia_ice_transport_info`). An IPv6 pair winning over a real network needs a global IPv6 address: not verified. - **Incoming.** Requests over UDP6, TCP6 and TLS6 reach the account bound to that transport: an IPv4 and an IPv6 account with the same user and domain each get the calls and messages of their own family. `SignallingSource` compares IPv6 addresses in any spelling (`[2001:DB8:0::1]` is `2001:db8::1`), so the registrar-source trust (answer-after) works over IPv6. - **Network changes.** `NetworkPath.address6` is the source address of the default IPv6 route (a UDP socket connected to 2001:db8::1, nothing sent; link-local and loopback do not count). With an account bound to IPv6, a new address starts a round (see "Network resilience"): a primary one (at once, even while an outgoing call rings) when the address those accounts used is no longer assigned to any interface (`NetworkPath.isAssignedLocally`, getifaddrs; IPv6 lost, or replaced and gone) or the path has no IPv6 route, a non-primary one when it is still assigned, as a deprecated temporary address stays for days after a new one takes over (the round waits for a ringing outgoing call like a gateway change; it restarts the listeners and re-REGISTERs, so Contact moves to the new address before the old one expires). Without IPv6 accounts an IPv6 change starts no round at all, so IPv4 accounts and their calls are not disturbed; when IPv6 appears or goes away, Auto host names are decided again and the reconciler moves the accounts whose family changed (after a round that may be running); a new temporary address alone changes nothing for them. An empty IPv6 lookup keeps the previous address only while the path still routes IPv6 (`NWPath.supportsIPv6`, `NetworkPath.ipv6Route`) and the address is still assigned, so losing IPv6 is noticed, also when the router stops advertising IPv6 while the SLAAC address stays assigned until its lifetime runs out. `pjsua_handle_ip_change` with `restart_listener` restarts every listener, the IPv6 ones included (all `tpdata`), and recomputes their published addresses. -- **Tests.** `EngineIPv6Tests.swift` with `IPv6Stub` (UDP and TCP on `[::1]`, optionally UDP on 127.0.0.1 with the same port; answers REGISTER and INVITE with `IN IP6 ::1`, records family, transport, Via, Contact and bodies; sends INVITE with an IPv6 or IPv4 offer and MESSAGE). Values: old JSON decodes as Auto (unknown values too), literals, first hop, contradictions, the decision with a fake resolver (literals, fixed families, resolver order, offline, availability, SRV), `IPFamilyResolver.system` against `getaddrinfo`, mapping by family and its read-back from `pjsua_acc_config` (transport id, `ipv6_media_use`, STUN, bind address), transport ids, IPv6 registrar-source comparison, `NetworkPath.address6`. pjsua: `bindAddressDecidesTransportFamilies`; `ipv6TransportFailureIsNotFatal` (`[::]:P` held by another socket: the engine starts with IPv4 UDP and TCP6 on P and refuses IPv6 UDP accounts; released, both UDP transports use P); `contradictoryIPProtocolIsRefused` (`.invalidArgument`); `ipv6AccountRegistersOverUDP6` (Via and Contact `[::1]`, the live config, a MESSAGE out over UDP6); `ipv6AccountRegistersOverTCP6`; `ipv6CallOffersIPv6MediaAndCarriesRTP` (`c=IN IP6 ::1`, RTP address `::1`, a loopback call over `[::1]` with RTP both ways); `incomingOverIPv6ReachesTheIPv6Account` (account by family, answers per offer family, MESSAGE); `autoFollowsSystemResolverForHostNames` ("localhost": Auto follows getaddrinfo's first family, IPv4 only and IPv6 only keep theirs); moves are checked as the registrar and the UI see them (`expectMove`: the un-REGISTER over the old family is answered, the REGISTER over the new one follows it, at least the stub's delay of the un-REGISTER answer later, and the account goes `.registering` → `.registered` only after that REGISTER, never `.unregistered` in between): `familyIsDecidedAgainOnNetworkChange` (both ways, `allow_sdp_nat_rewrite` read back); `ipProtocolChangeMovesTheAccount` (and an unchanged update moves nothing); `familyMoveWaitsForTheAccountsCalls`; `callDuringTheMoveWaitKeepsTheFamily` (a call made while the un-REGISTER waits: registered again over IPv4, moved after the hang-up); `switchToAutoRemovesTheOldBinding` (IPv4 only to Auto with an uncached host: `.registered` while the lookup runs, then the IPv4 binding un-REGISTERed before the IPv6 REGISTER; with a new password too, after the IPv4 binding is renewed); `switchToAutoOnTheSameFamilySendsNothing`; `ipv6OnlyWithoutAnIPv6TransportIsRefused` (`.transportUnavailable(.udp, ipv6: true)`, the account stays registered); `updateDroppingABusySessionDoesNotBlockTheMove` (a REGISTER waiting behind an unanswered one, then new credentials: the move still happens); `ipv6AppearingDuringARoundWaitsForTheRound` (the round ends on its REGISTER, not on its safety timer, then the move); `ipv6ChangeDuringAMoveLetsItFinish` (IPv6 gone while the un-REGISTER waits and the new lookup is slow: one un-REGISTER, no IPv4 REGISTER in between); `lookupAnswerFromBeforeANetworkChangeIsDropped`; `autoFallsBackToTheOtherFamilyWithoutAnswer` (IPv6 side silent: IPv4 at once; an unchanged update keeps IPv4; a retry stays on IPv4 before moving back); `fallbackAfterARoundMovesWhenTheRoundEnds`; `autoFallsBackWhenTheConnectionIsRefused` (TCP refused over IPv4: TCP6 at once); `autoKeepsTheFamilyWhenTheServerAnswers` (a 503 from the server: retried on IPv6, no switch); `srvFallbackIsUndoneAtANetworkChange` (DNS stub with SRV, A and AAAA); `subscriptionsFollowAFamilyMove` (MWI and presence SUBSCRIBE anew over IPv6); `familyLookupsDoNotBlockTheEngine` (a slow resolver delays neither `addAccount` nor a round, one lookup per host, cached; the first REGISTER waits for the lookup); `ipv6AddressChangesStartRoundsOnlyWhenTheyMatter` (no round without IPv6 accounts; with one, a rotation with the old address assigned waits for a ringing call, a loss runs at once, also with the address assigned but no IPv6 route); `networkChangeRestartsIPv6Listeners`; `iceGathersIPv6CandidatesOverIPv6` (ICE on: `c=IN IP6`, IPv6 host candidates including the default one, RTP to a peer without ICE); `iceOverIPv6HonoursTheBindAddress` (bind address `::1`: the only IPv6 candidate is `::1`, and a call between two ICE legs carries RTP over IPv6). In `Engine262Tests.swift`, `privateIPv6ServerAccountIsAdded` now registers over UDP6 with STUN on, and `privateServerAccountDoesNotUseSTUN` sets IPv4 only for its "localhost" account. +- **Tests.** `EngineIPv6Tests.swift` with `IPv6Stub` (UDP and TCP on `[::1]`, optionally UDP on 127.0.0.1 with the same port; answers REGISTER and INVITE with `IN IP6 ::1`, records family, transport, Via, Contact and bodies; sends INVITE with an IPv6 or IPv4 offer and MESSAGE). Values: old JSON decodes as Auto (unknown values too), literals, first hop, contradictions, the decision with a fake resolver (literals, fixed families, resolver order, offline, availability, SRV), `IPFamilyResolver.system` against `getaddrinfo`, mapping by family and its read-back from `pjsua_acc_config` (transport id, `ipv6_media_use`, STUN, bind address), transport ids, IPv6 registrar-source comparison, `NetworkPath.address6`. pjsua: `bindAddressDecidesTransportFamilies`; `ipv6TransportFailureIsNotFatal` (`[::]:P` held by another socket: the engine starts with IPv4 UDP and TCP6 on P and refuses IPv6 UDP accounts; released, both UDP transports use P); `contradictoryIPProtocolIsRefused` (`.invalidArgument`); `ipv6AccountRegistersOverUDP6` (Via and Contact `[::1]`, the live config, a MESSAGE out over UDP6); `ipv6AccountRegistersOverTCP6`; `ipv6CallOffersIPv6MediaAndCarriesRTP` (`c=IN IP6 ::1`, RTP address `::1`, a loopback call over `[::1]` with RTP both ways); `incomingOverIPv6ReachesTheIPv6Account` (account by family, answers per offer family, MESSAGE); `autoFollowsSystemResolverForHostNames` ("localhost": Auto follows getaddrinfo's first family, IPv4 only and IPv6 only keep theirs); moves are checked as the registrar and the UI see them (`expectMove`: the un-REGISTER over the old family is answered, the REGISTER over the new one follows it, at least the stub's delay of the un-REGISTER answer later, and the account goes `.registering` → `.registered` only after that REGISTER, never `.unregistered` in between): `familyIsDecidedAgainOnNetworkChange` (both ways, `allow_sdp_nat_rewrite` read back); `ipProtocolChangeMovesTheAccount` (and an unchanged update moves nothing); `familyMoveWaitsForTheAccountsCalls`; `callDuringTheMoveWaitKeepsTheFamily` (a call made while the un-REGISTER waits: registered again over IPv4, moved after the hang-up); `switchToAutoRemovesTheOldBinding` (IPv4 only to Auto with an uncached host: `.registered` while the lookup runs, then the IPv4 binding un-REGISTERed before the IPv6 REGISTER; with a new password too, after the IPv4 binding is renewed); `switchToAutoOnTheSameFamilySendsNothing`; `ipv6OnlyWithoutAnIPv6TransportIsRefused` (`.transportUnavailable(.udp, ipv6: true)`, the account stays registered); `updateDroppingABusySessionDoesNotBlockTheMove` (a REGISTER waiting behind an unanswered one, then new credentials: the move still happens); `ipv6AppearingDuringARoundWaitsForTheRound` (the round ends on its REGISTER, not on its safety timer, then the move); `ipv6ChangeDuringAMoveLetsItFinish` (IPv6 gone while the un-REGISTER waits and the new lookup is slow: one un-REGISTER, no IPv4 REGISTER in between); `lookupAnswerFromBeforeANetworkChangeIsDropped`; `autoFallsBackToTheOtherFamilyWithoutAnswer` (IPv6 side silent: IPv4 at once; an unchanged update keeps IPv4; a retry stays on IPv4 before moving back); `fallbackAfterARoundMovesWhenTheRoundEnds`; `autoFallsBackWhenTheConnectionIsRefused` (TCP refused over IPv4: TCP6 at once); `autoKeepsTheFamilyWhenTheServerAnswers` (a 503 from the server: retried on IPv6, no switch); `srvFallbackIsUndoneAtANetworkChange` (DNS stub with SRV, A and AAAA); `subscriptionsFollowAFamilyMove` (MWI and presence SUBSCRIBE anew over IPv6); `familyLookupsDoNotBlockTheEngine` (a slow resolver delays neither `addAccount` nor a round, one lookup per host; an update that adds an outbound proxy on the same host decides from the cache without a lookup; the first REGISTER waits for the lookup); `ipv6AddressChangesStartRoundsOnlyWhenTheyMatter` (no round without IPv6 accounts; with one, a rotation with the old address assigned waits for a ringing call, a loss runs at once, also with the address assigned but no IPv6 route); `networkChangeRestartsIPv6Listeners`; `iceGathersIPv6CandidatesOverIPv6` (ICE on: `c=IN IP6`, IPv6 host candidates including the default one, RTP to a peer without ICE); `iceOverIPv6HonoursTheBindAddress` (bind address `::1`: the only IPv6 candidate is `::1`; a call between two ICE legs completes ICE with the `::1` pair nominated on both and carries RTP over IPv6). In `Engine262Tests.swift`, `privateIPv6ServerAccountIsAdded` now registers over UDP6 with STUN on, and `privateServerAccountDoesNotUseSTUN` sets IPv4 only for its "localhost" account. - **Only a real network can verify:** a real IPv6 PBX over UDP, TCP and TLS (a certificate for an AAAA name), a dual-stack server by host name, an IPv6-only network, router-advertised and temporary addresses (whether NWPathMonitor reports a new temporary address at all, and the Contact after a rotation), moving between IPv4-only, dual-stack and IPv6-only networks with calls in progress, SRV targets with AAAA records only, IPv6 firewalls without NAT, and RTP through them. ## Deny incoming calls From ede73e14b0900c753f8d88fda61fce0ba48868f8 Mon Sep 17 00:00:00 2001 From: HSMM Date: Mon, 9 Nov 2026 18:51:52 +0300 Subject: [PATCH 12/12] 26.3.1: release status in the roadmap and READMEs --- README.md | 6 +++--- README.ru.md | 6 +++--- docs/ROADMAP.md | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index c4bcdbf..eaa1132 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ ![macOS 14+](https://img.shields.io/badge/macOS-14%2B-lightgrey) ![Universal: Apple Silicon and Intel](https://img.shields.io/badge/arch-universal-lightgrey) ![PJSIP 2.17](https://img.shields.io/badge/PJSIP-2.17-green) -![Release 26.3.0](https://img.shields.io/badge/release-26.3.0-brightgreen) +![Release 26.3.1](https://img.shields.io/badge/release-26.3.1-brightgreen) A MicroSIP-style SIP softphone for macOS on Apple Silicon and Intel. Native Swift and SwiftUI interface, [PJSIP](https://github.com/pjsip/pjproject) 2.17 engine, @@ -19,7 +19,7 @@ presence, quick keys, global hotkeys, English and Russian interface. Guide: https://hsmm.github.io/MacroSIP/wiki/ -Status: `26.3.0` released 2026-11-05. What comes next: [docs/ROADMAP.md](docs/ROADMAP.md). +Status: `26.3.1` released 2026-11-09. What comes next: [docs/ROADMAP.md](docs/ROADMAP.md). ## Screenshots @@ -221,7 +221,7 @@ scripts/selftest-call.sh # end-to-end call against a local pjsua: RTP both wa The details are in [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md#releasing). -1. Tag `26.3.0` (release candidates: `26.3.0-rc.1`) and push the tag; the app takes its version from the tag. For a final release also bump `Product.fallbackVersion`. +1. Tag `26.3.1` (release candidates: `26.3.1-rc.1`) and push the tag; the app takes its version from the tag. For a final release also bump `Product.fallbackVersion`. 2. `.github/workflows/release.yml` builds the DMG, creates the GitHub Release and adds it to the update feed (`appcast.xml` on the `gh-pages` branch, signed with the Actions secret `SPARKLE_PRIVATE_KEY`; ADR 0013). Tag each release on a new commit, a final release after its diff --git a/README.ru.md b/README.ru.md index 75aed06..081c9a4 100644 --- a/README.ru.md +++ b/README.ru.md @@ -9,7 +9,7 @@ ![macOS 14+](https://img.shields.io/badge/macOS-14%2B-lightgrey) ![Universal: Apple Silicon and Intel](https://img.shields.io/badge/arch-universal-lightgrey) ![PJSIP 2.17](https://img.shields.io/badge/PJSIP-2.17-green) -![Release 26.3.0](https://img.shields.io/badge/release-26.3.0-brightgreen) +![Release 26.3.1](https://img.shields.io/badge/release-26.3.1-brightgreen) SIP-софтфон для macOS на Apple Silicon и Intel в духе MicroSIP. Нативный интерфейс на Swift и SwiftUI, движок [PJSIP](https://github.com/pjsip/pjproject) 2.17, без @@ -19,7 +19,7 @@ Electron и Qt. Одно небольшое окно, значок в строк Руководство: https://hsmm.github.io/MacroSIP/wiki/ru/index.html -Статус: выпущена версия `26.3.0` (5 ноября 2026). Что дальше: [docs/ROADMAP.md](docs/ROADMAP.md). +Статус: выпущена версия `26.3.1` (9 ноября 2026). Что дальше: [docs/ROADMAP.md](docs/ROADMAP.md). ## Скриншоты @@ -223,7 +223,7 @@ scripts/selftest-call.sh # сквозной звонок на локальн Подробности в [docs/DEVELOPMENT.md](docs/DEVELOPMENT.md#releasing). -1. Поставить тег `26.3.0` (кандидаты: `26.3.0-rc.1`) и отправить его; версию приложение берёт из тега. Для финального релиза также обновить `Product.fallbackVersion`. +1. Поставить тег `26.3.1` (кандидаты: `26.3.1-rc.1`) и отправить его; версию приложение берёт из тега. Для финального релиза также обновить `Product.fallbackVersion`. 2. `.github/workflows/release.yml` собирает DMG, создаёт GitHub Release и добавляет его в ленту обновлений (`appcast.xml` в ветке `gh-pages`, подпись секретом Actions `SPARKLE_PRIVATE_KEY`; ADR 0013). Каждый релиз ставится на новый коммит, финальный после кандидата тоже. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 1f7e7c8..8ad8004 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -77,7 +77,7 @@ App: - Messages are off until switched on in Settings › General ([#8](https://github.com/HSMM/MacroSIP/issues/8)): with the switch off there is no Messages tab, no Send Message item, no notification and no sound, and incoming `MESSAGE` requests are dropped with a log line. - The ringtone chosen in Settings › Audio reaches the engine ([#7](https://github.com/HSMM/MacroSIP/issues/7)): Classic, Digital and Soft are three different melodies, a custom AIFF, M4A or MP3 file is converted to WAV once and reused, a file that cannot be read keeps the previous choice and says why, and the preview plays the real choice at the chosen volume. -`26.3.1` (not released yet): IPv6 ([#11](https://github.com/HSMM/MacroSIP/issues/11)). SIP over UDP, TCP and TLS and the audio over IPv6 next to IPv4, for a server given by an IPv6 address or by a host name with AAAA records; an account at `[2001:db8::1]` no longer retries forever. Account editor › Advanced › IP protocol: Auto (an IP address picks its own protocol, a host name follows the order macOS returns and falls back to the other protocol at once when the server does not answer; decided again after a network change; the move removes the old registration first and never happens during a call), IPv4 only, IPv6 only. IPv6 accounts use no STUN; ICE gathers IPv6 candidates with a PJSIP patch (pjsua bound its IPv6 ICE socket to "0", which macOS cannot bind; `scripts/pjsip-patches/`). Tested on loopback only; a real IPv6 PBX and network are not verified. +`26.3.1` (2026-11-09): IPv6 ([#11](https://github.com/HSMM/MacroSIP/issues/11)). SIP over UDP, TCP and TLS and the audio over IPv6 next to IPv4, for a server given by an IPv6 address or by a host name with AAAA records; an account at `[2001:db8::1]` no longer retries forever. Account editor › Advanced › IP protocol: Auto (an IP address picks its own protocol, a host name follows the order macOS returns and falls back to the other protocol at once when the server does not answer; decided again after a network change; the move removes the old registration first and never happens during a call), IPv4 only, IPv6 only. IPv6 accounts use no STUN; ICE gathers IPv6 candidates with a PJSIP patch (pjsua bound its IPv6 ICE socket to "0", which macOS cannot bind; `scripts/pjsip-patches/`). Tested on loopback only; a real IPv6 PBX and network are not verified. ## Later