# -*- coding: utf-8 -*-
"""Frida-based IPA dumper (frida 17.x compatible - pure libc, no ObjC bridge)."""
import frida, sys, os, struct, zipfile, time, plistlib

HOST = "127.0.0.1:27042"
CHUNK = 1 << 20  # 1MB per RPC read

JS = r'''
'use strict';
function sym(name){
  try { return Module.getGlobalExportByName(name); } catch (e) {}
  var mods = Process.enumerateModules();
  for (var i = 0; i < mods.length; i++){
    try {
      var p = mods[i].getExportByName(name);
      if (p && !p.isNull()) return p;
    } catch (e2) {}
  }
  throw new Error('cannot resolve symbol: ' + name);
}
var p_opendir  = new NativeFunction(sym('opendir'),  'pointer', ['pointer']);
var p_readdir  = new NativeFunction(sym('readdir'),  'pointer', ['pointer']);
var p_closedir = new NativeFunction(sym('closedir'), 'int',     ['pointer']);
var p_readlink = new NativeFunction(sym('readlink'), 'long',    ['pointer','pointer','int']);
var p_fopen    = new NativeFunction(sym('fopen'),    'pointer', ['pointer','pointer']);
var p_fread    = new NativeFunction(sym('fread'),    'ulong',   ['pointer','ulong','ulong','pointer']);
var p_fseek    = new NativeFunction(sym('fseek'),    'int',     ['pointer','long','int']);
var p_ftell    = new NativeFunction(sym('ftell'),    'long',    ['pointer']);
var p_fclose   = new NativeFunction(sym('fclose'),   'int',     ['pointer']);

function fsize(path){
  var f = p_fopen(Memory.allocUtf8String(path), Memory.allocUtf8String('rb'));
  if (f.isNull()) return -1;
  p_fseek(f, 0, 2); // SEEK_END
  var s = p_ftell(f).valueOf();
  p_fclose(f);
  return s;
}

function readlinkTo(path){
  var buf = Memory.alloc(1024);
  var n = p_readlink(Memory.allocUtf8String(path), buf, 1023);
  if (n <= 0) return null;
  return buf.readCString();
}

function listAll(root){
  var out = [];
  var stack = [{abs: root, rel: ''}];
  while (stack.length){
    var cur = stack.pop();
    var d = p_opendir(Memory.allocUtf8String(cur.abs));
    if (d.isNull()) continue;
    for (;;){
      var e = p_readdir(d);
      if (e.isNull()) break;
      var reclen = e.add(16).readU16();
      if (reclen === 0) break;
      var dtype = e.add(20).readU16() & 0xff;
      var name = e.add(22).readCString();
      if (name === '.' || name === '..') continue;
      var rel = cur.rel ? cur.rel + '/' + name : name;
      var abs = cur.abs + '/' + name;
      if (dtype === 4) { stack.push({abs: abs, rel: rel}); }        // DT_DIR
      else if (dtype === 10) {                                       // DT_LNK
        out.push({rel: rel, type: 10, target: readlinkTo(abs)});
      }
      else { out.push({rel: rel, type: dtype}); }
      if (reclen === 0) break;
    }
    p_closedir(d);
  }
  return out;
}

rpc.exports = {
  listFiles: function(dir){ return listAll(dir); },
  fileSize: function(p){ return fsize(p); },
  readChunk: function(path, off, len){
    var f = p_fopen(Memory.allocUtf8String(path), Memory.allocUtf8String('rb'));
    if (f.isNull()) return null;
    p_fseek(f, off, 0); // SEEK_SET
    var buf = Memory.alloc(len);
    var got = p_fread(buf, 1, len, f).valueOf();
    p_fclose(f);
    if (got <= 0) return null;
    return buf.readByteArray(got);
  },
  mainModule: function(){
    var m = Process.enumerateModules()[0];
    return { name: m.name, base: m.base.toString(), size: m.size, path: m.path };
  },
  readMem: function(addr, len){
    return Memory.readByteArray(ptr(addr), len);
  }
};
'''


