Skip to content

Linux + iPhone Continuity / iMessage / SMS

bidirectional file transfer

Zack Bartelf4722a40d7b7
diff --git a/.codex b/.codex
new file mode 100644
index 0000000..e69de29
diff --git a/apple/Tether/ViewModels/TetherViewModel.swift b/apple/Tether/ViewModels/TetherViewModel.swift
index 0b506c8..0584276 100644
--- a/apple/Tether/ViewModels/TetherViewModel.swift
+++ b/apple/Tether/ViewModels/TetherViewModel.swift
@@ -47,16 +47,23 @@ struct ClipboardEntry: Identifiable {
/// Tracks an active file transfer.
struct FileTransfer: Identifiable {
+ enum Direction {
+ case outgoing
+ case incoming
+ }
+
let id: String // transfer_id
- let filename: String
+ var filename: String
let totalSize: Int64
- var bytesSent: Int64 = 0
+ var direction: Direction
+ var bytesTransferred: Int64 = 0
var isComplete = false
var failed = false
+ var savedURL: URL?
var progress: Double {
guard totalSize > 0 else { return 0 }
- return Double(bytesSent) / Double(totalSize)
+ return Double(bytesTransferred) / Double(totalSize)
}
}
@@ -106,6 +113,14 @@ final class TetherViewModel {
/// The chunk size for file transfers (48KB raw → 64KB base64).
private let fileChunkSize = 48 * 1024
+ private struct IncomingTransferBuffer {
+ let filename: String
+ let expectedSize: Int64
+ var data = Data()
+ }
+
+ private var incomingTransfers: [String: IncomingTransferBuffer] = [:]
+
// MARK: - Initialization
/// Call once at app startup.
@@ -222,6 +237,7 @@ final class TetherViewModel {
Task.detached { [weak self] in
guard let self else { return }
+ defer { url.stopAccessingSecurityScopedResource() }
do {
let fileData = try Data(contentsOf: url)
@@ -231,7 +247,8 @@ final class TetherViewModel {
let transfer = FileTransfer(
id: transferId,
filename: filename,
- totalSize: totalSize
+ totalSize: totalSize,
+ direction: .outgoing
)
self.activeTransfers.append(transfer)
}
@@ -261,7 +278,7 @@ final class TetherViewModel {
))
if let idx = self.activeTransfers.firstIndex(where: { $0.id == transferId }) {
- self.activeTransfers[idx].bytesSent = Int64(end)
+ self.activeTransfers[idx].bytesTransferred = Int64(end)
}
}
@@ -284,8 +301,6 @@ final class TetherViewModel {
self.errorMessage = "File transfer failed: \(error.localizedDescription)"
}
}
-
- url.stopAccessingSecurityScopedResource()
}
}
@@ -373,6 +388,46 @@ final class TetherViewModel {
}
}
+ case .fileStart:
+ guard let transferId = message.transferId,
+ let filename = message.filename,
+ let size = message.size else { break }
+
+ incomingTransfers[transferId] = IncomingTransferBuffer(
+ filename: filename,
+ expectedSize: size
+ )
+
+ if let idx = activeTransfers.firstIndex(where: { $0.id == transferId }) {
+ activeTransfers[idx].filename = filename
+ activeTransfers[idx].direction = .incoming
+ activeTransfers[idx].bytesTransferred = 0
+ } else {
+ activeTransfers.append(FileTransfer(
+ id: transferId,
+ filename: filename,
+ totalSize: size,
+ direction: .incoming
+ ))
+ }
+
+ case .fileChunk:
+ guard let transferId = message.transferId,
+ let data = message.data,
+ let chunkData = Data(base64Encoded: data),
+ var transfer = incomingTransfers[transferId] else { break }
+
+ transfer.data.append(chunkData)
+ incomingTransfers[transferId] = transfer
+
+ if let idx = activeTransfers.firstIndex(where: { $0.id == transferId }) {
+ activeTransfers[idx].bytesTransferred = Int64(transfer.data.count)
+ }
+
+ case .fileEnd:
+ guard let transferId = message.transferId else { break }
+ finalizeIncomingTransfer(transferId: transferId)
+
case .error:
if message.message == "unauthorized" {
// The daemon rejected us — we're not paired yet.
@@ -397,4 +452,55 @@ final class TetherViewModel {
showPairingSheet = false
appState = .connected
}
+
+ private func finalizeIncomingTransfer(transferId: String) {
+ guard let buffered = incomingTransfers.removeValue(forKey: transferId) else { return }
+
+ do {
+ guard Int64(buffered.data.count) == buffered.expectedSize else {
+ throw CocoaError(.fileReadCorruptFile)
+ }
+
+ let destination = try incomingFileURL(for: buffered.filename)
+ try buffered.data.write(to: destination, options: .atomic)
+
+ if let idx = activeTransfers.firstIndex(where: { $0.id == transferId }) {
+ var transfer = activeTransfers.remove(at: idx)
+ transfer.bytesTransferred = Int64(buffered.data.count)
+ transfer.isComplete = true
+ transfer.savedURL = destination
+ completedTransfers.insert(transfer, at: 0)
+ }
+ } catch {
+ if let idx = activeTransfers.firstIndex(where: { $0.id == transferId }) {
+ activeTransfers[idx].failed = true
+ }
+ errorMessage = "Failed to save incoming file: \(error.localizedDescription)"
+ }
+ }
+
+ private func incomingFileURL(for filename: String) throws -> URL {
+ let fm = FileManager.default
+ let docs = try fm.url(
+ for: .documentDirectory,
+ in: .userDomainMask,
+ appropriateFor: nil,
+ create: true
+ )
+ let incomingDir = docs.appendingPathComponent("Received", isDirectory: true)
+ try fm.createDirectory(at: incomingDir, withIntermediateDirectories: true, attributes: nil)
+
+ let base = URL(fileURLWithPath: filename).deletingPathExtension().lastPathComponent
+ let ext = URL(fileURLWithPath: filename).pathExtension
+ var candidate = incomingDir.appendingPathComponent(filename)
+ var counter = 1
+
+ while fm.fileExists(atPath: candidate.path) {
+ let deduped = ext.isEmpty ? "\(base)(\(counter))" : "\(base)(\(counter)).\(ext)"
+ candidate = incomingDir.appendingPathComponent(deduped)
+ counter += 1
+ }
+
+ return candidate
+ }
}
diff --git a/apple/Tether/Views/FilesView.swift b/apple/Tether/Views/FilesView.swift
index c91990c..3fc776e 100644
--- a/apple/Tether/Views/FilesView.swift
+++ b/apple/Tether/Views/FilesView.swift
@@ -170,7 +170,7 @@ struct FilesView: View {
HStack(spacing: 14) {
Image(systemName: fileIcon(for: transfer.filename))
.font(.title3)
- .foregroundStyle(isActive ? .teal : .secondary)
+ .foregroundStyle(transfer.direction == .incoming ? .blue : (isActive ? .teal : .secondary))
.frame(width: 32)
VStack(alignment: .leading, spacing: 6) {
@@ -178,11 +178,15 @@ struct FilesView: View {
.font(.subheadline.weight(.medium))
.lineLimit(1)
+ Text(transfer.direction == .incoming ? "Incoming to iPhone" : "Outgoing to desktop")
+ .font(.caption2)
+ .foregroundStyle(.secondary)
+
if isActive && !transfer.failed {
ProgressView(value: transfer.progress)
- .tint(.teal)
+ .tint(transfer.direction == .incoming ? .blue : .teal)
- Text(formatBytes(transfer.bytesSent) + " / " + formatBytes(transfer.totalSize))
+ Text(formatBytes(transfer.bytesTransferred) + " / " + formatBytes(transfer.totalSize))
.font(.caption2)
.foregroundStyle(.tertiary)
} else if transfer.failed {
@@ -190,15 +194,9 @@ struct FilesView: View {
.font(.caption)
.foregroundStyle(.red)
} else {
- HStack(spacing: 4) {
- Image(systemName: "checkmark.circle.fill")
- .font(.caption2)
- .foregroundStyle(.green)
-
- Text(formatBytes(transfer.totalSize))
- .font(.caption)
- .foregroundStyle(.tertiary)
- }
+ Text(completedText(for: transfer))
+ .font(.caption)
+ .foregroundStyle(.tertiary)
}
}
}
@@ -233,6 +231,14 @@ struct FilesView: View {
formatter.countStyle = .file
return formatter.string(fromByteCount: bytes)
}
+
+ private func completedText(for transfer: FileTransfer) -> String {
+ if transfer.direction == .incoming {
+ return "Saved to On My iPhone/Tether/Received • " + formatBytes(transfer.totalSize)
+ }
+
+ return "Delivered • " + formatBytes(transfer.totalSize)
+ }
}
#Preview {
diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md
index 85ac463..a42b9dd 100644
--- a/docs/PROTOCOL.md
+++ b/docs/PROTOCOL.md
@@ -52,10 +52,14 @@ The clipboard capabilities allow seamless copying and pasting between the Host (
Tether supports streaming large binary files seamlessly through JSON using Base64 chunks to adhere to extension native messaging payload restrictions.
-### `file_start` (Client -> Daemon)
+### `file_start`
**Description**: Announces an incoming binary transmission.
+**Direction**:
+- `Client -> Daemon` when a remote device uploads into the Linux host.
+- `Daemon -> Client` when a local Unix client asks `tetherd` to push a file to a connected mobile app.
+
**Payload**:
```json
{
@@ -66,10 +70,14 @@ Tether supports streaming large binary files seamlessly through JSON using Base6
}
```
-### `file_chunk` (Client -> Daemon)
+### `file_chunk`
**Description**: Sends a sequential Base64 chunk of the file data.
+**Direction**:
+- `Client -> Daemon` for mobile-to-Linux uploads.
+- `Daemon -> Client` for Linux-to-mobile sends.
+
**Payload**:
```json
{
@@ -80,9 +88,13 @@ Tether supports streaming large binary files seamlessly through JSON using Base6
}
```
-### `file_end` (Client -> Daemon)
+### `file_end`
+
+**Description**: Marks the end of the streamed file.
-**Description**: Closes the file handle on the daemon and returns a success status back.
+**Direction**:
+- `Client -> Daemon` for mobile-to-Linux uploads.
+- `Daemon -> Client` for Linux-to-mobile sends.
**Payload**:
```json
@@ -101,6 +113,15 @@ Tether supports streaming large binary files seamlessly through JSON using Base6
}
```
+For local Unix clients, `tetherd` returns `file_status` once the stream has been forwarded to at least one connected TCP client. If no mobile client is connected, the daemon returns:
+
+```json
+{
+ "command": "error",
+ "message": "no_connected_mobile_client"
+}
+```
+
---
## 3. Device Pairing (mTLS)
diff --git a/src/cli/main.cpp b/src/cli/main.cpp
index 25937c7..47b6d2e 100644
--- a/src/cli/main.cpp
+++ b/src/cli/main.cpp
@@ -11,7 +11,7 @@ void print_help() {
<< " -h, --help Show this help message.\n"
<< " -g, --get-clipboard Retrieve the current Wayland clipboard text.\n"
<< " -s, --set-clipboard Take string input and copy it to the local Wayland clipboard.\n"
- << " -f, --send-file Send a file securely to the local Wayland download directory.\n"
+ << " -f, --send-file Send a file through tether.\n"
<< " -d, --discover Scan the local network for tetherd instances via mDNS.\n"
<< " --host <ip> Connect over TCP to daemon ip instead of UNIX Socket.\n"
<< " --port <num> Connect over TCP port (default 5134).\n"
@@ -25,6 +25,7 @@ void print_help() {
<< " echo \"pipe\" | tether -s\n"
<< " tether --discover\n"
<< " tether --discover --timeout 5000\n"
+ << " tether -f ./report.pdf\n"
<< " tether --accept 9a4f21...\n";
}
@@ -138,14 +139,13 @@ int main(int argc, char* argv[]) {
return 1;
}
} else if (action == "file") {
- std::cout << "Uploading " << arg_val << "..." << std::endl;
+ std::cout << "Sending " << arg_val << "..." << std::endl;
if (!client.send_file(arg_val, err)) {
std::cerr << "Transfer Failed: " << err << "\n";
return 1;
}
- std::cout << "File transfer successfully saved.\n";
+ std::cout << "File transfer delivered.\n";
}
return 0;
}
-
diff --git a/src/core/include/tether/net.hpp b/src/core/include/tether/net.hpp
index d59f126..9f7497b 100644
--- a/src/core/include/tether/net.hpp
+++ b/src/core/include/tether/net.hpp
@@ -20,6 +20,7 @@ namespace tether {
void register_client_ssl(int fd, SSL* ssl);
void unregister_client_fd(int fd);
void broadcast_message(const std::string& msg, int exclude_fd = -1);
+ size_t broadcast_tcp_message(const std::string& msg, int exclude_fd = -1);
class UnixServer {
public:
diff --git a/src/core/src/client.cpp b/src/core/src/client.cpp
index c8758bc..bd6e6e4 100644
--- a/src/core/src/client.cpp
+++ b/src/core/src/client.cpp
@@ -17,6 +17,22 @@
namespace tether {
+namespace {
+
+std::string extract_protocol_error(const std::string& response) {
+ try {
+ nlohmann::json parsed = nlohmann::json::parse(response);
+ if (parsed.value("command", "") == "error") {
+ return parsed.value("message", "unknown_error");
+ }
+ } catch (...) {
+ }
+
+ return "";
+}
+
+}
+
Client::Client() {}
Client::~Client() {
@@ -223,9 +239,15 @@ bool Client::send_file(const std::string& path, std::string& err_out) {
j_start["transfer_id"] = transfer_id;
std::string s_resp = send_and_wait(j_start.dump() + "\n");
- if (s_resp.find("unauthorized") != std::string::npos) {
- err_out = "Unauthorized. Device not paired.";
- return false;
+ if (std::string protocol_error = extract_protocol_error(s_resp); !protocol_error.empty()) {
+ if (protocol_error == "unauthorized") {
+ err_out = "Unauthorized. Device not paired.";
+ } else if (protocol_error == "no_connected_mobile_client") {
+ err_out = "No connected iPhone client is available.";
+ } else {
+ err_out = protocol_error;
+ }
+ return false;
}
const size_t chunk_size = 512 * 1024;
@@ -243,7 +265,15 @@ bool Client::send_file(const std::string& path, std::string& err_out) {
j_chunk["transfer_id"] = transfer_id;
j_chunk["data"] = tether::base64_encode(buffer.data(), bytes_read);
- send_and_wait(j_chunk.dump() + "\n");
+ std::string chunk_resp = send_and_wait(j_chunk.dump() + "\n");
+ if (std::string protocol_error = extract_protocol_error(chunk_resp); !protocol_error.empty()) {
+ if (protocol_error == "no_connected_mobile_client") {
+ err_out = "No connected iPhone client is available.";
+ } else {
+ err_out = protocol_error;
+ }
+ return false;
+ }
}
nlohmann::json j_end;
@@ -256,6 +286,15 @@ bool Client::send_file(const std::string& path, std::string& err_out) {
if (r.contains("status") && r["status"] == "success") {
return true;
}
+ if (r.value("command", "") == "error") {
+ std::string message = r.value("message", "Transfer sequence explicitly rejected externally.");
+ if (message == "no_connected_mobile_client") {
+ err_out = "No connected iPhone client is available.";
+ } else {
+ err_out = message;
+ }
+ return false;
+ }
} catch (...) {
}
diff --git a/src/core/src/net.cpp b/src/core/src/net.cpp
index ee08bb7..99df755 100644
--- a/src/core/src/net.cpp
+++ b/src/core/src/net.cpp
@@ -72,6 +72,23 @@ namespace tether {
}
}
+ size_t broadcast_tcp_message(const std::string& msg, int exclude_fd) {
+ std::string packet = msg;
+ if (packet.back() != '\n')
+ packet += '\n';
+
+ size_t recipients = 0;
+ for (auto const& [fd, session] : active_sessions) {
+ if (fd == exclude_fd || !session.ssl)
+ continue;
+
+ robust_ssl_write(session.ssl, packet.c_str(), packet.size());
+ recipients++;
+ }
+
+ return recipients;
+ }
+
std::string get_runtime_dir() {
const char* xdg_runtime = std::getenv("XDG_RUNTIME_DIR");
if (!xdg_runtime) {
@@ -214,21 +231,40 @@ namespace tether {
continue;
}
} else if (j.contains("command") && j["command"] == "file_start") {
- if (g_file_manager)
- g_file_manager->handle_start(j["transfer_id"], j["filename"], j["size"]);
+ if (broadcast_tcp_message(msg) == 0) {
+ nlohmann::json resp;
+ resp["command"] = "error";
+ resp["message"] = "no_connected_mobile_client";
+ std::string payload = resp.dump() + "\n";
+ write(client_fd, payload.c_str(), payload.size());
+ continue;
+ }
} else if (j.contains("command") && j["command"] == "file_chunk") {
- if (g_file_manager)
- g_file_manager->handle_chunk(j["transfer_id"], j["chunk_index"], j["data"]);
+ if (broadcast_tcp_message(msg) == 0) {
+ nlohmann::json resp;
+ resp["command"] = "error";
+ resp["message"] = "no_connected_mobile_client";
+ std::string payload = resp.dump() + "\n";
+ write(client_fd, payload.c_str(), payload.size());
+ continue;
+ }
} else if (j.contains("command") && j["command"] == "file_end") {
- if (g_file_manager && g_file_manager->handle_end(j["transfer_id"])) {
+ if (broadcast_tcp_message(msg) == 0) {
nlohmann::json resp;
- resp["command"] = "file_status";
- resp["transfer_id"] = j["transfer_id"];
- resp["status"] = "success";
+ resp["command"] = "error";
+ resp["message"] = "no_connected_mobile_client";
std::string payload = resp.dump() + "\n";
write(client_fd, payload.c_str(), payload.size());
continue;
}
+
+ nlohmann::json resp;
+ resp["command"] = "file_status";
+ resp["transfer_id"] = j["transfer_id"];
+ resp["status"] = "success";
+ std::string payload = resp.dump() + "\n";
+ write(client_fd, payload.c_str(), payload.size());
+ continue;
}
} catch (...) {
}
@@ -355,11 +391,10 @@ namespace tether {
std::string print = Crypto::get_peer_fingerprint(ssl);
if (Crypto::instance().is_host_known(print)) {
client_paired_[client_fd] = true;
+ register_client_ssl(client_fd, ssl);
} else {
std::cout << "TcpServer: Untrusted client connected. Fingerprint: " << print << std::endl;
}
- // Now that handshake is done, we can safely receive broadcasts
- register_client_ssl(client_fd, ssl);
} else {
int err = SSL_get_error(ssl, ret);
if (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE) {
@@ -600,6 +635,10 @@ namespace tether {
client_paired_[info.client_fd] = true;
}
+ if (active_ssl_.count(info.client_fd)) {
+ register_client_ssl(info.client_fd, active_ssl_[info.client_fd]);
+ }
+
// Notify the remote client
if (active_ssl_.count(info.client_fd)) {
nlohmann::json resp;
diff --git a/src/gtk/main.cpp b/src/gtk/main.cpp
index 2890475..5e0b63b 100644
--- a/src/gtk/main.cpp
+++ b/src/gtk/main.cpp
@@ -468,8 +468,8 @@ static GtkWidget* build_file_transfer_tab() {
gtk_box_pack_start(GTK_BOX(box), header, FALSE, FALSE, 0);
GtkWidget* desc = gtk_label_new(
- "Pick a file to send to the connected host.\n"
- "Files are chunked via Base64 and saved to the remote Downloads directory.");
+ "Pick a file to send through tether.\n"
+ "The local daemon forwards files to connected iPhone clients.");
gtk_label_set_xalign(GTK_LABEL(desc), 0.0);
gtk_label_set_line_wrap(GTK_LABEL(desc), TRUE);
gtk_style_context_add_class(gtk_widget_get_style_context(desc), "dim-label");