package me.teafry.voipmessages; import android.app.job.JobInfo; import android.app.job.JobScheduler; import android.content.ComponentName; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.BitmapFactory; import android.util.Base64; import android.util.Log; import org.json.JSONArray; import org.json.JSONObject; import java.io.File; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.crypto.Cipher; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.SecretKeySpec; /** * The relay through jai (the desktop's src/main/relay.ts; server in * server/bubble_relay.py): the SIM's texts go to the desktop, texts typed * there go out over the SIM here, and chat names and read/unread/archived * stay in step without a cable. * * Everything is AES-256-GCM sealed with the key the desktop handed over USB * (config.json "relay"); jai only passes blobs on. It runs with the checks * the Rabbit already makes (PollJob) plus one network job after something * happens here (a text, a send, a swipe), never on a timer of its own: the * battery pays for nothing new while nothing's going on. */ final class Relay { private Relay() {} private static final String TAG = "Relay"; private static final int JOB_ID = 2; private static final Object LOCK = new Object(); private static final SecureRandom random = new SecureRandom(); /** A send from the desktop that waited longer than this isn't sent any more. */ private static final long MAX_SEND_AGE = 24 * 3600_000L; private static final int MSG_CHUNK = 300; private static final int MAX_PUSH = 7 * 1024 * 1024; /** New messages carry their photos; older ones (the first copy of the history) send them when asked. */ private static final long INLINE_RECENT = 2 * 86_400_000L; static boolean configured(Config cfg) { return cfg.relayUrl != null && cfg.relayToken != null && cfg.relayKey != null; } private static SharedPreferences prefs(Context c) { return c.getSharedPreferences("relay", Context.MODE_PRIVATE); } // ---- sealing (relay.ts seal/unseal) ---- static String seal(byte[] key, String author, JSONObject payload) throws Exception { byte[] nonce = new byte[12]; random.nextBytes(nonce); Cipher ci = Cipher.getInstance("AES/GCM/NoPadding"); ci.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, nonce)); ci.updateAAD(("bubble-relay/1/" + author).getBytes(StandardCharsets.UTF_8)); byte[] ct = ci.doFinal(payload.toString().getBytes(StandardCharsets.UTF_8)); byte[] out = new byte[1 + 12 + ct.length]; out[0] = 1; System.arraycopy(nonce, 0, out, 1, 12); System.arraycopy(ct, 0, out, 13, ct.length); return Base64.encodeToString(out, Base64.NO_WRAP); } /** Null for anything not sealed with our key by `author`. */ static JSONObject unseal(byte[] key, String author, String blob) { try { byte[] b = Base64.decode(blob, Base64.DEFAULT); if (b.length < 1 + 12 + 16 || b[0] != 1) return null; Cipher ci = Cipher.getInstance("AES/GCM/NoPadding"); ci.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"), new GCMParameterSpec(128, b, 1, 12)); ci.updateAAD(("bubble-relay/1/" + author).getBytes(StandardCharsets.UTF_8)); return new JSONObject(new String(ci.doFinal(b, 13, b.length - 13), StandardCharsets.UTF_8)); } catch (Exception e) { return null; } } // ---- what's waiting to go ---- /** Names or read/unread/archived changed here (StateSync): tell the desktop soon. */ static void stateChanged(Context c) { if (!configured(Config.get(c))) return; prefs(c).edit().putBoolean("stateDirty", true).apply(); soon(c); } /** Something to tell the desktop: one network job, a few seconds out so a burst shares it. */ static void soon(Context c) { if (!configured(Config.get(c))) return; JobInfo job = new JobInfo.Builder(JOB_ID, new ComponentName(c, RelayJob.class)) .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) .setMinimumLatency(5000) .build(); c.getSystemService(JobScheduler.class).schedule(job); } private static synchronized void addToList(Context c, String key, JSONObject item) { try { JSONArray a = new JSONArray(prefs(c).getString(key, "[]")); a.put(item); prefs(c).edit().putString(key, a.toString()).commit(); } catch (Exception ignored) { } } private static synchronized JSONArray takeList(Context c, String key, int count) { try { JSONArray a = new JSONArray(prefs(c).getString(key, "[]")); JSONArray rest = new JSONArray(); for (int i = count; i < a.length(); i++) rest.put(a.get(i)); prefs(c).edit().putString(key, rest.toString()).commit(); return a; } catch (Exception e) { return new JSONArray(); } } private static JSONArray peekList(Context c, String key) { try { return new JSONArray(prefs(c).getString(key, "[]")); } catch (Exception e) { return new JSONArray(); } } // ---- one sync ---- /** One round with jai (more while there's more). Off the main thread; quiet when jai's unreachable. */ static void sync(Context c) { Config cfg = Config.get(c); if (!configured(cfg)) return; synchronized (LOCK) { try { for (int round = 0; round < 20; round++) if (!syncOnce(c, cfg)) break; prefs(c).edit().putLong("lastSync", System.currentTimeMillis()).remove("error").apply(); } catch (Exception e) { Log.w(TAG, "relay sync failed: " + e.getMessage()); prefs(c).edit().putString("error", e.getMessage() == null ? e.getClass().getSimpleName() : e.getMessage()).apply(); } } } static String status(Context c) { SharedPreferences p = prefs(c); String err = p.getString("error", null); long last = p.getLong("lastSync", 0); if (err != null) return "⚠ " + err; return last == 0 ? "Not yet" : "Last check " + Ui.shortTime(c, last).toLowerCase(); } /** Returns true if there's more to do right away. */ private static boolean syncOnce(Context c, Config cfg) throws Exception { SharedPreferences p = prefs(c); Store store = Store.get(c); List push = new ArrayList<>(); int size = 0; // 1. How the desktop's sends went. JSONArray results = peekList(c, "results"); for (int i = 0; i < results.length(); i++) { String b = seal(cfg.relayKey, "rabbit", results.getJSONObject(i)); push.add(b); size += b.length(); } int resultsPushed = results.length(); // 2. The SIM's messages we haven't passed on (both id ranges: SMS, MMS). long smsLast = p.getLong("smsLast", Sim.SMS_BASE), mmsLast = p.getLong("mmsLast", Sim.MMS_BASE); long[] newSms = {smsLast}, newMms = {mmsLast}; boolean moreMsgs = false; long now = System.currentTimeMillis(); int[] inlineBudget = {3 * 1024 * 1024}; for (int range = 0; range < 2; range++) { long from = range == 0 ? smsLast : mmsLast, to = range == 0 ? Sim.MMS_BASE : Sim.FALLBACK_BASE; JSONArray msgs = new JSONArray(); long max = from; int n = 0; try (Cursor cur = store.db.rawQuery("SELECT id FROM messages WHERE did = ? AND id > ? AND id < ? ORDER BY id LIMIT " + MSG_CHUNK, new String[] {Sim.DID, String.valueOf(from), String.valueOf(to)})) { while (cur.moveToNext()) { Store.Msg m = store.getMessage(cur.getLong(0)); n++; if (m == null) continue; max = Math.max(max, m.id); msgs.put(toJson(c, m, now - m.ts < INLINE_RECENT, inlineBudget)); } } if (n == MSG_CHUNK) moreMsgs = true; if (msgs.length() > 0) { String b = seal(cfg.relayKey, "rabbit", new JSONObject().put("t", "msgs").put("msgs", msgs)); push.add(b); size += b.length(); } if (range == 0) newSms[0] = max; else newMms[0] = max; } // 3. Names and read status, if they changed here. boolean stateDirty = p.getBoolean("stateDirty", false); if (stateDirty) { String b = seal(cfg.relayKey, "rabbit", new JSONObject().put("t", "state") .put("names", store.namesExport()).put("read", store.readStateExport())); push.add(b); size += b.length(); } // 4. Photos the desktop asked for (a few MB per round). JSONArray wants = peekList(c, "wants"); int wantsDone = 0; for (int i = 0; i < wants.length() && size < MAX_PUSH; i++) { JSONObject w = wants.getJSONObject(i); String b = seal(cfg.relayKey, "rabbit", mediaReply(c, w.optLong("id"), w.optInt("index"))); push.add(b); size += b.length(); wantsDone++; } // Out, and in. long since = p.getLong("cursor", 0); JSONArray arr = new JSONArray(); for (String b : push) arr.put(b); byte[] body = new JSONObject().put("device", "rabbit").put("since", since).put("push", arr).toString().getBytes(StandardCharsets.UTF_8); Map h = new HashMap<>(); h.put("Authorization", "Bearer " + cfg.relayToken); h.put("Content-Type", "application/json"); Http.Response r = Http.request("POST", cfg.relayUrl + "/sync", h, body, 120_000); if (r.status == 401) throw new Exception("jai turned down the token (Sync to Rabbit from the desktop again)"); if (r.status != 200) throw new Exception("jai answered " + r.status); JSONObject res = new JSONObject(new String(r.body, StandardCharsets.UTF_8)); // jai has them now. if (resultsPushed > 0) takeList(c, "results", resultsPushed); if (wantsDone > 0) takeList(c, "wants", wantsDone); SharedPreferences.Editor ed = p.edit().putLong("smsLast", newSms[0]).putLong("mmsLast", newMms[0]); if (stateDirty) ed.putBoolean("stateDirty", false); ed.commit(); JSONArray events = res.getJSONArray("events"); for (int i = 0; i < events.length(); i++) handle(c, unseal(cfg.relayKey, "desktop", events.getString(i))); p.edit().putLong("cursor", res.getLong("cursor")).commit(); return res.optBoolean("more") || moreMsgs || peekList(c, "wants").length() > 0 && wantsDone > 0; } private static JSONObject toJson(Context c, Store.Msg m, boolean inline, int[] budget) throws Exception { JSONObject o = new JSONObject().put("id", m.id).put("did", m.did).put("contact", m.contact).put("direction", m.direction) .put("body", m.body == null ? "" : m.body).put("ts", m.ts).put("kind", m.kind); if (m.sender != null) o.put("sender", m.sender); List refs = m.media(); if (!refs.isEmpty()) { JSONArray media = new JSONArray(); for (int i = 0; i < refs.size(); i++) { JSONObject ref = refs.get(i); JSONObject out = new JSONObject().put("mime", ref.optString("mime", "application/octet-stream")); String url = ref.optString("url", ""); File f = null; if (inline || !url.startsWith("mmspart:")) f = Media.resolve(c, m.id, i); if (f != null && (f.length() <= budget[0] || !url.startsWith("mmspart:"))) { budget[0] -= (int) f.length(); out.put("data", Base64.encodeToString(Media.read(f), Base64.NO_WRAP)); if (ref.optInt("width") > 0) out.put("width", ref.optInt("width")).put("height", ref.optInt("height")); } else if (url.startsWith("mmspart:")) { out.put("url", url); } else continue; media.put(out); } if (media.length() > 0) o.put("media", media); } return o; } private static JSONObject mediaReply(Context c, long id, int index) throws Exception { JSONObject out = new JSONObject().put("t", "media").put("id", id).put("index", index); Store.Msg m = Store.get(c).getMessage(id); // Only the SIM's own attachments go this way. File f = m != null && Sim.isSim(m.did) ? Media.resolve(c, id, index) : null; if (f == null) return out.put("missing", true); JSONObject ref = m.media().get(index); out.put("mime", ref.optString("mime", "application/octet-stream")).put("data", Base64.encodeToString(Media.read(f), Base64.NO_WRAP)); if (ref.optInt("width") > 0) out.put("width", ref.optInt("width")).put("height", ref.optInt("height")); return out; } // ---- what the desktop sent ---- private static void handle(Context c, JSONObject p) { if (p == null) return; try { switch (p.optString("t")) { case "send": onSend(c, p); break; case "state": onState(c, p); break; case "want": { JSONArray items = p.optJSONArray("items"); for (int i = 0; items != null && i < items.length(); i++) addToList(c, "wants", items.getJSONObject(i)); break; } default: break; } } catch (Exception e) { Log.w(TAG, "skipped a message from the desktop: " + e.getMessage()); } } private static void onState(Context c, JSONObject p) throws Exception { Store store = Store.get(c); JSONArray names = p.optJSONArray("names"), read = p.optJSONArray("read"); if (names != null) store.namesImport(names); if (read != null) store.readStateImport(read); StateSync.export(c); Notifier.sweep(c); Sync.changed(); } /** Each send from the desktop goes out at most once, ever: remembered before it's tried. */ private static synchronized boolean firstTime(Context c, String id) { SharedPreferences p = prefs(c); Set done = new HashSet<>(p.getStringSet("sent", new HashSet<>())); long now = System.currentTimeMillis(); for (String e : done) if (e.startsWith(id + "\t")) return false; // Forget ones old enough to be refused by age anyway. done.removeIf(e -> { try { return now - Long.parseLong(e.substring(e.indexOf('\t') + 1)) > 2 * MAX_SEND_AGE; } catch (Exception x) { return true; } }); done.add(id + "\t" + now); return p.edit().putStringSet("sent", done).commit(); } private static void result(Context c, String id, long msgId, String error) { try { JSONObject o = new JSONObject().put("t", "sent").put("id", id); o.put("msgId", msgId != 0 ? msgId : JSONObject.NULL); o.put("error", error != null ? error : JSONObject.NULL); addToList(c, "results", o); } catch (Exception ignored) { } soon(c); } private static void onSend(Context c, JSONObject p) throws Exception { String id = p.getString("id"); if (!id.matches("[0-9a-fA-F-]{36}") || !firstTime(c, id)) return; String contact = p.optString("contact", ""); String text = p.optString("text", ""); if (contact.isEmpty() || !contact.matches("[0-9,]+|[^,]+")) { result(c, id, 0, "No one to send it to."); return; } if (System.currentTimeMillis() - p.optLong("ts") > MAX_SEND_AGE) { result(c, id, 0, "Waited over a day for the Rabbit, so it wasn't sent. Send it again?"); return; } if (!Sim.isDefault(c)) { result(c, id, 0, "bubble isn't the Rabbit's texting app, so it can't use the SIM."); return; } List photos = new ArrayList<>(); JSONArray media = p.optJSONArray("media"); for (int i = 0; media != null && i < media.length(); i++) { JSONObject a = media.getJSONObject(i); byte[] data = Base64.decode(a.getString("data"), Base64.DEFAULT); String mime = a.optString("mime", "application/octet-stream"); String file = Media.save(c, data, mime); int w = a.optInt("width"), hgt = a.optInt("height"); if (w == 0 && mime.startsWith("image/")) { BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; BitmapFactory.decodeByteArray(data, 0, data.length, o); w = o.outWidth; hgt = o.outHeight; } photos.add(new Sender.Photo(file, mime, Math.max(0, w), Math.max(0, hgt))); } if (text.isEmpty() && photos.isEmpty()) { result(c, id, 0, "It was empty."); return; } Sender.send(c, Sim.DID, contact, text, photos, (msgId, error) -> result(c, id, msgId, error)); } }