unpack method

String unpack()

Unpacks P.A.C.K.E.R. packed js code

Implementation

String unpack() {
  var lst = _filterargs();
  String payload = lst[0];
  List<String> symtab = lst[1];
  int radix = lst[2];
  int count = lst[3];
  late UnBaser unBaser;

  String getString(int c, {int? a}) {
    a ??= radix;
    var foo = String.fromCharCode(c % a + 161);
    if (c < a) {
      return foo;
    } else {
      return getString(c ~/ a, a: a) + foo;
    }
  }

  if (count != symtab.length) {
    throw ("Malformed p.a.c.k.e.r. symtab.");
  }
  try {
    unBaser = UnBaser(radix);
  } catch (_) {
    throw ("base conversion error");
  }

  payload = payload.replaceAll("\\\\", "\\").replaceAll("\\'", "'");
  var p = RegExp(r'eval\(function\(p,a,c,k,e.+?String\.fromCharCode\(([^)]+)')
      .firstMatch(payload);
  bool pNew = false;
  if (p?.groupCount != 0) {
    pNew = RegExp(r'String\.fromCharCode\(([^)]+)')
            .firstMatch(payload)
            ?.group(0)
            ?.split('+')[0] ==
        '161';
  }
  if (pNew) {
    for (int i = count - 1; i != -1; i--) {
      payload = payload.replaceAll(getString(i), symtab[i]);
    }
    return _replaceJsStrings(_replaceStrings(payload));
  }
  var source = payload;
  var reg = RegExp(
    r"\b\w+\b",
  ).allMatches(payload);
  int correct = 0;
  for (var element in reg) {
    var word = payload.substring(element.start, element.end);
    var lookUp = "";
    if (radix == 1) {
      lookUp = symtab[int.parse(word)];
    } else {
      var v = unBaser.toBase10(word);
      if (v < symtab.length) {
        lookUp = symtab[v];
        if (lookUp.isEmpty) lookUp = word;
      } else {
        lookUp = word;
      }
    }
    source = source.replaceRange(element.start + correct,
        element.start + word.length + correct, lookUp);
    correct += lookUp.length - (element.end - element.start);
  }
  return _replaceStrings(source);
}