diff --git a/README.md b/README.md index 22b5b20..d7df1e3 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@    - + 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.2.0` released 2026-11-04. What comes next: [docs/ROADMAP.md](docs/ROADMAP.md). +Status: `26.3.0` released 2026-11-05. What comes next: [docs/ROADMAP.md](docs/ROADMAP.md). ## Screenshots @@ -27,41 +27,48 @@ The app follows the macOS appearance; every picture below switches with it (ligh frames are in [docs/screenshots](docs/screenshots), English and Russian).
- 





- 



-
-
+
+
- 



- 

![]() |
-![]() |
+![]() |
+![]() |
+ 

- 





- 



-
-
+
+
- 



- 

![]() |
-![]() |
+![]() |
+![]() |
+ 

/" (level 3),
+/// and in the packet dumps of a MESSAGE request: pjsua's "RX/TX ... bytes ...:\n\n--end
+/// msg--" (level 4) and pjsip's "Dropped packet:\n-- end of packet." (level 4). The text
+/// or the body becomes "…"; status, reason, request line and headers stay. Where the end of the
+/// text is ambiguous, more is replaced, never less.
+enum MessageLogRedaction {
+ static let placeholder = "…"
+
+ static func redact(_ line: String) -> String {
+ // Every log line passes here: only lines that can carry a MESSAGE are looked at.
+ guard line.contains("essage '") || line.contains("MESSAGE ") else { return line }
+ var out = line
+ if !redactDelivery(&out) { redactPacketBody(&out) }
+ return out
+ }
+
+ /// pjsua_im.c's delivery lines. Returns true when the line was one.
+ private static func redactDelivery(_ s: inout String) -> Bool {
+ if let start = s.range(of: "Message '"),
+ let end = s.range(of: "' delivered successfully", options: .backwards), start.upperBound <= end.lowerBound {
+ s.replaceSubrange(start.upperBound../" (pjsua appends "/").
+ var searchEnd = s.endIndex
+ while let quote = s.range(of: "': ", options: .backwards, range: start.upperBound.. result. 2xx: accepted. A response: its code and reason phrase. No
+ /// response (`answered == false`): 408 for the transaction timeout, else a local failure
+ /// (pjsua reports transport errors as 503 and DNS errors as 502 with the pj_strerror text
+ /// as reason), which becomes code 0 with that text.
+ static func result(code: Int, reason: String, answered: Bool) -> MessageSendResult {
+ if (200...299).contains(code) { return .accepted(code: code) }
+ let text = reason.isEmpty ? PJ.string(pjsip_get_status_text(Int32(code)).pointee) : reason
+ if !answered && code != 408 { return .failed(code: 0, reason: text) }
+ return .failed(code: code, reason: text)
+ }
+
+ /// `on_pager2` -> event, nil for a MESSAGE that is not text/plain or has no body.
+ /// `mimeType` is pjsua's "type/subtype" (parameters dropped); `from` the From name-addr.
+ static func incoming(account: AccountID, from: String, mimeType: String, body: String, at: Date) -> IncomingMessage? {
+ guard mimeType.trimmingCharacters(in: .whitespaces).lowercased() == "text/plain", !body.isEmpty else { return nil }
+ return IncomingMessage(accountID: account, remote: RemoteParty.parse(from), text: body, receivedAt: at)
+ }
+}
diff --git a/Sources/MacroSIPCore/Engine/Engine+Sounds.swift b/Sources/MacroSIPCore/Engine/Engine+Sounds.swift
index ab9a71c..5a231ad 100644
--- a/Sources/MacroSIPCore/Engine/Engine+Sounds.swift
+++ b/Sources/MacroSIPCore/Engine/Engine+Sounds.swift
@@ -20,6 +20,7 @@ enum EventSounds {
case .callEnded: return [tone(660, on: 80, off: 40), tone(440, on: 160, off: 0)]
case .voicemail: return [tone(880, on: 70, off: 30), tone(880, on: 70, off: 30), tone(1175, on: 120, off: 0)]
case .error: return [tone(330, on: 120, off: 60), tone(330, on: 120, off: 0)]
+ case .message: return [tone(1175, on: 70, off: 60), tone(1175, on: 70, off: 0)]
case .keyPress: return nil
}
}
diff --git a/Sources/MacroSIPCore/Engine/Engine.swift b/Sources/MacroSIPCore/Engine/Engine.swift
index 426ac9f..71cd00d 100644
--- a/Sources/MacroSIPCore/Engine/Engine.swift
+++ b/Sources/MacroSIPCore/Engine/Engine.swift
@@ -336,6 +336,8 @@ public actor Engine {
bridge.unwatchAll()
buddies = [:]
pendingHolds = [:]
+ // pjsua_destroy terminates MESSAGEs still waiting for an answer (reported as interrupted).
+ bridge.beginStopping()
pjsua_call_hangup_all()
PJ.warn(pjsua_destroy(), "pjsua_destroy")
if transactionTimeoutOverrideMs != nil { cpjsua_set_tsx_timeout(Engine.defaultTransactionTimeoutMs) }
@@ -353,8 +355,10 @@ public actor Engine {
appliedSoftwareEC = nil
let ids = Array(accounts.keys)
accounts = [:]
+ let interrupted = interruptedMessageEvents()
bridge.detach(self)
for id in ids { emit(.registration(id, .unregistered)) }
+ for event in interrupted { emit(event) }
}
private func initPJSUA(_ network: NetworkSettings) throws {
@@ -413,6 +417,8 @@ public actor Engine {
try withExtendedLifetime(arena) {
try PJ.check(pjsua_init(ua, log, media), "pjsua_init")
}
+ // 415 for MESSAGE bodies other than text/plain (pjsua would accept them with 200).
+ PJ.warn(cpjsua_im_filter_register(), "MESSAGE content-type filter")
if dnsServers.contains(where: { $0.port != 53 }) { applyNameservers(dnsServers) }
if !dnsServers.isEmpty {
emit(.log(level: 3, "engine: DNS SRV via \(dnsServers.map(\.description).joined(separator: ", "))"))
diff --git a/Sources/MacroSIPCore/Engine/EngineBridge.swift b/Sources/MacroSIPCore/Engine/EngineBridge.swift
index d4b3a2b..c87f88e 100644
--- a/Sources/MacroSIPCore/Engine/EngineBridge.swift
+++ b/Sources/MacroSIPCore/Engine/EngineBridge.swift
@@ -133,6 +133,13 @@ final class EngineBridge: Sendable {
var watched: [UInt64: WatchedBuddy] = [:]
/// Latest voicemail indicator per account (RFC 3842 message-summary NOTIFY).
var voicemail: [AccountID: VoicemailState] = [:]
+ /// MESSAGEs sent and not answered yet, by the token in their pjsua user data. Whoever
+ /// removes an entry reports it: `on_pager_status2`, `sendMessage` after a failure
+ /// pjsua did not report, or `Engine.stop`.
+ var pendingMessages: [UInt64: PendingMessage] = [:]
+ /// `Engine.stop` is destroying pjsua: it terminates pending MESSAGEs itself (503, no
+ /// response), which are reported as interrupted.
+ var stopping = false
/// Never reset, so CallIDs stay unique across engine restarts in one process.
var nextSerial: UInt64 = 1
/// `Engine.setCallOptions` / `start`: read by `on_incoming_call` (single-call mode).
@@ -603,6 +610,60 @@ final class EngineBridge: Sendable {
}
}
+ // MARK: text messages
+
+ func addPendingMessage(_ token: UInt64, _ message: PendingMessage) {
+ state.withLock { $0.pendingMessages[token] = message }
+ }
+
+ /// Removes the entry; nil when its outcome was reported already.
+ func takePendingMessage(_ token: UInt64) -> PendingMessage? {
+ state.withLock { $0.pendingMessages.removeValue(forKey: token) }
+ }
+
+ /// Removes every entry, oldest first (`Engine.stop`: no answer can come any more).
+ func takeAllPendingMessages() -> [PendingMessage] {
+ state.withLock { st in
+ defer { st.pendingMessages = [:] }
+ return st.pendingMessages.sorted { $0.key < $1.key }.map(\.value)
+ }
+ }
+
+ /// `Engine.stop`: from now on a MESSAGE that fails without an answer was interrupted.
+ func beginStopping() {
+ state.withLock { $0.stopping = true }
+ }
+
+ /// The final answer to a MESSAGE we sent: emits `.messageStatus` once, the first time the
+ /// token is reported.
+ func reportMessageStatus(token: UInt64, _ reported: MessageSendResult) {
+ state.withLock { st in
+ guard let m = st.pendingMessages.removeValue(forKey: token) else { return }
+ var result = reported
+ if st.stopping, case .failed(0, _) = reported {
+ result = .failed(code: 0, reason: Engine.messageInterruptedReason)
+ }
+ switch result {
+ case let .accepted(code):
+ st.sink?.yield(.log(level: 4, "engine: \(m.id) to \(m.target) accepted (\(code))"))
+ case let .failed(code, reason):
+ st.sink?.yield(.log(level: 3, "engine: \(m.id) to \(m.target) failed: \(code > 0 ? "\(code) " : "")\(reason)"))
+ }
+ st.sink?.yield(.messageStatus(m.id, result))
+ }
+ }
+
+ /// Emits `.messageReceived` for an account the engine knows (none during shutdown).
+ func reportIncomingMessage(_ message: IncomingMessage, inCall slot: Int32) {
+ state.withLock { st in
+ guard st.accounts.values.contains(where: { $0.id == message.accountID }) else { return }
+ let sender = message.remote.number.isEmpty ? message.remote.uri : message.remote.number
+ st.sink?.yield(.log(level: 4, "engine: account \(message.accountID.raw): MESSAGE from \(sender), "
+ + "\(message.text.utf8.count) bytes\(slot >= 0 ? " (in call \(slot))" : "")"))
+ st.sink?.yield(.messageReceived(message))
+ }
+ }
+
/// Logs a warning (os_log + `.log` event) from a callback.
func warn(_ text: String) {
engineLogger.notice("\(text, privacy: .public)")
@@ -737,7 +798,8 @@ func installPJCallbacks(_ cb: inout pjsua_callback) {
cb.on_transport_state = pjOnTransportState
cb.on_ip_change_progress = pjOnIPChangeProgress
cb.on_mwi_info = pjOnMwiInfo
- // on_pager (instant messages) stays unset: pjsua answers MESSAGE with 200 and drops it.
+ cb.on_pager2 = pjOnPager2 // text messages (Engine+Messages.swift)
+ cb.on_pager_status2 = pjOnPagerStatus2
}
/// PJSIP log writer: os_log (subsystem com.hsmm.macrosip, category pjsip) + `.log` event.
@@ -745,6 +807,7 @@ func pjLogWriter(_ level: Int32, _ data: UnsafePointer?, _ len: Int32) {
guard let data, len > 0 else { return }
var text = String(decoding: UnsafeRawBufferPointer(start: data, count: Int(len)), as: UTF8.self)
while let last = text.last, last.isNewline { text.removeLast() } // "\r\n" is one Character
+ text = MessageLogRedaction.redact(text) // no message text in any log
let bridge = EngineBridge.shared
let type: OSLogType
switch level {
@@ -1140,6 +1203,45 @@ private func pjOnMwiInfo(_ accID: pjsua_acc_id, _ info: UnsafeMutablePointer`, no tag).
+private func pjOnPager2(_ callID: pjsua_call_id, _ from: UnsafePointer?, _ to: UnsafePointer?,
+ _ contact: UnsafePointer?, _ mimeType: UnsafePointer?,
+ _ body: UnsafePointer?, _ rdata: UnsafeMutablePointer?,
+ _ accID: pjsua_acc_id) {
+ let bridge = EngineBridge.shared
+ let sender = from.map { PJ.string($0.pointee) } ?? ""
+ guard let account = bridge.account(for: accID) else {
+ bridge.emit(.log(level: 4, "engine: MESSAGE from \(sender) for pjsua account \(accID) ignored (not ours)"))
+ return
+ }
+ let mime = mimeType.map { PJ.string($0.pointee) } ?? ""
+ guard let message = MessageMapping.incoming(account: account.id, from: sender, mimeType: mime,
+ body: body.map { PJ.string($0.pointee) } ?? "", at: Date())
+ else {
+ bridge.emit(.log(level: 4, "engine: MESSAGE from \(sender) ignored (\(mime.isEmpty ? "no body" : mime))"))
+ return
+ }
+ bridge.reportIncomingMessage(message, inCall: callID)
+}
+
+/// The final answer to a MESSAGE of `Engine.sendMessage` (user data = its token). pjsua calls it
+/// once per request: for a response, a timeout (408) and a local failure alike, never for 1xx;
+/// after a 401/407 it sends the request again with credentials and reports that one.
+private func pjOnPagerStatus2(_ callID: pjsua_call_id, _ to: UnsafePointer?, _ body: UnsafePointer?,
+ _ userData: UnsafeMutableRawPointer?, _ status: pjsip_status_code,
+ _ reason: UnsafePointer?, _ tdata: UnsafeMutablePointer?,
+ _ rdata: UnsafeMutablePointer?, _ accID: pjsua_acc_id) {
+ let code = Int(status.rawValue)
+ guard code >= 200 else { return } // not a final answer: the request is still pending
+ let token = UInt64(UInt(bitPattern: userData))
+ guard token != 0 else { return }
+ let text = reason.map { PJ.string($0.pointee) } ?? ""
+ EngineBridge.shared.reportMessageStatus(token: token, MessageMapping.result(code: code, reason: text,
+ answered: rdata != nil))
+}
+
private func pjOnBuddyState(_ buddyID: pjsua_buddy_id) {
PJ.registerThread()
guard let buddy = BuddySnapshot.read(buddyID) else { return }
diff --git a/Sources/MacroSIPCore/Engine/EngineTypes.swift b/Sources/MacroSIPCore/Engine/EngineTypes.swift
index cc2bdc4..0c10496 100644
--- a/Sources/MacroSIPCore/Engine/EngineTypes.swift
+++ b/Sources/MacroSIPCore/Engine/EngineTypes.swift
@@ -173,9 +173,55 @@ public enum EngineEvent: Sendable {
/// whether messages wait and the new/old voice message counts. Emitted when the
/// indicator changed (and on the first NOTIFY); `Engine.voicemailState(for:)` has the latest.
case voicemail(AccountID, waiting: Bool, new: Int, old: Int)
+ /// A text/plain MESSAGE arrived on one of our accounts (docs/ENGINE.md "Text messages").
+ case messageReceived(IncomingMessage)
+ /// The final outcome of `Engine.sendMessage`, exactly once per id.
+ case messageStatus(MessageID, MessageSendResult)
case log(level: Int, String)
}
+// MARK: - Text messages (SIP MESSAGE, release 26.3)
+
+/// Token of one outgoing MESSAGE (`Engine.sendMessage`); `.messageStatus` names it.
+public struct MessageID: Hashable, Sendable, CustomStringConvertible {
+ public let raw: UUID
+
+ public init(raw: UUID = UUID()) {
+ self.raw = raw
+ }
+
+ public var description: String { "message#\(raw.uuidString.prefix(8))" }
+}
+
+/// A MESSAGE that arrived on one of our accounts (text/plain only).
+public struct IncomingMessage: Equatable, Sendable {
+ public var accountID: AccountID
+ /// From the From header: `number` is the user part ("+375291234567", "102"), `uri` the
+ /// sender's URI (the reply target), `displayName` the From display name, if any.
+ public var remote: RemoteParty
+ /// The body decoded as UTF-8 (with `charset=utf-8` or without a charset); invalid bytes
+ /// become U+FFFD.
+ public var text: String
+ public var receivedAt: Date
+
+ public init(accountID: AccountID, remote: RemoteParty, text: String, receivedAt: Date) {
+ self.accountID = accountID
+ self.remote = remote
+ self.text = text
+ self.receivedAt = receivedAt
+ }
+}
+
+/// How a MESSAGE we sent ended (`.messageStatus`).
+public enum MessageSendResult: Equatable, Sendable {
+ /// 2xx from the server or the peer: accepted, which does not mean delivered to a phone.
+ case accepted(code: Int)
+ /// Final failure: the SIP code and reason phrase of the answer (404 "Not Found", 480,
+ /// 403...), 408 "Request Timeout" when nothing answered, or code 0 with the PJSIP error
+ /// text when the request could not be sent at all (transport or DNS error, engine stopped).
+ case failed(code: Int, reason: String)
+}
+
/// The latest voicemail indicator of an account (`Engine.voicemailState(for:)`).
public struct VoicemailState: Equatable, Sendable {
/// `Messages-Waiting: yes`.
@@ -209,6 +255,8 @@ public enum SoundEvent: Equatable, Sendable {
case voicemail
/// Two low beeps.
case error
+ /// Two short high beeps (a text message arrived).
+ case message
}
public enum EngineError: Error, Equatable, Sendable, CustomStringConvertible {
diff --git a/Sources/MacroSIPCore/Engine/PJSupport.swift b/Sources/MacroSIPCore/Engine/PJSupport.swift
index a20ee45..03488ad 100644
--- a/Sources/MacroSIPCore/Engine/PJSupport.swift
+++ b/Sources/MacroSIPCore/Engine/PJSupport.swift
@@ -179,23 +179,58 @@ extension AccountID {
}
extension RemoteParty {
- /// Parses a printed name-addr such as `"Alice" `.
+ /// Parses a printed name-addr such as `"Alice" ` (also the
+ /// sender of a MESSAGE, whose `uri` is the reply target). The URI is the last `<...>` outside
+ /// the quoted display name (`"x " ` -> `sip:a@b`); a quoted name is unescaped
+ /// (`"A \"B\""` -> `A "B"`), an unquoted one trimmed. Without brackets the whole value is the URI.
static func parse(_ raw: String) -> RemoteParty {
let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)
var name: String?
var uri = trimmed
- if let lt = trimmed.firstIndex(of: "<"),
- let gt = trimmed[lt...].firstIndex(of: ">") {
- uri = String(trimmed[trimmed.index(after: lt)..` pair outside double quotes (backslash escapes inside quotes).
+ private static func lastAngleBrackets(_ s: String) -> (String.Index, String.Index)? {
+ var inQuotes = false
+ var escaped = false
+ var open: String.Index?
+ var pair: (String.Index, String.Index)?
+ for i in s.indices {
+ let ch = s[i]
+ if inQuotes {
+ if escaped { escaped = false } else if ch == "\\" { escaped = true } else if ch == "\"" { inQuotes = false }
+ continue
+ }
+ switch ch {
+ case "\"": inQuotes = true
+ case "<": open = i
+ case ">":
+ if let o = open { pair = (o, i); open = nil }
+ default: break
+ }
+ }
+ return pair
+ }
+
+ /// A display name as printed: a quoted string loses its quotes and backslash escapes
+ /// (RFC 3261 quoted-pair); anything after the closing quote is ignored. A token is kept.
+ private static func displayName(_ s: String) -> String {
+ guard s.first == "\"" else { return s }
+ var out = ""
+ var escaped = false
+ for ch in s.dropFirst() {
+ if escaped { out.append(ch); escaped = false } else if ch == "\\" { escaped = true } else if ch == "\"" { break } else { out.append(ch) }
+ }
+ return out.trimmingCharacters(in: .whitespaces)
+ }
}
/// `Call-Info` header parsing (the C parser in shim.c, also used on incoming INVITEs).
diff --git a/Sources/MacroSIPCore/Model/AppSettings.swift b/Sources/MacroSIPCore/Model/AppSettings.swift
index 7b7d3ed..c563c98 100644
--- a/Sources/MacroSIPCore/Model/AppSettings.swift
+++ b/Sources/MacroSIPCore/Model/AppSettings.swift
@@ -27,12 +27,16 @@ public struct SoundEventSettings: Codable, Equatable, Sendable {
public var voicemail: Bool
/// `.error` when a call or registration fails.
public var error: Bool
+ /// `.message` when a text message arrives.
+ public var message: Bool
- public init(callEvents: Bool = false, keyPress: Bool = false, voicemail: Bool = false, error: Bool = false) {
+ public init(callEvents: Bool = false, keyPress: Bool = false, voicemail: Bool = false, error: Bool = false,
+ message: Bool = false) {
self.callEvents = callEvents
self.keyPress = keyPress
self.voicemail = voicemail
self.error = error
+ self.message = message
}
/// Missing keys decode as off.
@@ -42,6 +46,7 @@ public struct SoundEventSettings: Codable, Equatable, Sendable {
keyPress = (try? c.decodeIfPresent(Bool.self, forKey: .keyPress)) ?? false
voicemail = (try? c.decodeIfPresent(Bool.self, forKey: .voicemail)) ?? false
error = (try? c.decodeIfPresent(Bool.self, forKey: .error)) ?? false
+ message = (try? c.decodeIfPresent(Bool.self, forKey: .message)) ?? false
}
}
diff --git a/Sources/MacroSIPCore/Model/Message.swift b/Sources/MacroSIPCore/Model/Message.swift
new file mode 100644
index 0000000..e8312d4
--- /dev/null
+++ b/Sources/MacroSIPCore/Model/Message.swift
@@ -0,0 +1,194 @@
+import Foundation
+
+public enum MessageDirection: String, Codable, Sendable { case incoming, outgoing }
+
+/// `sent` means the SIP server or peer accepted the message (2xx), not that a phone received it.
+public enum MessageState: String, Codable, Sendable { case sending, sent, failed }
+
+public struct Conversation: Codable, Identifiable, Equatable, Sendable {
+ public var id: UUID
+ public var accountID: AccountID
+ /// What the UI shows and what a reply dials (user part, e.g. "+375291234567" or "102").
+ public var remoteNumber: String
+ /// Full URI of the peer as last seen.
+ public var remoteURI: String
+ /// The peer's host when it is part of who the peer is: an explicit host that is not the account's own domain, and the
+ /// host of every non-numeric user. nil for numbers dialled through the account. Absent in older files.
+ public var remoteHost: String?
+ /// From display name of the last incoming message, if any. Absent in older files.
+ public var remoteDisplayName: String?
+ /// Resolved when the conversation is created, if a contact matches.
+ public var contactID: UUID?
+ public var lastActivityAt: Date
+ /// Incoming messages not yet read. Absent in older files.
+ public var unread: Int
+
+ public init(
+ id: UUID = UUID(),
+ accountID: AccountID,
+ remoteNumber: String,
+ remoteURI: String = "",
+ remoteHost: String? = nil,
+ remoteDisplayName: String? = nil,
+ contactID: UUID? = nil,
+ lastActivityAt: Date = Date(),
+ unread: Int = 0
+ ) {
+ self.id = id
+ self.accountID = accountID
+ self.remoteNumber = remoteNumber
+ self.remoteURI = remoteURI
+ self.remoteHost = remoteHost
+ self.remoteDisplayName = remoteDisplayName
+ self.contactID = contactID
+ self.lastActivityAt = lastActivityAt
+ self.unread = unread
+ }
+
+ private enum CodingKeys: String, CodingKey {
+ case id, accountID, remoteNumber, remoteURI, remoteHost, remoteDisplayName, contactID, lastActivityAt, unread
+ }
+
+ public init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ id = try c.decode(UUID.self, forKey: .id)
+ accountID = try c.decode(AccountID.self, forKey: .accountID)
+ remoteNumber = try c.decode(String.self, forKey: .remoteNumber)
+ remoteURI = try c.decodeIfPresent(String.self, forKey: .remoteURI) ?? ""
+ remoteHost = try c.decodeIfPresent(String.self, forKey: .remoteHost)
+ remoteDisplayName = try c.decodeIfPresent(String.self, forKey: .remoteDisplayName)
+ contactID = try c.decodeIfPresent(UUID.self, forKey: .contactID)
+ lastActivityAt = try c.decode(Date.self, forKey: .lastActivityAt)
+ unread = try c.decodeIfPresent(Int.self, forKey: .unread) ?? 0
+ }
+}
+
+extension Conversation {
+ /// What the UI shows when the peer has no name: the number, or `user@host` where the host tells peers apart.
+ public var shownNumber: String { remoteHost.map { "\(remoteNumber)@\($0)" } ?? remoteNumber }
+
+ /// Whether this conversation is with the peer `address` on `account`.
+ public func matches(account: AccountID, address: ConversationAddress) -> Bool {
+ accountID == account && address.matches(user: remoteNumber, host: remoteHost)
+ }
+}
+
+/// Who a message is to or from, as a conversation tells peers apart: the user and, where it matters, the host.
+/// - A number (digits, `+`, `*`, `#` and the usual separators) is compared by its digits: `+375 29 123-45-67` and
+/// `375291234567` are one number, and a number with a country prefix meets the same number without it (one ends with
+/// the other and the shorter has at least 7 digits); shorter numbers (extensions) must be equal. The host counts only when it is explicit and not
+/// the account's own domain (an unknown domain: never).
+/// - Any other user (`alice`, `bob.smith`) is compared as written, case-insensitively, together with its host, which
+/// always counts.
+public struct ConversationAddress: Equatable, Sendable {
+ public var user: String
+ public var host: String?
+
+ /// Fewest digits for which one number may match another as its suffix.
+ public static let minSuffixDigits = 7
+
+ /// `raw` is a number, a `sip:`/`sips:`/`tel:` URI or `user@host`; `accountDomain` the account's domain.
+ public init(_ raw: String, accountDomain: String = "") {
+ let s = raw.trimmingCharacters(in: .whitespacesAndNewlines)
+ let lower = s.lowercased()
+ var user = s
+ var host: String?
+ if lower.hasPrefix("tel:") {
+ user = String(s.dropFirst(4))
+ } else if lower.hasPrefix("sip:") || lower.hasPrefix("sips:") || s.contains("@") {
+ user = DialString.userPart(of: s)
+ if let at = s.lastIndex(of: "@") {
+ let h = Self.bareHost(String(s[s.index(after: at)...]))
+ host = h.isEmpty ? nil : h
+ }
+ }
+ self.init(user: user, host: host, accountDomain: accountDomain)
+ }
+
+ /// The user as written and the host found next to it (nil when none).
+ init(user: String, host: String?, accountDomain: String) {
+ var host = host
+ if Self.isNumber(user) {
+ self.user = DialString.normalizeNumber(user)
+ // The host of a number counts only when it is explicit and differs from the account's domain (unknown: never).
+ if let h = host, accountDomain.isEmpty || h == Self.bareHost(accountDomain) { host = nil }
+ } else {
+ self.user = user.lowercased()
+ }
+ self.host = host
+ }
+
+ /// The peer of a conversation: `number` is the user part, `uri` (may be empty) says where it lives.
+ public init(number: String, uri: String, accountDomain: String) {
+ let fromURI = ConversationAddress(uri, accountDomain: accountDomain)
+ if number.isEmpty { self = fromURI; return }
+ let plain = ConversationAddress(number, accountDomain: accountDomain)
+ if plain.host != nil || uri.isEmpty { self = plain; return }
+ // `number` is a bare user: the host is the URI's (and numbers drop it when it is the account's own).
+ let host = uri.lastIndex(of: "@").map { Self.bareHost(String(uri[uri.index(after: $0)...])) }.flatMap { $0.isEmpty ? nil : $0 }
+ self.init(user: number, host: host, accountDomain: accountDomain)
+ }
+
+ static func isNumber(_ user: String) -> Bool {
+ !user.isEmpty && user.allSatisfy { "0123456789+*#-.() ".contains($0) } && user.contains(where: \.isNumber)
+ }
+
+ /// Host without port, parameters and header part, lower case.
+ static func bareHost(_ s: String) -> String {
+ String(s.prefix { !";?>:".contains($0) }).trimmingCharacters(in: .whitespaces).lowercased()
+ }
+
+ func matches(user other: String, host otherHost: String?) -> Bool {
+ guard host == otherHost.map({ $0.lowercased() }) else { return false }
+ if Self.isNumber(user) || Self.isNumber(other) {
+ guard Self.isNumber(user), Self.isNumber(other) else { return false }
+ return Self.sameNumber(user, DialString.normalizeNumber(other))
+ }
+ return user == other.lowercased()
+ }
+
+ /// Equal digits, or one number is the tail of the other and at least `minSuffixDigits` long (country prefix, trunk
+ /// prefix). `*` and `#` codes are compared as written.
+ static func sameNumber(_ a: String, _ b: String) -> Bool {
+ if a == b { return true }
+ let da = a.filter(\.isNumber), db = b.filter(\.isNumber)
+ guard !da.isEmpty, !db.isEmpty, a.allSatisfy({ $0.isNumber || $0 == "+" }), b.allSatisfy({ $0.isNumber || $0 == "+" }) else { return false }
+ if da == db { return true }
+ let (short, long) = da.count <= db.count ? (da, db) : (db, da)
+ return short.count >= minSuffixDigits && long.hasSuffix(short)
+ }
+}
+
+public struct Message: Codable, Identifiable, Equatable, Sendable {
+ public var id: UUID
+ public var conversationID: UUID
+ public var direction: MessageDirection
+ public var text: String
+ /// Received, or when sending started.
+ public var at: Date
+ /// Incoming messages are always `.sent`.
+ public var state: MessageState
+ /// For `.failed`: the SIP code, or 0 for a local failure.
+ public var failureCode: Int?
+ public var failureReason: String?
+
+ public init(
+ id: UUID = UUID(),
+ conversationID: UUID,
+ direction: MessageDirection,
+ text: String,
+ at: Date = Date(),
+ state: MessageState = .sent,
+ failureCode: Int? = nil,
+ failureReason: String? = nil
+ ) {
+ self.id = id
+ self.conversationID = conversationID
+ self.direction = direction
+ self.text = text
+ self.at = at
+ self.state = state
+ self.failureCode = failureCode
+ self.failureReason = failureReason
+ }
+}
diff --git a/Sources/MacroSIPCore/Product.swift b/Sources/MacroSIPCore/Product.swift
index 2d60087..365faa0 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.2.0"
+ public static let fallbackVersion = "26.3.0"
}
diff --git a/Sources/MacroSIPCore/Storage/MessageStore.swift b/Sources/MacroSIPCore/Storage/MessageStore.swift
new file mode 100644
index 0000000..5ff6d41
--- /dev/null
+++ b/Sources/MacroSIPCore/Storage/MessageStore.swift
@@ -0,0 +1,272 @@
+import Foundation
+import os
+
+/// messages.json as stored: conversations and their messages in one file. Each array is read element by element: a
+/// record that cannot be decoded is skipped and counted, the rest stays (as `ContactList` does for contacts).
+struct MessageFile: Codable, Sendable {
+ var conversations: [Conversation] = []
+ var messages: [Message] = []
+ /// Records the decoder could not read (only set by decoding).
+ var skipped = 0
+
+ init(conversations: [Conversation] = [], messages: [Message] = []) {
+ self.conversations = conversations
+ self.messages = messages
+ }
+
+ private enum CodingKeys: String, CodingKey { case conversations, messages }
+ private struct Skip: Decodable {}
+
+ init(from decoder: Decoder) throws {
+ let c = try decoder.container(keyedBy: CodingKeys.self)
+ func elements(_ key: CodingKeys, _ type: T.Type) throws -> ([T], Int) {
+ guard c.contains(key) else { return ([], 0) }
+ var list = try c.nestedUnkeyedContainer(forKey: key)
+ var out: [T] = [], bad = 0
+ while !list.isAtEnd {
+ if let item = try? list.decode(T.self) { out.append(item) }
+ else { _ = try? list.decode(Skip.self); bad += 1 }
+ }
+ return (out, bad)
+ }
+ let (conversations, badConversations) = try elements(.conversations, Conversation.self)
+ let (messages, badMessages) = try elements(.messages, Message.self)
+ self.conversations = conversations
+ self.messages = messages
+ skipped = badConversations + badMessages
+ }
+
+ func encode(to encoder: Encoder) throws {
+ var c = encoder.container(keyedBy: CodingKeys.self)
+ try c.encode(conversations, forKey: .conversations)
+ try c.encode(messages, forKey: .messages)
+ }
+}
+
+/// Conversations and messages (messages.json). The whole file is held in memory after the first access and written
+/// through on every change: one write per operation, no reads. Safe from any thread.
+public final class MessageStore: @unchecked Sendable {
+ private let store: JSONStore
+ private let directory: URL
+ private let contacts: ContactStore?
+ private let limit: @Sendable () -> Int
+ private let lock = NSLock()
+ private var cache: MessageFile?
+ private static let log = Logger(subsystem: "com.hsmm.macrosip", category: "messages")
+
+ /// `contacts`: used to resolve `contactID` when a conversation is created. `limit`: max messages kept overall
+ /// (default 5000); the oldest are dropped and conversations left without messages are pruned.
+ public init(directory: URL, contacts: ContactStore? = nil, limit: @escaping @Sendable () -> Int = { 5000 }) {
+ self.directory = directory
+ store = JSONStore(directory: directory, name: "messages", default: MessageFile())
+ self.contacts = contacts
+ self.limit = limit
+ }
+
+ // MARK: - Access
+
+ /// The file, read on first use. A file with unreadable records keeps a copy of the original and is rewritten
+ /// without them; a file that is not JSON at all is moved aside by `JSONStore.load`.
+ private func loaded() -> MessageFile {
+ if let cache { return cache }
+ var file = store.load()
+ if file.skipped > 0 {
+ if let data = try? Data(contentsOf: store.fileURL) {
+ let stamp = ISO8601DateFormatter().string(from: Date()).replacingOccurrences(of: ":", with: "-")
+ let copy = directory.appendingPathComponent("messages.damaged-\(stamp).json")
+ try? data.write(to: copy)
+ Self.log.error("messages.json: \(file.skipped) unreadable records skipped, original kept as \(copy.lastPathComponent, privacy: .public)")
+ }
+ file.skipped = 0
+ try? store.save(file)
+ }
+ cache = file
+ return file
+ }
+
+ private func read(_ body: (MessageFile) -> T) -> T {
+ lock.lock(); defer { lock.unlock() }
+ return body(loaded())
+ }
+
+ /// Applies `body` to a copy, writes it, and only then keeps it: a failed write leaves memory and file as they were.
+ @discardableResult
+ private func change(_ body: (inout MessageFile) throws -> T) throws -> T {
+ lock.lock(); defer { lock.unlock() }
+ var file = loaded()
+ let result = try body(&file)
+ try store.save(file)
+ cache = file
+ return result
+ }
+
+ /// Newest activity first.
+ public func conversations() -> [Conversation] {
+ read { $0.conversations.sorted { $0.lastActivityAt > $1.lastActivityAt } }
+ }
+
+ /// Oldest first; messages with equal dates keep their insertion order.
+ public func messages(in conversation: UUID) -> [Message] {
+ read { Self.ordered($0.messages.filter { $0.conversationID == conversation }) }
+ }
+
+ public func allMessages() -> [Message] { read { Self.ordered($0.messages) } }
+
+ /// The newest message of every conversation (what the list previews), in one pass.
+ public func lastMessages() -> [UUID: Message] {
+ read { file in
+ var best: [UUID: (Message, Int)] = [:]
+ for (i, m) in file.messages.enumerated() {
+ if let b = best[m.conversationID], (b.0.at, b.1) > (m.at, i) { continue }
+ best[m.conversationID] = (m, i)
+ }
+ return best.mapValues(\.0)
+ }
+ }
+
+ public var unreadTotal: Int { read { $0.conversations.reduce(0) { $0 + $1.unread } } }
+
+ private static func ordered(_ list: [Message]) -> [Message] {
+ list.enumerated().sorted { ($0.element.at, $0.offset) < ($1.element.at, $1.offset) }.map(\.element)
+ }
+
+ // MARK: - Conversations
+
+ /// Finds the conversation of (account, peer) or creates it. The peer is told apart by `ConversationAddress`: the user
+ /// (numbers by their digits, so `+375291234567` and `375 29 123-45-67` meet) and the host where it matters (an explicit
+ /// host other than `accountDomain`, or any host of a non-numeric user). A non-empty `remoteURI` or `displayName`
+ /// replaces the stored one. `remoteNumber` is the user part; `remoteURI` may carry the host.
+ @discardableResult
+ public func conversation(account: AccountID, remoteNumber: String, remoteURI: String, displayName: String?,
+ accountDomain: String = "") throws -> Conversation {
+ try change { file in
+ Self.findOrCreate(&file, account: account, remoteNumber: remoteNumber, remoteURI: remoteURI, displayName: displayName,
+ accountDomain: accountDomain, contactID: contacts?.findUnique(byNumber: remoteNumber)?.id)
+ }
+ }
+
+ /// `conversation(...)` and the first message in one write; `message` gets the conversation's id. Nothing is
+ /// stored when the write fails.
+ @discardableResult
+ public func conversation(account: AccountID, remoteNumber: String, remoteURI: String, displayName: String?,
+ accountDomain: String = "", appending message: (UUID) -> Message) throws -> (Conversation, Message) {
+ let max = Swift.max(1, limit())
+ let contactID = contacts?.findUnique(byNumber: remoteNumber)?.id
+ return try change { file in
+ let conv = Self.findOrCreate(&file, account: account, remoteNumber: remoteNumber, remoteURI: remoteURI, displayName: displayName,
+ accountDomain: accountDomain, contactID: contactID)
+ let m = message(conv.id)
+ Self.appendLocked(&file, m, max: max)
+ return (file.conversations.first { $0.id == conv.id } ?? conv, m)
+ }
+ }
+
+ private static func findOrCreate(_ file: inout MessageFile, account: AccountID, remoteNumber: String, remoteURI: String,
+ displayName: String?, accountDomain: String, contactID: UUID?) -> Conversation {
+ let key = ConversationAddress(number: remoteNumber, uri: remoteURI, accountDomain: accountDomain)
+ if let i = file.conversations.firstIndex(where: { $0.matches(account: account, address: key) }) {
+ if !remoteURI.isEmpty { file.conversations[i].remoteURI = remoteURI }
+ if let name = displayName, !name.isEmpty { file.conversations[i].remoteDisplayName = name }
+ if file.conversations[i].contactID == nil { file.conversations[i].contactID = contactID }
+ return file.conversations[i]
+ }
+ let c = Conversation(
+ accountID: account, remoteNumber: remoteNumber, remoteURI: remoteURI, remoteHost: key.host,
+ remoteDisplayName: (displayName?.isEmpty ?? true) ? nil : displayName,
+ contactID: contactID, lastActivityAt: Date(), unread: 0)
+ file.conversations.append(c)
+ return c
+ }
+
+ // MARK: - Messages
+
+ /// Adds the message, bumps the conversation's activity and, for an incoming one, its unread count.
+ @discardableResult
+ public func append(_ message: Message) throws -> Message {
+ let max = Swift.max(1, limit())
+ try change { Self.appendLocked(&$0, message, max: max) }
+ return message
+ }
+
+ private static func appendLocked(_ file: inout MessageFile, _ message: Message, max: Int) {
+ file.messages.append(message)
+ if let i = file.conversations.firstIndex(where: { $0.id == message.conversationID }) {
+ if message.at > file.conversations[i].lastActivityAt { file.conversations[i].lastActivityAt = message.at }
+ if message.direction == .incoming { file.conversations[i].unread += 1 }
+ }
+ prune(&file, max: max)
+ }
+
+ private static func prune(_ file: inout MessageFile, max: Int) {
+ if file.messages.count > max {
+ let drop = file.messages.enumerated()
+ .sorted { ($0.element.at, $0.offset) < ($1.element.at, $1.offset) }
+ .prefix(file.messages.count - max).map(\.offset)
+ let dropSet = Set(drop)
+ file.messages = file.messages.enumerated().filter { !dropSet.contains($0.offset) }.map(\.element)
+ let alive = Set(file.messages.map(\.conversationID))
+ file.conversations.removeAll { !alive.contains($0.id) }
+ clampUnread(&file)
+ }
+ }
+
+ /// A conversation never has more unread messages than incoming messages left in it.
+ private static func clampUnread(_ file: inout MessageFile) {
+ var incoming: [UUID: Int] = [:]
+ for m in file.messages where m.direction == .incoming { incoming[m.conversationID, default: 0] += 1 }
+ for i in file.conversations.indices where file.conversations[i].unread > (incoming[file.conversations[i].id] ?? 0) {
+ file.conversations[i].unread = incoming[file.conversations[i].id] ?? 0
+ }
+ }
+
+ /// Changes one message (state transitions). A message that is gone is ignored.
+ public func update(_ id: UUID, _ change: (inout Message) -> Void) throws {
+ try self.change { file in
+ if let i = file.messages.firstIndex(where: { $0.id == id }) { change(&file.messages[i]) }
+ }
+ }
+
+ /// Retry: `old` is removed and `new` added in one write, so the message moves to the end with its new time.
+ /// Nothing changes when the write fails.
+ public func replace(message old: UUID, with new: Message) throws {
+ let max = Swift.max(1, limit())
+ try change { file in
+ file.messages.removeAll { $0.id == old }
+ Self.appendLocked(&file, new, max: max)
+ Self.clampUnread(&file)
+ }
+ }
+
+ public func markRead(_ conversation: UUID) throws {
+ try change { file in
+ if let i = file.conversations.firstIndex(where: { $0.id == conversation }) { file.conversations[i].unread = 0 }
+ }
+ }
+
+ public func remove(message id: UUID) throws {
+ try change { file in
+ file.messages.removeAll { $0.id == id }
+ Self.clampUnread(&file)
+ }
+ }
+
+ public func remove(conversation id: UUID) throws {
+ try change { file in
+ file.conversations.removeAll { $0.id == id }
+ file.messages.removeAll { $0.conversationID == id }
+ }
+ }
+
+ public func clear() throws { try change { $0 = MessageFile() } }
+
+ /// At launch: every message still `.sending` becomes `.failed(0, "interrupted")` so the UI can offer Retry.
+ public func failInterruptedSends() throws {
+ try change { file in
+ for i in file.messages.indices where file.messages[i].state == .sending {
+ file.messages[i].state = .failed
+ file.messages[i].failureCode = 0
+ file.messages[i].failureReason = "interrupted"
+ }
+ }
+ }
+}
diff --git a/Sources/macrosip-cli/main.swift b/Sources/macrosip-cli/main.swift
index 8e0ed12..7650c1d 100644
--- a/Sources/macrosip-cli/main.swift
+++ b/Sources/macrosip-cli/main.swift
@@ -128,6 +128,14 @@ func describe(_ e: EngineEvent) -> String {
case let .network(state): return "[network] \(state == .online ? "online" : "offline")"
case let .voicemail(id, waiting, new, old):
return "[voicemail] \(id.raw.uuidString.prefix(8)) \(waiting ? "waiting" : "none") new=\(new) old=\(old)"
+ case let .messageReceived(m):
+ let from = m.remote.displayName.map { "\"\($0)\" <\(m.remote.uri)>" } ?? m.remote.uri
+ return "[messageReceived] \(m.accountID.raw.uuidString.prefix(8)) from \(from): \(m.text)"
+ case let .messageStatus(id, result):
+ switch result {
+ case let .accepted(code): return "[messageStatus] \(id) accepted \(code)"
+ case let .failed(code, reason): return "[messageStatus] \(id) failed \(code) \(reason)"
+ }
case let .log(level, text):
return text.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline)
.map { " pj\(level)| \($0)" }.joined(separator: "\n")
diff --git a/Tests/MacroSIPCoreTests/EngineMessageTests.swift b/Tests/MacroSIPCoreTests/EngineMessageTests.swift
new file mode 100644
index 0000000..76569e7
--- /dev/null
+++ b/Tests/MacroSIPCoreTests/EngineMessageTests.swift
@@ -0,0 +1,652 @@
+import Foundation
+import os
+import Testing
+@testable import MacroSIPCore
+
+// Text messages (docs/ENGINE.md "Text messages (SIP MESSAGE)"): sending with each outcome,
+// receiving (Cyrillic from chan_dongle, the 415 filter, account mapping, inside a call),
+// validation, and the pure mappings.
+
+// MARK: - MESSAGE stub
+
+/// A SIP peer on 127.0.0.1 (one UDP socket, random port) for the MESSAGE tests. Every MESSAGE
+/// it receives is recorded byte for byte and answered with `answer` (a status line such as
+/// "404 Not Found"; nil = no answer at all, so the sender times out). It answers an INVITE with
+/// 200 and a PCMU SDP (it never sends RTP) and remembers that dialog for `sendInDialogMessage`;
+/// any other request gets 200. It sends MESSAGEs of its own as Asterisk/chan_dongle does
+/// (`sendMessage`) and records the status lines of the answers by Call-ID.
+final class MessageStub: Sendable {
+ struct Request: Sendable {
+ var requestLine: String
+ /// Header lines as received ("Content-Type: text/plain;charset=utf-8").
+ var headers: [String]
+ var body: [UInt8]
+ /// Size of the whole datagram.
+ var size: Int
+
+ /// Value of the first header called `name` (case-insensitive), trimmed.
+ func header(_ name: String) -> String? {
+ for line in headers {
+ guard let colon = line.firstIndex(of: ":"),
+ line[..(initialState: "200 OK")
+ private let received = OSAllocatedUnfairLock(initialState: [Request]())
+ private let answers = OSAllocatedUnfairLock(initialState: [Response]())
+ private let dialog = OSAllocatedUnfairLock