Files
2026-10-11 16:01:50 -07:00

548 lines
24 KiB
Swift

import Foundation
/// What can go wrong between this app and Steam's connection servers.
enum SteamFailure: LocalizedError, Equatable {
/// There is no sign-in to connect with.
case notSignedIn
/// Steam no longer accepts the stored sign-in (expired, revoked, password changed).
case signInRejected(code: Int)
/// Steam refused the connection for another reason.
case refused(code: Int)
case unreachable
case timedOut
case connectionLost
/// A request Steam answered with an error result.
case requestFailed(what: String, code: Int)
case unexpectedReply
var errorDescription: String? {
switch self {
case .notSignedIn: return "Sign in to Steam first."
case .signInRejected: return "Steam no longer accepts this sign-in. Sign out, then sign in again."
case .refused(let code): return "Steam refused the connection (result \(code)). Try again in a little while."
case .unreachable: return "Steam can't be reached. Check the internet connection."
case .timedOut: return "Steam took too long to answer. Try again."
case .connectionLost: return "The connection to Steam dropped. Try again."
case .requestFailed(let what, let code): return "Steam couldn't complete a request (\(what), result \(code))."
case .unexpectedReply: return "Steam sent an answer this app didn't understand."
}
}
}
/// A connection to Steam's network: one WebSocket to a connection server,
/// logged on with the stored sign-in, carrying requests and their replies.
///
/// It connects when something is asked of it and lets go again after a spell
/// of quiet, so the account is not held online for nothing.
actor SteamClient {
enum Credentials: Sendable {
/// Steam's guest logon, which can read public information and
/// download the few things Steam offers to everyone.
case anonymous
case account(SteamSignIn)
}
struct Reply: Sendable {
let kind: UInt32
/// The result in the reply's header (1 is success; absent counts as success).
let result: Int
let body: Data
}
struct License: Sendable {
let packageID: UInt32
/// The token that unlocks the package's description.
let accessToken: UInt64
}
/// EOSType sent with logons and sign-ins. Steam's list has no entry for a
/// phone acting as a desktop client; this is its generic Apple desktop one.
static let operatingSystem: Int64 = -102
// Message kinds (EMsg) this client sends or understands.
private enum Kind {
static let multi: UInt32 = 1
static let serviceResponse: UInt32 = 147
static let serviceCall: UInt32 = 151
static let heartbeat: UInt32 = 703
static let logOff: UInt32 = 706
static let logOnResponse: UInt32 = 751
static let loggedOff: UInt32 = 757
static let licenseList: UInt32 = 780
static let logOn: UInt32 = 5514
static let protobufFlag: UInt32 = 0x8000_0000
}
private let credentials: @Sendable () -> Credentials?
private let http: URLSession
private var socket: URLSessionWebSocketTask?
/// Counts connections, so a late callback from an old socket is recognised.
private var epoch = 0
private var online = false
private var connecting: Task<Void, Error>?
private var anonymous = false
private var steamID: UInt64 = 0
private var sessionID: Int32 = 0
private var cellID: UInt32 = 0
private var lastAccountID: UInt64 = 0
private struct Waiter {
var replies: [Reply] = []
let isLast: @Sendable (Reply) -> Bool
let continuation: CheckedContinuation<[Reply], Error>
}
private var nextJob: UInt64 = 1
private var waiters: [UInt64: Waiter] = [:]
private var logOnWaiter: CheckedContinuation<Void, Error>?
private var licenses: [License]?
private var licenseWaiters: [CheckedContinuation<[License], Error>] = []
private var heartbeat: Task<Void, Never>?
private var idleTimer: Task<Void, Never>?
/// `credentials` is asked each time a logon is needed, so a sign-in or
/// sign-out between connections is picked up.
init(credentials: @escaping @Sendable () -> Credentials?) {
self.credentials = credentials
let configuration = URLSessionConfiguration.ephemeral
configuration.timeoutIntervalForRequest = 20
http = URLSession(configuration: configuration)
}
// MARK: Asking Steam things
/// Sends a message and returns the reply addressed to it.
func request(_ kind: UInt32, _ body: Data, timeout: TimeInterval = 20) async throws -> Reply {
let replies = try await exchange(kind: kind, method: nil, body: body, timeout: timeout) { _ in true }
guard let reply = replies.first else { throw SteamFailure.unexpectedReply }
return reply
}
/// Sends a message whose answer arrives in several replies, and collects
/// them until `isLast` says the answer is complete.
func requestAll(_ kind: UInt32, _ body: Data, timeout: TimeInterval = 40,
until isLast: @escaping @Sendable (Reply) -> Bool) async throws -> [Reply] {
try await exchange(kind: kind, method: nil, body: body, timeout: timeout, until: isLast)
}
/// Calls one of Steam's named service methods ("Service.Method#1").
func call(_ method: String, _ body: Data, timeout: TimeInterval = 20) async throws -> ProtoMessage {
let replies = try await exchange(kind: Kind.serviceCall, method: method, body: body, timeout: timeout) { _ in true }
guard let reply = replies.first else { throw SteamFailure.unexpectedReply }
guard reply.result == 1 else { throw SteamFailure.requestFailed(what: method, code: reply.result) }
guard let message = try? ProtoMessage(reply.body) else { throw SteamFailure.unexpectedReply }
return message
}
/// The packages the account holds, which Steam sends by itself after a logon.
func ownedPackages() async throws -> [License] {
try await ensureOnline()
// A guest holds exactly one package, and Steam does not announce it.
if anonymous { return [License(packageID: 17906, accessToken: 0)] }
if let licenses { return licenses }
let mine = epoch
return try await withCheckedThrowingContinuation { continuation in
licenseWaiters.append(continuation)
Task {
try? await Task.sleep(for: .seconds(20))
self.abandonLicenseWait(epoch: mine)
}
}
}
/// The content region Steam placed this connection in, which picks the download servers.
func cell() async throws -> UInt32 {
try await ensureOnline()
return cellID
}
/// The Steam ID of the account most recently logged on, or 0.
func accountID() -> UInt64 { lastAccountID }
/// Logs off and closes the connection. The next request connects again.
func disconnect() async {
idleTimer?.cancel()
guard let socket else { return }
if online {
try? await socket.send(.data(frame(Kind.logOff, body: Data())))
}
tearDown(failing: SteamFailure.connectionLost)
}
// MARK: Connecting
private func ensureOnline() async throws {
idleTimer?.cancel()
if online { return }
if let connecting { return try await connecting.value }
let attempt = Task { try await self.connect() }
connecting = attempt
defer { connecting = nil }
try await attempt.value
restIfQuiet()
}
private func connect() async throws {
guard let who = credentials() else { throw SteamFailure.notSignedIn }
let servers = try await Self.connectionServers(using: http)
var failure: Error = SteamFailure.unreachable
for server in servers.prefix(4) {
do {
try await logOn(to: server, as: who)
return
} catch let refusal as SteamFailure {
tearDown(failing: SteamFailure.connectionLost)
// A rejected sign-in is the same on every server; a busy or silent one is not.
if case .signInRejected = refusal { throw refusal }
failure = refusal
} catch {
tearDown(failing: SteamFailure.connectionLost)
if error is CancellationError { throw error }
failure = SteamFailure.unreachable
}
}
throw failure
}
private func logOn(to server: URL, as who: Credentials) async throws {
epoch += 1
let mine = epoch
let task = http.webSocketTask(with: server)
task.maximumMessageSize = 64 << 20
socket = task
licenses = nil
task.resume()
listen(to: task, epoch: mine)
var message = ProtoWriter()
message.uint(1, 65580) // protocol_version
message.uint(5, 1771) // client_package_version
message.string(6, "english") // client_language
message.uint(7, UInt64(UInt32(truncatingIfNeeded: Self.operatingSystem))) // client_os_type
if let address = LocalNetwork.ipv4() {
// Clients send their local address lightly scrambled; Steam uses it to tell
// machines behind one router apart.
message.message(11) { $0.fixed32(1, address ^ 0xBAAD_F00D) } // obfuscated_private_ip.v4
}
message.bool(102, true) // supports_rate_limit_response
// Before a logon the header names the kind of account logging on, with no number yet:
// an individual on a desktop, or a guest.
let placeholder: UInt64
switch who {
case .anonymous:
anonymous = true
placeholder = 0x01A0_0000_0000_0000
case .account(let signIn):
anonymous = false
placeholder = 0x0110_0001_0000_0000
message.bool(8, true) // should_remember_password
message.string(50, signIn.accountName) // account_name
message.string(96, SteamDevice.name) // machine_name
message.string(108, signIn.refreshToken) // access_token
}
let logOn = Self.encode(Kind.logOn, steamID: placeholder, sessionID: 0, job: nil, method: nil, body: message.data)
try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
logOnWaiter = continuation
Task {
do {
try await task.send(.data(logOn))
} catch {
self.finishLogOn(epoch: mine, with: .failure(SteamFailure.unreachable))
return
}
try? await Task.sleep(for: .seconds(15))
self.finishLogOn(epoch: mine, with: .failure(SteamFailure.timedOut))
}
}
}
private func finishLogOn(epoch mine: Int, with result: Result<Void, Error>) {
guard mine == epoch, let waiter = logOnWaiter else { return }
logOnWaiter = nil
waiter.resume(with: result)
}
/// The connection servers Steam currently offers for WebSockets, least busy first.
private static func connectionServers(using http: URLSession) async throws -> [URL] {
let directory = URL(string: "https://api.steampowered.com/ISteamDirectory/GetCMListForConnect/v1/?cellid=0&cmtype=websockets&format=json")!
let data: Data
do {
(data, _) = try await http.data(from: directory)
} catch {
if error is CancellationError || (error as? URLError)?.code == .cancelled { throw CancellationError() }
throw SteamFailure.unreachable
}
guard let root = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
let response = root["response"] as? [String: Any],
let list = response["serverlist"] as? [[String: Any]] else {
throw SteamFailure.unreachable
}
let usable = list.compactMap { entry -> (url: URL, load: Double)? in
guard let endpoint = entry["endpoint"] as? String,
(entry["type"] as? String ?? "websockets") == "websockets",
(entry["realm"] as? String ?? "steamglobal") == "steamglobal",
let url = URL(string: "wss://\(endpoint)/cmsocket/") else { return nil }
return (url, (entry["wtd_load"] as? NSNumber)?.doubleValue ?? 0)
}
guard !usable.isEmpty else { throw SteamFailure.unreachable }
// The few least busy, in a random order so that not every client picks the same one.
return Array(usable.sorted { $0.load < $1.load }.prefix(6)).shuffled().map(\.url)
}
// MARK: Sending
private func exchange(kind: UInt32, method: String?, body: Data, timeout: TimeInterval,
until isLast: @escaping @Sendable (Reply) -> Bool) async throws -> [Reply] {
try await ensureOnline()
guard let socket else { throw SteamFailure.connectionLost }
let job = nextJob
nextJob += 1
let data = Self.encode(kind, steamID: steamID, sessionID: sessionID, job: job, method: method, body: body)
return try await withTaskCancellationHandler {
try await withCheckedThrowingContinuation { continuation in
guard !Task.isCancelled else {
continuation.resume(throwing: CancellationError())
return
}
idleTimer?.cancel()
waiters[job] = Waiter(isLast: isLast, continuation: continuation)
Task {
do {
try await socket.send(.data(data))
} catch {
self.fail(job, with: SteamFailure.connectionLost)
return
}
try? await Task.sleep(for: .seconds(timeout))
self.fail(job, with: SteamFailure.timedOut)
}
}
} onCancel: {
Task { await self.fail(job, with: CancellationError()) }
}
}
private func fail(_ job: UInt64, with error: Error) {
guard let waiter = waiters.removeValue(forKey: job) else { return }
// A timeout after some replies still hands over what arrived.
if !waiter.replies.isEmpty, error as? SteamFailure == .timedOut {
waiter.continuation.resume(returning: waiter.replies)
} else {
waiter.continuation.resume(throwing: error)
}
restIfQuiet()
}
private func frame(_ kind: UInt32, body: Data) -> Data {
Self.encode(kind, steamID: steamID, sessionID: sessionID, job: nil, method: nil, body: body)
}
/// A message on the wire: its kind (flagged as protobuf), the length of
/// its header, the header, the body.
private static func encode(_ kind: UInt32, steamID: UInt64, sessionID: Int32, job: UInt64?, method: String?, body: Data) -> Data {
var header = ProtoWriter()
header.fixed64(1, steamID) // steamid
header.int(2, Int64(sessionID)) // client_sessionid
if let job { header.fixed64(10, job) } // jobid_source
if let method { header.string(12, method) } // target_job_name
var data = Data(capacity: 8 + header.data.count + body.count)
withUnsafeBytes(of: (kind | Kind.protobufFlag).littleEndian) { data.append(contentsOf: $0) }
withUnsafeBytes(of: UInt32(header.data.count).littleEndian) { data.append(contentsOf: $0) }
data.append(header.data)
data.append(body)
return data
}
// MARK: Receiving
private nonisolated func listen(to task: URLSessionWebSocketTask, epoch mine: Int) {
Task {
while true {
do {
if case .data(let data) = try await task.receive() {
await self.accept(data, epoch: mine)
}
} catch {
await self.socketClosed(epoch: mine)
return
}
}
}
}
private func socketClosed(epoch mine: Int) {
guard mine == epoch else { return }
finishLogOn(epoch: mine, with: .failure(SteamFailure.unreachable))
tearDown(failing: SteamFailure.connectionLost)
}
private func accept(_ data: Data, epoch mine: Int) {
guard mine == epoch, data.count >= 8 else { return }
let bytes = [UInt8](data.prefix(8))
let word = UInt32(bytes[0]) | UInt32(bytes[1]) << 8 | UInt32(bytes[2]) << 16 | UInt32(bytes[3]) << 24
// Everything this client uses is protobuf; the few old fixed-layout messages are not needed.
guard word & Kind.protobufFlag != 0 else { return }
let kind = word & ~Kind.protobufFlag
let headerLength = Int(UInt32(bytes[4]) | UInt32(bytes[5]) << 8 | UInt32(bytes[6]) << 16 | UInt32(bytes[7]) << 24)
guard headerLength <= data.count - 8 else { return }
let start = data.startIndex + 8
guard let header = try? ProtoMessage(data.subdata(in: start..<(start + headerLength))) else { return }
let body = data.subdata(in: (start + headerLength)..<data.endIndex)
switch kind {
case Kind.multi:
unpack(body, epoch: mine)
case Kind.logOnResponse:
loggedOn(header: header, body: body, epoch: mine)
case Kind.loggedOff:
finishLogOn(epoch: mine, with: .failure(SteamFailure.unreachable))
tearDown(failing: SteamFailure.connectionLost)
case Kind.licenseList:
guard let list = try? ProtoMessage(body) else { return }
let found = list.messages(2).map { License(packageID: UInt32(truncatingIfNeeded: $0.uint(1) ?? 0), accessToken: $0.uint(17) ?? 0) }
licenses = found
let waiting = licenseWaiters
licenseWaiters = []
for waiter in waiting { waiter.resume(returning: found) }
default:
guard let job = header.uint(11), var waiter = waiters[job] else { return } // jobid_target
let reply = Reply(kind: kind, result: Int(header.int32(13) ?? 1), body: body) // eresult
waiter.replies.append(reply)
if waiter.isLast(reply) {
waiters[job] = nil
waiter.continuation.resume(returning: waiter.replies)
restIfQuiet()
} else {
waiters[job] = waiter
}
}
}
/// Several messages sent as one, usually gzipped: each inner message is
/// preceded by its length.
private func unpack(_ body: Data, epoch mine: Int) {
guard let multi = try? ProtoMessage(body), var payload = multi.data(2) else { return } // message_body
if let size = multi.uint(1), size > 0 { // size_unzipped
guard size <= 256 << 20, let inflated = try? Inflate.run(payload, wrapper: .gzip, sizeHint: Int(size)) else { return }
payload = inflated
}
let bytes = [UInt8](payload)
var at = 0
while bytes.count - at >= 4 {
let length = Int(UInt32(bytes[at]) | UInt32(bytes[at + 1]) << 8 | UInt32(bytes[at + 2]) << 16 | UInt32(bytes[at + 3]) << 24)
at += 4
guard length <= bytes.count - at else { return }
accept(Data(bytes[at..<(at + length)]), epoch: mine)
at += length
}
}
private func loggedOn(header: ProtoMessage, body: Data, epoch mine: Int) {
guard let response = try? ProtoMessage(body) else {
finishLogOn(epoch: mine, with: .failure(SteamFailure.unexpectedReply))
return
}
let result = Int(response.int32(1) ?? 2) // eresult
guard result == 1 else {
// InvalidPassword, AccessDenied, AccountNotFound, Revoked, Expired, InvalidSignature:
// the sign-in itself is no good. Anything else is about the server or the moment.
let rejected = [5, 15, 18, 26, 27, 94].contains(result)
finishLogOn(epoch: mine, with: .failure(rejected ? SteamFailure.signInRejected(code: result) : SteamFailure.refused(code: result)))
return
}
steamID = header.uint(1) ?? 0 // steamid, now the real one
lastAccountID = steamID
sessionID = header.int32(2) ?? 0 // client_sessionid
cellID = UInt32(truncatingIfNeeded: response.uint(7) ?? 0) // cell_id
online = true
let pause = max(5, min(Int(response.int32(3) ?? 30), 120)) // heartbeat_seconds
heartbeat?.cancel()
heartbeat = Task {
while !Task.isCancelled {
try? await Task.sleep(for: .seconds(pause))
guard !Task.isCancelled else { return }
await self.beat(epoch: mine)
}
}
finishLogOn(epoch: mine, with: .success(()))
}
private func beat(epoch mine: Int) async {
guard mine == epoch, online, let socket else { return }
try? await socket.send(.data(frame(Kind.heartbeat, body: Data())))
}
private func abandonLicenseWait(epoch mine: Int) {
guard mine == epoch, !licenseWaiters.isEmpty else { return }
let waiting = licenseWaiters
licenseWaiters = []
for waiter in waiting { waiter.resume(throwing: SteamFailure.timedOut) }
}
// MARK: Letting go
/// Closes the socket and fails whatever was still waiting on it.
private func tearDown(failing error: Error) {
heartbeat?.cancel()
heartbeat = nil
socket?.cancel(with: .goingAway, reason: nil)
socket = nil
online = false
steamID = 0
sessionID = 0
epoch += 1
if let waiter = logOnWaiter {
logOnWaiter = nil
waiter.resume(throwing: error)
}
let pending = waiters
waiters = [:]
for waiter in pending.values { waiter.continuation.resume(throwing: error) }
let waiting = licenseWaiters
licenseWaiters = []
for waiter in waiting { waiter.resume(throwing: error) }
}
/// With nothing outstanding, the connection is given a little while and then closed.
private func restIfQuiet() {
guard waiters.isEmpty else { return }
idleTimer?.cancel()
idleTimer = Task {
try? await Task.sleep(for: .seconds(45))
guard !Task.isCancelled else { return }
await self.closeIfStillQuiet()
}
}
private func closeIfStillQuiet() async {
guard waiters.isEmpty, connecting == nil, licenseWaiters.isEmpty else { return }
await disconnect()
}
}
/// This device's address on the local network.
enum LocalNetwork {
/// The first IPv4 address that is not the loopback, as a host-order number.
static func ipv4() -> UInt32? {
var list: UnsafeMutablePointer<ifaddrs>?
guard getifaddrs(&list) == 0, let first = list else { return nil }
defer { freeifaddrs(list) }
var entry: UnsafeMutablePointer<ifaddrs>? = first
while let current = entry {
defer { entry = current.pointee.ifa_next }
guard let address = current.pointee.ifa_addr, address.pointee.sa_family == UInt8(AF_INET),
current.pointee.ifa_flags & UInt32(IFF_LOOPBACK) == 0,
current.pointee.ifa_flags & UInt32(IFF_UP) != 0 else { continue }
let raw = address.withMemoryRebound(to: sockaddr_in.self, capacity: 1) { $0.pointee.sin_addr.s_addr }
return UInt32(bigEndian: raw)
}
return nil
}
}