import Foundation import CCurlShim /// Una connessione salvata (Ctrl+F). La password sta nel Portachiavi, non qui. public struct FtpConnection: Codable, Equatable, Identifiable { public var id = UUID() /// "Cartella|Nome" per le connessioni dentro una cartella, come in TC. public var name: String /// "ftp.sito.it" oppure "ftp.sito.it:2121". public var host: String /// FTP con TLS esplicito (AUTH TLS), la casella "SSL/TLS" di TC. public var tls = false /// TLS implicito (porta 990), "ftpis://" in TC. public var implicitTLS = false public var user = "" public var remoteDir = "" public var localDir = "" public var passive = true public init(name: String, host: String) { self.name = name self.host = host } } public struct FtpEntry: Equatable { public let name: String public let isDirectory: Bool public let isLink: Bool public let size: Int64 public let modified: Date? public init(name: String, isDirectory: Bool, isLink: Bool = false, size: Int64 = 0, modified: Date? = nil) { self.name = name self.isDirectory = isDirectory self.isLink = isLink self.size = size self.modified = modified } } public struct FtpError: LocalizedError { public let code: Int public let message: String public var errorDescription: String? { message } /// Il certificato TLS del server non è valido (capita con gli hosting condivisi). public var isCertificateProblem: Bool { code == 60 || code == 51 } public var isLoginProblem: Bool { code == 67 } } /// Una sessione FTP: una sola connessione di controllo, usata da un'operazione alla volta. public final class FtpSession { public let connection: FtpConnection private let password: String private let lock = NSLock() private let handle: UnsafeMutableRawPointer private let errorBuffer = UnsafeMutablePointer.allocate(capacity: Int(CURL_ERROR_SIZE) + 1) /// Accetta certificati non validi (dopo che l'utente ha detto sì). public var allowInvalidCertificate = false private var mlsdSupported: Bool? public init(connection: FtpConnection, password: String) { curl_global_init(Int(CURL_GLOBAL_DEFAULT)) self.connection = connection self.password = password handle = curl_easy_init() } deinit { curl_easy_cleanup(handle) errorBuffer.deallocate() } // MARK: - Indirizzi private var scheme: String { connection.implicitTLS ? "ftps" : "ftp" } private var hostPart: String { var h = connection.host for prefix in ["ftp://", "ftps://", "ftpes://", "ftpis://"] where h.lowercased().hasPrefix(prefix) { h = String(h.dropFirst(prefix.count)) } return h.hasSuffix("/") ? String(h.dropLast()) : h } /// "/cartella/file" -> "ftp://host/cartella/file" con i caratteri speciali codificati. func url(_ path: String, directory: Bool = false) -> String { let parts = path.split(separator: "/").map { String($0).addingPercentEncoding(withAllowedCharacters: .urlPathAllowed.subtracting(CharacterSet(charactersIn: "/;?#"))) ?? String($0) } // "%2F" all'inizio = percorso assoluto dalla radice del server, non dalla home dell'utente. var u = "\(scheme)://\(hostPart)/%2F" + parts.joined(separator: "/") if directory && !u.hasSuffix("/") { u += "/" } return u } // MARK: - Operazioni /// Contenuto di una cartella. Prova MLSD (date precise, in UTC), altrimenti LIST. public func list(_ path: String) throws -> [FtpEntry] { if mlsdSupported != false { do { let data = try fetch(url(path, directory: true), customRequest: "MLSD") mlsdSupported = true return FtpListParser.parseMLSD(data) } catch let e as FtpError where e.code != 67 && e.code != 7 && e.code != 28 && !e.isCertificateProblem { mlsdSupported = false } } return FtpListParser.parseLIST(try fetch(url(path, directory: true), customRequest: nil)) } private func fetch(_ u: String, customRequest: String?) throws -> Data { let sink = Sink() try perform(u) { h in if let customRequest { mc_setopt_str(h, CURLOPT_CUSTOMREQUEST, customRequest) } mc_set_write(h, Sink.writeCallback, Unmanaged.passUnretained(sink).toOpaque()) } return sink.data } /// Scarica un file. `progress` riceve i byte arrivati e restituisce false per interrompere. public func download(_ remotePath: String, to local: URL, progress: @escaping (Int64) -> Bool) throws { FileManager.default.createFile(atPath: local.path, contents: nil) guard let fh = try? FileHandle(forWritingTo: local) else { throw FtpError(code: -1, message: "Non riesco a scrivere \(local.lastPathComponent)") } defer { try? fh.close() } let sink = Sink() sink.file = fh sink.progress = progress do { try perform(url(remotePath)) { h in mc_set_write(h, Sink.writeCallback, Unmanaged.passUnretained(sink).toOpaque()) mc_set_progress(h, Sink.progressCallback, Unmanaged.passUnretained(sink).toOpaque()) } } catch { try? fh.close() try? FileManager.default.removeItem(at: local) throw error } } /// Carica un file, creando le cartelle che mancano. public func upload(_ local: URL, to remotePath: String, progress: @escaping (Int64) -> Bool) throws { guard let fh = try? FileHandle(forReadingFrom: local) else { throw FtpError(code: -1, message: "Non riesco a leggere \(local.lastPathComponent)") } defer { try? fh.close() } let size = (try? local.resourceValues(forKeys: [.fileSizeKey]).fileSize).map { Int64($0 ?? 0) } ?? 0 let source = Source(file: fh) source.progress = progress try perform(url(remotePath)) { h in mc_setopt_long(h, CURLOPT_UPLOAD, 1) mc_setopt_long(h, CURLOPT_FTP_CREATE_MISSING_DIRS, Int(CURLFTP_CREATE_DIR_RETRY.rawValue)) mc_setopt_off(h, CURLOPT_INFILESIZE_LARGE, curl_off_t(size)) mc_set_read(h, Source.readCallback, Unmanaged.passUnretained(source).toOpaque()) mc_set_progress(h, Source.progressCallback, Unmanaged.passUnretained(source).toOpaque()) } } /// La cartella in cui il server ci mette dopo l'accesso (per le connessioni senza "cartella remota"). public func homeDirectory() throws -> String { var home = "/" try perform("\(scheme)://\(hostPart)/") { h in mc_setopt_long(h, CURLOPT_NOBODY, 1) } lock.lock() var p: UnsafeMutablePointer? if mc_getinfo_str(handle, CURLINFO_FTP_ENTRY_PATH, &p) == CURLE_OK, let p { home = String(cString: p) } lock.unlock() return home.isEmpty ? "/" : home } public func makeDirectory(_ path: String) throws { try commands(["MKD \(path)"]) } public func deleteFile(_ path: String) throws { try commands(["DELE \(path)"]) } public func removeDirectory(_ path: String) throws { try commands(["RMD \(path)"]) } public func rename(_ from: String, to: String) throws { try commands(["RNFR \(from)", "RNTO \(to)"]) } /// Elimina una cartella con tutto il contenuto. public func deleteRecursively(_ path: String, isDirectory: Bool, isCancelled: () -> Bool = { false }) throws { guard isDirectory else { try deleteFile(path); return } for e in try list(path) { if isCancelled() { return } try deleteRecursively(path + "/" + e.name, isDirectory: e.isDirectory && !e.isLink, isCancelled: isCancelled) } try removeDirectory(path) } /// Comandi FTP grezzi (QUOTE), eseguiti dopo il collegamento. private func commands(_ cmds: [String]) throws { var list: UnsafeMutablePointer? for c in cmds { list = curl_slist_append(list, c) } defer { curl_slist_free_all(list) } try perform(url("/", directory: true)) { h in mc_setopt_ptr(h, CURLOPT_QUOTE, UnsafeMutableRawPointer(list)) mc_setopt_long(h, CURLOPT_NOBODY, 1) } } private func perform(_ u: String, configure: (UnsafeMutableRawPointer) -> Void) throws { lock.lock() defer { lock.unlock() } let h = handle curl_easy_reset(h) mc_setopt_str(h, CURLOPT_URL, u) mc_setopt_str(h, CURLOPT_USERNAME, connection.user.isEmpty ? "anonymous" : connection.user) mc_setopt_str(h, CURLOPT_PASSWORD, password) mc_setopt_long(h, CURLOPT_NOSIGNAL, 1) mc_setopt_long(h, CURLOPT_CONNECTTIMEOUT, 20) mc_setopt_long(h, CURLOPT_SERVER_RESPONSE_TIMEOUT, 60) mc_setopt_long(h, CURLOPT_TCP_KEEPALIVE, 1) mc_setopt_long(h, CURLOPT_FTP_USE_EPSV, 1) if !connection.passive { mc_setopt_str(h, CURLOPT_FTPPORT, "-") } if connection.tls && !connection.implicitTLS { mc_setopt_long(h, CURLOPT_USE_SSL, Int(CURLUSESSL_ALL.rawValue)) } if allowInvalidCertificate { mc_setopt_long(h, CURLOPT_SSL_VERIFYPEER, 0) mc_setopt_long(h, CURLOPT_SSL_VERIFYHOST, 0) } if ProcessInfo.processInfo.environment["MC_FTP_DEBUG"] != nil { mc_setopt_long(h, CURLOPT_VERBOSE, 1) } errorBuffer[0] = 0 mc_setopt_ptr(h, CURLOPT_ERRORBUFFER, UnsafeMutableRawPointer(errorBuffer)) configure(h) let rc = curl_easy_perform(h) guard rc == CURLE_OK else { let detail = String(cString: errorBuffer) let base = String(cString: curl_easy_strerror(rc)) throw FtpError(code: Int(rc.rawValue), message: FtpSession.italian(Int(rc.rawValue), detail.isEmpty ? base : detail)) } } static func italian(_ code: Int, _ detail: String) -> String { switch code { case 6: return "Server non trovato (\(detail))" case 7: return "Il server non risponde (\(detail))" case 9: return "Accesso negato alla cartella (\(detail))" case 28: return "Tempo scaduto (\(detail))" case 42: return "Interrotto" case 51, 60: return "Il certificato del server non è valido (\(detail))" case 67: return "Utente o password sbagliati (\(detail))" case 78: return "File o cartella non trovati (\(detail))" default: return detail } } } // MARK: - Callback di libcurl private final class Sink { var data = Data() var file: FileHandle? var received: Int64 = 0 var progress: ((Int64) -> Bool)? var stop = false static let writeCallback: mc_io_cb = { ptr, size, n, ud in guard let ptr, let ud else { return 0 } let s = Unmanaged.fromOpaque(ud).takeUnretainedValue() let count = size * n let chunk = Data(bytes: ptr, count: count) if let f = s.file { do { try f.write(contentsOf: chunk) } catch { return 0 } } else { s.data.append(chunk) } s.received += Int64(count) return s.stop ? 0 : count } static let progressCallback: mc_progress_cb = { ud, _, now, _, _ in guard let ud else { return 0 } let s = Unmanaged.fromOpaque(ud).takeUnretainedValue() if let p = s.progress, !p(Int64(now)) { s.stop = true; return 1 } return 0 } } private final class Source { let file: FileHandle var progress: ((Int64) -> Bool)? init(file: FileHandle) { self.file = file } static let readCallback: mc_io_cb = { ptr, size, n, ud in guard let ptr, let ud else { return 0 } let s = Unmanaged.fromOpaque(ud).takeUnretainedValue() guard let chunk = try? s.file.read(upToCount: size * n), !chunk.isEmpty else { return 0 } chunk.withUnsafeBytes { raw in ptr.withMemoryRebound(to: UInt8.self, capacity: chunk.count) { dst in raw.copyBytes(to: UnsafeMutableBufferPointer(start: dst, count: chunk.count)) } } return chunk.count } static let progressCallback: mc_progress_cb = { ud, _, _, _, now in guard let ud else { return 0 } let s = Unmanaged.fromOpaque(ud).takeUnretainedValue() if let p = s.progress, !p(Int64(now)) { return 1 } return 0 } } // MARK: - Elenchi del server public enum FtpListParser { /// MLSD: "type=file;size=123;modify=20230101120000; nome" public static func parseMLSD(_ data: Data) -> [FtpEntry] { let text = String(decoding: data, as: UTF8.self) var out: [FtpEntry] = [] let f = DateFormatter() f.dateFormat = "yyyyMMddHHmmss" f.timeZone = TimeZone(identifier: "UTC") for raw in text.split(whereSeparator: \.isNewline) { let line = String(raw) guard let sep = line.range(of: "; ") ?? line.range(of: " ") else { continue } let factsPart = line[.. nome"). public static func parseLIST(_ data: Data) -> [FtpEntry] { let text = String(data: data, encoding: .utf8) ?? String(data: data, encoding: .windowsCP1252) ?? "" var out: [FtpEntry] = [] for raw in text.split(whereSeparator: \.isNewline) { let line = String(raw) if line.hasPrefix("total ") { continue } // Un nome con "/" o "\\" (server sbagliato o ostile) farebbe scrivere fuori dalla cartella scelta. if let e = unixEntry(line) ?? windowsEntry(line), e.name != ".", e.name != "..", !e.name.contains("/"), !e.name.contains("\\"), !e.name.contains("\0") { out.append(e) } } return out } private static let months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"] static func unixEntry(_ line: String) -> FtpEntry? { guard let kind = line.first, "-dlbcps".contains(kind) else { return nil } // Gli 8 campi prima del nome; il nome può contenere spazi. var fields: [Substring] = [] var idx = line.startIndex while fields.count < 8 { while idx < line.endIndex && line[idx] == " " { idx = line.index(after: idx) } guard idx < line.endIndex else { return nil } let start = idx while idx < line.endIndex && line[idx] != " " { idx = line.index(after: idx) } fields.append(line[start.. ") { name = String(name[.. (now.month ?? 12) ? 1 : 0) } else { c.year = Int(t) } date = Calendar.current.date(from: c) } return FtpEntry(name: name, isDirectory: kind == "d", isLink: kind == "l", size: size, modified: date) } static func windowsEntry(_ line: String) -> FtpEntry? { let parts = line.split(separator: " ", maxSplits: 3, omittingEmptySubsequences: true) guard parts.count == 4, parts[0].contains("-") else { return nil } let isDir = parts[2] == "" let f = DateFormatter() f.dateFormat = "MM-dd-yy hh:mma" f.locale = Locale(identifier: "en_US_POSIX") let date = f.date(from: "\(parts[0]) \(parts[1])") return FtpEntry(name: parts[3].trimmingCharacters(in: .whitespaces), isDirectory: isDir, size: isDir ? 0 : Int64(parts[2]) ?? 0, modified: date) } }