#!/usr/bin/env python3 """Native messaging host for the Quick Profile extension. Firefox spawns this once per message: read one request, write one reply, exit. Requests: {"cmd": "list"} -> {"ok": true, "profiles": [...]} {"cmd": "launch", "path": "..."} -> {"ok": true} """ import base64 import glob import json import mimetypes import os import shutil import sqlite3 import struct import subprocess import sys import zlib FIREFOX_DIR = os.path.expanduser("~/.mozilla/firefox") GROUPS_DIR = os.path.join(FIREFOX_DIR, "Profile Groups") AVATAR_PREFIX = "chrome/browser/content/browser/profiles/assets/" # Mirrors STANDARD_AVATARS in SelectableProfile.sys.mjs; anything else is a # custom image stored in "Profile Groups/avatars/". STANDARD_AVATARS = { "barbell", "bike", "book", "briefcase", "canvas", "craft", "default-favicon", "diamond", "flower", "folder", "hammer", "heart", "heart-rate", "history", "leaf", "lightbulb", "makeup", "message", "musical-note", "palette", "paw-print", "plane", "present", "shopping", "soccer", "sparkle-single", "star", "video-game-controller", } def read_message(): raw_len = sys.stdin.buffer.read(4) if len(raw_len) < 4: sys.exit(0) (length,) = struct.unpack("@I", raw_len) return json.loads(sys.stdin.buffer.read(length)) def send_message(msg): data = json.dumps(msg).encode() sys.stdout.buffer.write(struct.pack("@I", len(data))) sys.stdout.buffer.write(data) sys.stdout.buffer.flush() def firefox_binary(): """The Firefox that spawned us, so we launch the same build.""" try: exe = os.readlink(f"/proc/{os.getppid()}/exe") if os.path.basename(exe).startswith("firefox"): return exe except OSError: pass return shutil.which("firefox") or "firefox" def read_jar(jar_path, names): """Extract `names` from a Mozilla jar. omni.ja is an "optimized" jar: the central directory sits at the front of the file, after a 4-byte readahead header, so zipfile rejects it. Walk the central directory ourselves instead. """ wanted = set(names) out = {} with open(jar_path, "rb") as f: data = f.read() pos = data.find(b"PK\x01\x02") while pos != -1 and data[pos:pos + 4] == b"PK\x01\x02" and wanted: (method, csize, name_len, extra_len, comment_len, local_off) = ( struct.unpack_from(" {"16": svg, "48": svg} or {"custom": data URL}.""" images = {} standard = [a for a in avatars if a in STANDARD_AVATARS] if standard: app_dir = os.path.dirname(os.path.realpath(firefox_binary())) omni = os.path.join(app_dir, "browser", "omni.ja") try: files = read_jar( omni, [f"{AVATAR_PREFIX}{size}_{a}.svg" for a in standard for size in (16, 48)], ) except OSError: files = {} for a in standard: images[a] = { size: files[f"{AVATAR_PREFIX}{size}_{a}.svg"].decode() for size in ("16", "48") if f"{AVATAR_PREFIX}{size}_{a}.svg" in files } for a in avatars: if a in STANDARD_AVATARS: continue path = os.path.join(GROUPS_DIR, "avatars", a) try: with open(path, "rb") as f: mime = mimetypes.guess_type(path)[0] or "image/png" images[a] = { "custom": f"data:{mime};base64,{base64.b64encode(f.read()).decode()}" } except OSError: images[a] = {} return images def list_profiles(): profiles = {} for db in sorted(glob.glob(os.path.join(GROUPS_DIR, "*.sqlite"))): try: conn = sqlite3.connect(f"file:{db}?mode=ro", uri=True) rows = conn.execute( "SELECT path, name, avatar, themeFg, themeBg FROM Profiles ORDER BY id" ).fetchall() conn.close() except sqlite3.Error: continue for path, name, avatar, fg, bg in rows: abspath = path if os.path.isabs(path) else os.path.join(FIREFOX_DIR, path) profiles.setdefault(abspath, { "path": abspath, "name": name, "avatar": avatar, "themeFg": fg, "themeBg": bg, }) result = list(profiles.values()) images = avatar_images({p["avatar"] for p in result}) for p in result: p["images"] = images.get(p["avatar"], {}) return result def launch(path): # Same arguments as SelectableProfileService.launchInstance. If the # profile is already running, Firefox's remoting service focuses it. if not os.path.isdir(path): raise ValueError(f"profile directory not found: {path}") subprocess.Popen( [firefox_binary(), "--profile", path, "--profiles-activate"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True, ) def main(): msg = read_message() try: cmd = msg.get("cmd") if cmd == "list": send_message({"ok": True, "profiles": list_profiles()}) elif cmd == "launch": launch(msg["path"]) send_message({"ok": True}) else: send_message({"ok": False, "error": f"unknown command: {cmd}"}) except Exception as e: send_message({"ok": False, "error": str(e)}) if __name__ == "__main__": main()