Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : Local Chat9// File : Services/LocalAPIServer/Sources/HTTPConnection.swift10// Description : One HTTP/1.1 connection on Network.framework: inbound byte11// stream, request parsing, full and chunked (SSE) responses.12// Module : Services13// Repository : https://git.spboucher.ai/local-chat14// Created : 2026-11-2015// Last Modified : 2026-11-2016//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author : Simon-Pierre Boucher22// Position : Professor of Finance23// Institution : Université du Québec en Outaouais (UQO)24// Department : Département des sciences administratives25// Organization : SP Boucher26//27// Website : https://spboucher.ai28// Git : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General : info@spboucher.ai35// Professional : contact@spboucher.ai36// Direct : simon@spboucher.ai37// Research : research@spboucher.ai38// Development : dev@spboucher.ai39// Support : support@spboucher.ai40// Security/Admin : admin@spboucher.ai41// Notifications : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification : Public68// Distribution : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License : None specified (no license file in this repository)82// Maintainer : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import Foundation90import LocalChatCore91import Network9293final class HTTPConnection: @unchecked Sendable {94 let id = UUID()95 let connection: NWConnection96 let remoteAddress: String?97 let inbound: AsyncStream<Data>98 private let inboundContinuation: AsyncStream<Data>.Continuation99 private let lock = NSLock()100 private var task: Task<Void, Never>?101 private var closed = false102 private var onClose: (@Sendable (UUID) -> Void)?103104 init(_ connection: NWConnection) {105 self.connection = connection106 if case .hostPort(let host, _) = connection.endpoint {107 var text = "\(host)"108 if let zone = text.firstIndex(of: "%") { text = String(text[..<zone]) }109 remoteAddress = text110 } else { remoteAddress = nil }111 (inbound, inboundContinuation) = AsyncStream<Data>.makeStream(bufferingPolicy: .unbounded)112 }113114 func start(queue: DispatchQueue, onClose: @escaping @Sendable (UUID) -> Void, serve: @escaping @Sendable (HTTPConnection) async -> Void) {115 lock.withLock { self.onClose = onClose }116 connection.stateUpdateHandler = { [weak self] state in117 guard let self else { return }118 switch state {119 case .ready:120 self.receive()121 let task = Task { await serve(self); self.close() }122 let alreadyClosed = self.lock.withLock { () -> Bool in self.task = task; return self.closed }123 if alreadyClosed { task.cancel() }124 case .failed, .cancelled: self.finish()125 default: break126 }127 }128 connection.start(queue: queue)129 }130131 private func receive() {132 connection.receive(minimumIncompleteLength: 1, maximumLength: 256 * 1024) { [weak self] data, _, isComplete, error in133 guard let self else { return }134 if let data, !data.isEmpty { self.inboundContinuation.yield(data) }135 if isComplete || error != nil { self.finish(); self.connection.cancel() } // the client went away: cancel the work in progress136 else { self.receive() }137 }138 }139140 /// Ends the inbound stream and cancels the request being served (which cancels any running generation).141 private func finish() {142 let (task, callback) = lock.withLock { () -> (Task<Void, Never>?, (@Sendable (UUID) -> Void)?) in143 guard !closed else { return (nil, nil) }144 closed = true145 defer { onClose = nil }146 return (self.task, onClose)147 }148 inboundContinuation.finish()149 task?.cancel()150 callback?(id)151 }152153 var isClosed: Bool { lock.withLock { closed } }154155 func send(_ data: Data) async throws {156 if isClosed { throw CancellationError() }157 try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in158 connection.send(content: data, completion: .contentProcessed { error in159 if let error { continuation.resume(throwing: error) } else { continuation.resume() }160 })161 }162 }163164 /// Closes after pending sends were handed to the network stack.165 func close() {166 guard !isClosed else { return }167 connection.send(content: nil, contentContext: .finalMessage, isComplete: true, completion: .contentProcessed { [weak self] _ in168 self?.connection.cancel()169 })170 finish()171 }172173 func forceClose() { connection.cancel(); finish() }174}175176enum HTTPParseError: Error { case badRequest(String), headerTooLarge, bodyTooLarge, lengthRequired, unsupportedEncoding }177178enum HTTPParser {179 static let headEnd = Data("\r\n\r\n".utf8)180181 struct Head { var method: String; var path: String; var query: [String: String]; var headers: [String: String]; var version: String; var contentLength: Int }182183 static func parseHead(_ data: Data) throws -> Head {184 guard let text = String(data: data, encoding: .utf8) ?? String(data: data, encoding: .isoLatin1) else { throw HTTPParseError.badRequest("Unreadable request head.") }185 var lines = text.components(separatedBy: "\r\n")186 guard !lines.isEmpty else { throw HTTPParseError.badRequest("Empty request.") }187 let requestLine = lines.removeFirst().split(separator: " ", omittingEmptySubsequences: true)188 guard requestLine.count == 3, requestLine[2].hasPrefix("HTTP/1.") else { throw HTTPParseError.badRequest("Malformed request line.") }189 var headers: [String: String] = [:]190 for line in lines where !line.isEmpty {191 guard let colon = line.firstIndex(of: ":") else { throw HTTPParseError.badRequest("Malformed header.") }192 let name = line[..<colon].trimmingCharacters(in: .whitespaces).lowercased()193 let value = line[line.index(after: colon)...].trimmingCharacters(in: .whitespaces)194 headers[name] = headers[name].map { "\($0), \(value)" } ?? value195 }196 let target = String(requestLine[1])197 var path = target; var query: [String: String] = [:]198 if let mark = target.firstIndex(of: "?") {199 path = String(target[..<mark])200 for pair in target[target.index(after: mark)...].split(separator: "&") {201 let kv = pair.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false)202 let key = String(kv[0]).replacingOccurrences(of: "+", with: " ").removingPercentEncoding ?? String(kv[0])203 let value = kv.count > 1 ? (String(kv[1]).replacingOccurrences(of: "+", with: " ").removingPercentEncoding ?? String(kv[1])) : ""204 query[key] = value205 }206 }207 path = path.removingPercentEncoding ?? path208 if path.count > 1, path.hasSuffix("/") { path.removeLast() }209 guard path.hasPrefix("/"), !path.contains("..") else { throw HTTPParseError.badRequest("Invalid path.") }210 if let encoding = headers["transfer-encoding"], encoding.lowercased() != "identity" { throw HTTPParseError.unsupportedEncoding }211 var length = 0212 if let raw = headers["content-length"] {213 guard let n = Int(raw), n >= 0 else { throw HTTPParseError.badRequest("Invalid Content-Length.") }214 length = n215 }216 return Head(method: requestLine[0].uppercased(), path: path, query: query, headers: headers, version: String(requestLine[2]), contentLength: length)217 }218219 static func statusText(_ code: Int) -> String {220 switch code {221 case 200: "OK"; case 201: "Created"; case 204: "No Content"; case 400: "Bad Request"; case 401: "Unauthorized"; case 403: "Forbidden"222 case 404: "Not Found"; case 405: "Method Not Allowed"; case 408: "Request Timeout"; case 409: "Conflict"; case 411: "Length Required"223 case 413: "Content Too Large"; case 422: "Unprocessable Content"; case 429: "Too Many Requests"; case 431: "Request Header Fields Too Large"224 case 500: "Internal Server Error"; case 501: "Not Implemented"; case 503: "Service Unavailable"225 default: code < 400 ? "OK" : "Error"226 }227 }228229 static let dateFormatter: DateFormatter = {230 let f = DateFormatter(); f.locale = Locale(identifier: "en_US_POSIX"); f.timeZone = TimeZone(identifier: "GMT")231 f.dateFormat = "EEE, dd MMM yyyy HH:mm:ss 'GMT'"; return f232 }()233}234235/// Writes one response on a connection: either a complete body, or a chunked stream (used for SSE).236struct ResponseWriter: Sendable {237 let connection: HTTPConnection238 let keepAlive: Bool239 let extraHeaders: [String: String] // CORS headers decided by the router240 let isHead: Bool241242 private func head(_ status: Int, _ headers: [String: String]) -> Data {243 var all = ["Server": "LocalChat", "Date": HTTPParser.dateFormatter.string(from: Date()), "Connection": keepAlive ? "keep-alive" : "close",244 "X-Content-Type-Options": "nosniff"]245 for (k, v) in extraHeaders { all[k] = v }246 for (k, v) in headers { all[k] = v }247 var text = "HTTP/1.1 \(status) \(HTTPParser.statusText(status))\r\n"248 for (k, v) in all.sorted(by: { $0.key < $1.key }) { text += "\(k): \(v.replacingOccurrences(of: "\r", with: "").replacingOccurrences(of: "\n", with: ""))\r\n" }249 return Data((text + "\r\n").utf8)250 }251252 func respond(_ response: HTTPResponseMessage) async throws {253 var headers = response.headers254 headers["Content-Length"] = String(response.body.count)255 var out = head(response.status, headers)256 if !isHead { out.append(response.body) }257 try await connection.send(out)258 }259260 func beginStream(status: Int = 200, headers: [String: String]) async throws {261 var headers = headers; headers["Transfer-Encoding"] = "chunked"262 try await connection.send(head(status, headers))263 }264265 func chunk(_ data: Data) async throws {266 guard !data.isEmpty else { return }267 var out = Data(String(data.count, radix: 16).utf8); out.append(contentsOf: [0x0D, 0x0A]); out.append(data); out.append(contentsOf: [0x0D, 0x0A])268 try await connection.send(out)269 }270271 func endStream() async throws { try await connection.send(Data("0\r\n\r\n".utf8)) }272}273