← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Scripts/ota-server.swift (5180B)

1// Serves the OTA install site on 127.0.0.1 for deploy-ota.sh and exits once
2// the IPA has been sent in full and the page has been told so.
3//
4// Usage: swift Scripts/ota-server.swift <site-dir> <port>
5import Foundation
6import Network
7
8let arguments = CommandLine.arguments
9guard arguments.count == 3, let portNumber = UInt16(arguments[2]),
10      let port = NWEndpoint.Port(rawValue: portNumber) else {
11  FileHandle.standardError.write(Data("usage: ota-server.swift <site-dir> <port>\n".utf8))
12  exit(2)
13}
14let site = URL(fileURLWithPath: arguments[1], isDirectory: true)
15
16// Only these files are served; anything else is a 404.
17let contentTypes = [
18  "index.html": "text/html; charset=utf-8",
19  "manifest.plist": "text/xml",
20  "Reportage.ipa": "application/octet-stream",
21]
22
23// Install progress, reported to the page through /status. The phone fetches
24// the manifest when Install is tapped and the IPA once the alert is
25// confirmed; iOS installs the app after the IPA has been sent, but nothing
26// reports when that finishes.
27enum Stage: String {
28  case waiting, confirming, downloading, installing
29}
30nonisolated(unsafe) var stage = Stage.waiting
31
32// Exit once Tailscale has had time to relay the IPA and the page has seen the
33// installing stage, so it doesn't lose /status partway through.
34nonisolated(unsafe) var relayed = false
35nonisolated(unsafe) var reported = false
36
37func exitIfDone() {
38  if relayed && reported { exit(0) }
39}
40
41func log(_ message: String) {
42  let time = Date.now.formatted(.dateTime.hour(.twoDigits(amPM: .omitted)).minute().second())
43  print("    \(time) \(message)")
44  fflush(stdout)
45}
46
47func respond(on connection: NWConnection, to request: String) {
48  let parts = request.split(separator: " ")
49  guard parts.count >= 2 else {
50    connection.cancel()
51    return
52  }
53  let method = String(parts[0])
54  var path = String(parts[1].split(separator: "?", maxSplits: 1).first ?? "/")
55  if path == "/" { path = "/index.html" }
56  let name = String(path.dropFirst())
57
58  var status = "404 Not Found"
59  var contentType = "text/plain"
60  var body = Data("Not found\n".utf8)
61  if method != "GET" && method != "HEAD" {
62    status = "405 Method Not Allowed"
63    body = Data("Method not allowed\n".utf8)
64  } else if name == "status" {
65    status = "200 OK"
66    contentType = "application/json"
67    body = Data(#"{"stage":"\#(stage.rawValue)"}"#.utf8)
68  } else if let type = contentTypes[name],
69            let data = try? Data(contentsOf: site.appendingPathComponent(name)) {
70    status = "200 OK"
71    contentType = type
72    body = data
73  }
74
75  if method == "GET" && status.hasPrefix("200") {
76    if name == "manifest.plist" && stage == .waiting { stage = .confirming }
77    if name == "Reportage.ipa" { stage = .downloading }
78  }
79
80  let head = "HTTP/1.1 \(status)\r\n"
81    + "Content-Type: \(contentType)\r\n"
82    + "Cache-Control: no-store\r\n"
83    + "Content-Length: \(body.count)\r\n"
84    + "Connection: close\r\n\r\n"
85  var payload = Data(head.utf8)
86  if method != "HEAD" { payload.append(body) }
87
88  // The page polls /status every second; logging each poll is noise.
89  if name != "status" { log("\(method) \(path) \(status.prefix(3))") }
90  let reportedStage = stage
91  connection.send(content: payload, completion: .contentProcessed { error in
92    connection.cancel()
93    guard error == nil, method == "GET", status.hasPrefix("200") else { return }
94    if name == "status" && reportedStage == .installing {
95      reported = true
96      exitIfDone()
97    }
98    guard name == "Reportage.ipa" else { return }
99    stage = .installing
100    print("==> IPA downloaded; shutting down")
101    fflush(stdout)
102    // Give Tailscale a moment to finish relaying the IPA to the phone.
103    DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
104      relayed = true
105      exitIfDone()
106    }
107    // Don't wait on a page that has stopped polling.
108    DispatchQueue.main.asyncAfter(deadline: .now() + 60) { exit(0) }
109  })
110}
111
112func receiveRequest(on connection: NWConnection, buffer: Data = Data()) {
113  connection.receive(minimumIncompleteLength: 1, maximumLength: 65_536) { data, _, isComplete, error in
114    var buffer = buffer
115    if let data { buffer.append(data) }
116    if let end = buffer.range(of: Data("\r\n\r\n".utf8)) {
117      let header = String(decoding: buffer[..<end.lowerBound], as: UTF8.self)
118      respond(on: connection, to: String(header.prefix { $0 != "\r" }))
119    } else if isComplete || error != nil || buffer.count > 65_536 {
120      connection.cancel()
121    } else {
122      receiveRequest(on: connection, buffer: buffer)
123    }
124  }
125}
126
127let parameters = NWParameters.tcp
128parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: port)
129let listener: NWListener
130do {
131  listener = try NWListener(using: parameters)
132} catch {
133  FileHandle.standardError.write(Data("Could not listen on port \(portNumber): \(error)\n".utf8))
134  exit(1)
135}
136listener.stateUpdateHandler = { state in
137  if case .failed(let error) = state {
138    FileHandle.standardError.write(Data("Listener failed: \(error)\n".utf8))
139    exit(1)
140  }
141}
142listener.newConnectionHandler = { connection in
143  connection.start(queue: .main)
144  receiveRequest(on: connection)
145}
146listener.start(queue: .main)
147dispatchMain()