def macho_crypt_info(path):
    """Return (slice_off, cryptoff, cryptsize, cryptid, cryptid_file_off) or None."""
    MH64 = b'\xcf\xfa\xed\xfe'
    FAT_BE = b'\xca\xfe\xba\xbe'
    FAT_LE = b'\xbe\xba\xfe\xca'
    with open(path, 'rb') as f:
        magic = f.read(4)
        if magic in (FAT_BE, FAT_LE):
            big = (magic == FAT_BE)
            f.seek(4)
            hdr = f.read(24)
            fmt = '>I' if big else '<I'
            ncmds = struct.unpack(fmt + 'I', hdr[8:12])[0]
            slice_off = None
            for _ in range(ncmds):
                e = f.read(20)
                cpu, _sub, off, _size, _align = struct.unpack(fmt + 'IIIII', e)
                if cpu == 0x0100000C:  # arm64
                    slice_off = off
                    break
            if slice_off is None:
                return None
        elif magic == MH64:
            slice_off = 0
        else:
            return None
        f.seek(slice_off)
        hdr = f.read(32)
        if len(hdr) < 32 or hdr[:4] != MH64:
            return None
        ncmds = struct.unpack('<I', hdr[16:20])[0]
        pos = slice_off + 32
        for _ in range(ncmds):
            f.seek(pos)
            lc = f.read(8)
            if len(lc) < 8:
                break
            cmd, cmdsize = struct.unpack('<II', lc)
            if cmd == 0x2C and cmdsize >= 24:  # LC_ENCRYPTION_INFO_64
                f.seek(pos + 8)
                cryptoff, cryptsize, cryptid = struct.unpack('<III', f.read(12))
                return (slice_off, cryptoff, cryptsize, cryptid, pos + 16)
            pos += cmdsize
    return None


def get_app_path(dev, bundle_id):
    for a in dev.enumerate_applications(scope="full"):
        if a.identifier == bundle_id:
            return a.parameters.get('path')
    return None


def attach_poll(dev, target, timeout=180):
    t0 = time.time()
    last = None
    while time.time() - t0 < timeout:
        try:
            return dev.attach(target)
        except Exception as e:
            last = e
            time.sleep(2)
    raise RuntimeError(f"attach timeout: {last}")


def dump_app(dev, bundle_id, out_dir, attach_mode=False):
    print(f"=== [{bundle_id}] ===", flush=True)
    app_path = get_app_path(dev, bundle_id)
    if not app_path:
        raise RuntimeError("khong tim thay app: " + bundle_id)
    print(f"[*] bundle: {app_path}", flush=True)

    session, pid = None, None
    if not attach_mode:
        try:
            print("[*] spawning...", flush=True)
            pid = dev.spawn([bundle_id])
            session = dev.attach(pid)
            print(f"[*] spawned pid={pid}", flush=True)
        except Exception as e:
            print(f"[!] spawn failed: {e} -> attach mode", flush=True)
    if session is None:
        print("[*] MO APP TREN IPHONE (neu chua mo)...", flush=True)
        session = attach_poll(dev, bundle_id)
        print("[*] attach OK", flush=True)

    script = session.create_script(JS)

    def on_msg(m, _d):
        if m['type'] == 'error':
            print("[JS] " + m.get('description', str(m)), flush=True)
    script.on('message', on_msg)
    script.load()
    if pid is not None:
        dev.resume(pid)
    time.sleep(3)

    subs = script.exports_sync.listFiles(app_path)
    print(f"[*] {len(subs)} entries", flush=True)

    app_name = os.path.basename(app_path)
    local_app = os.path.join(out_dir, "Payload", app_name)
    os.makedirs(local_app, exist_ok=True)

    total = 0
    skipped = []
    for e in subs:
        rel = e['rel']
        if rel.startswith('._') or '/._' in rel or rel.endswith('.DS_Store'):
            continue
        if e['type'] == 10:
            skipped.append(f"{rel} (symlink -> {e.get('target')})")
            continue
        if e['type'] not in (8, 0):  # chi file thuong
            continue
        remote = f"{app_path}/{rel}"
        try:
            size = script.exports_sync.fileSize(remote)
            if size is None or size < 0:
                size = 0
            local = os.path.join(local_app, *rel.split('/'))
            os.makedirs(os.path.dirname(local), exist_ok=True)
            with open(local, 'wb') as f:
                off = 0
                lastp = 0
                while off < size:
                    n = min(CHUNK, size - off)
                    data = script.exports_sync.readChunk(remote, off, n)
                    if data is None:
                        raise RuntimeError("read null")
                    f.write(data)
                    off += len(data)
                    mb = off >> 20
                    if mb >= lastp + 32:
                        print(f"    {rel}: {mb} MB", flush=True)
                        lastp = mb
            total += size
        except Exception as ex:
            skipped.append(f"{rel} ({type(ex).__name__}: {ex})")
    print(f"[*] downloaded {total/1048576:.1f} MB, skipped {len(skipped)}", flush=True)
    for s in skipped[:30]:
        print("    SKIP:", s, flush=True)

    # --- decrypt main binary if FairPlay-encrypted ---
    try:
        with open(os.path.join(local_app, "Info.plist"), 'rb') as f:
            pl = plistlib.load(f)
        exe_name = pl.get('CFBundleExecutable')
    except Exception as ex:
        exe_name = None
        print(f"[!] Info.plist: {ex}", flush=True)

    if exe_name:
        exe_path = os.path.join(local_app, exe_name)
        ci = macho_crypt_info(exe_path)
        if ci:
            slice_off, cryptoff, cryptsize, cryptid, cryptid_off = ci
            print(f"[*] {exe_name}: cryptoff={cryptoff} cryptsize={cryptsize} cryptid={cryptid}", flush=True)
            if cryptsize > 0 and cryptid:
                mm = script.exports_sync.mainModule()
                base = int(mm['base'], 16)
                print(f"[*] decrypting via memory (base {mm['base']})...", flush=True)
                try:
                    with open(exe_path, 'r+b') as f:
                        f.seek(slice_off + cryptoff)
                        done = 0
                        while done < cryptsize:
                            n = min(4 << 20, cryptsize - done)
                            buf = script.exports_sync.readMem(hex(base + cryptoff + done), n)
                            f.write(buf)
                            done += n
                        f.seek(cryptid_off)
                        f.write(struct.pack('<I', 0))  # cryptid = 0
                    print(f"[*] decrypted {cryptsize/1048576:.1f} MB OK", flush=True)
                except Exception as ex:
                    print(f"[!] DECRYPT FAILED: {ex}", flush=True)
        else:
            print(f"[*] {exe_name}: not Mach-O / no encryption LC", flush=True)

    try:
        session.detach()
    except Exception:
        pass

    ipa = os.path.join(out_dir, app_name[:-4] + ".ipa")
    print(f"[*] zipping -> {ipa}", flush=True)
    with zipfile.ZipFile(ipa, 'w', zipfile.ZIP_DEFLATED, compresslevel=6) as z:
        for root, _dirs, files in os.walk(os.path.join(out_dir, "Payload")):
            for fn in files:
                fp = os.path.join(root, fn)
                arc = os.path.relpath(fp, out_dir).replace('\\', '/')
                z.write(fp, arc)
    print(f"=== DONE: {ipa} ({os.path.getsize(ipa)/1048576:.1f} MB) ===", flush=True)


def main():
    dm = frida.get_device_manager()
    dev = dm.add_remote_device(HOST)
    args = [a for a in sys.argv[1:]]
    attach_mode = "--attach" in args
    args = [a for a in args if a != "--attach"]
    out_dir = os.path.abspath(args[0]) if args and os.path.isdir(args[0]) else \
        os.path.join(os.path.dirname(os.path.abspath(__file__)), "out")
    bundles = [a for a in args if not os.path.isdir(a)] or ["vn.gsm.md", "ru.inDriver-ru"]
    os.makedirs(os.path.join(out_dir, "Payload"), exist_ok=True)
    for b in bundles:
        try:
            dump_app(dev, b, out_dir, attach_mode)
        except Exception:
            import traceback
            traceback.print_exc()
    print("ALL DONE", flush=True)


if __name__ == "__main__":
    main()
