+static std::string Temporary(std::filebuf &file, const Split &split) {
+ std::string temp(split.dir + ".ldid." + split.base);
+ mkdir_p(split.dir);
+ _assert_(file.open(temp.c_str(), std::ios::out | std::ios::trunc | std::ios::binary) == &file, "open(): %s", temp.c_str());
+ return temp;
+}
+
+static void Commit(const std::string &path, const std::string &temp) {
+ struct stat info;
+ if (_syscall(stat(path.c_str(), &info), ENOENT) == 0) {
+#ifndef __WIN32__
+ _syscall(chown(temp.c_str(), info.st_uid, info.st_gid));
+#endif
+ _syscall(chmod(temp.c_str(), info.st_mode));
+ }
+
+ _syscall(rename(temp.c_str(), path.c_str()));
+}
+#endif
+
+namespace ldid {
+
+void Sign(const void *idata, size_t isize, std::streambuf &output, const std::string &identifier, const std::string &entitlements, const std::string &key, const Slots &slots) {
+ std::string team;
+
+#ifndef LDID_NOSMIME
+ if (!key.empty()) {
+ std::stringbuf data;
+ Stuff stuff(key);
+ auto name(X509_get_subject_name(stuff));
+ _assert(name != NULL);
+ auto index(X509_NAME_get_index_by_NID(name, NID_organizationalUnitName, -1));
+ _assert(index >= 0);
+ auto next(X509_NAME_get_index_by_NID(name, NID_organizationalUnitName, index));
+ _assert(next == -1);
+ auto entry(X509_NAME_get_entry(name, index));
+ _assert(entry != NULL);
+ auto asn(X509_NAME_ENTRY_get_data(entry));
+ _assert(asn != NULL);
+ team.assign(reinterpret_cast<char *>(ASN1_STRING_data(asn)), ASN1_STRING_length(asn));
+ }
+#endif
+
+ Allocate(idata, isize, output, fun([&](const MachHeader &mach_header, size_t size) -> size_t {
+ size_t alloc(sizeof(struct SuperBlob));
+
+ uint32_t special(0);
+
+ special = std::max(special, CSSLOT_REQUIREMENTS);
+ alloc += sizeof(struct BlobIndex);
+ alloc += 0xc;
+
+ if (!entitlements.empty()) {
+ special = std::max(special, CSSLOT_ENTITLEMENTS);
+ alloc += sizeof(struct BlobIndex);
+ alloc += sizeof(struct Blob);
+ alloc += entitlements.size();
+ }
+
+ special = std::max(special, CSSLOT_CODEDIRECTORY);
+ alloc += sizeof(struct BlobIndex);
+ alloc += sizeof(struct Blob);
+ alloc += sizeof(struct CodeDirectory);
+ alloc += identifier.size() + 1;
+
+ if (!team.empty())
+ alloc += team.size() + 1;
+
+ if (!key.empty()) {
+ alloc += sizeof(struct BlobIndex);
+ alloc += sizeof(struct Blob);
+ // XXX: this is just a "sufficiently large number"
+ alloc += 0x3000;
+ }
+
+ _foreach (slot, slots)
+ special = std::max(special, slot.first);
+
+ mach_header.ForSection(fun([&](const char *segment, const char *section, void *data, size_t size) {
+ if (strcmp(segment, "__TEXT") == 0 && section != NULL && strcmp(section, "__info_plist") == 0)
+ special = std::max(special, CSSLOT_INFOSLOT);
+ }));
+
+ uint32_t normal((size + PageSize_ - 1) / PageSize_);
+ alloc = Align(alloc + (special + normal) * LDID_SHA1_DIGEST_LENGTH, 16);
+ return alloc;
+ }), fun([&](const MachHeader &mach_header, std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
+ Blobs blobs;
+
+ if (true) {
+ std::stringbuf data;
+
+ Blobs requirements;
+ put(data, CSMAGIC_REQUIREMENTS, requirements);
+
+ insert(blobs, CSSLOT_REQUIREMENTS, data);
+ }
+
+ if (!entitlements.empty()) {
+ std::stringbuf data;
+ put(data, entitlements.data(), entitlements.size());
+ insert(blobs, CSSLOT_ENTITLEMENTS, CSMAGIC_EMBEDDED_ENTITLEMENTS, data);
+ }
+
+ if (true) {
+ std::stringbuf data;
+
+ Slots posts(slots);
+
+ mach_header.ForSection(fun([&](const char *segment, const char *section, void *data, size_t size) {
+ if (strcmp(segment, "__TEXT") == 0 && section != NULL && strcmp(section, "__info_plist") == 0)
+ sha1(posts[CSSLOT_INFOSLOT], data, size);
+ }));
+
+ uint32_t special(0);
+ _foreach (blob, blobs)
+ special = std::max(special, blob.first);
+ _foreach (slot, posts)
+ special = std::max(special, slot.first);
+ uint32_t normal((limit + PageSize_ - 1) / PageSize_);
+
+ CodeDirectory directory;
+ directory.version = Swap(uint32_t(0x00020200));
+ directory.flags = Swap(uint32_t(0));
+ directory.nSpecialSlots = Swap(special);
+ directory.codeLimit = Swap(uint32_t(limit));
+ directory.nCodeSlots = Swap(normal);
+ directory.hashSize = LDID_SHA1_DIGEST_LENGTH;
+ directory.hashType = CS_HASHTYPE_SHA1;
+ directory.spare1 = 0x00;
+ directory.pageSize = PageShift_;
+ directory.spare2 = Swap(uint32_t(0));
+ directory.scatterOffset = Swap(uint32_t(0));
+ directory.spare3 = Swap(uint32_t(0));
+ directory.codeLimit64 = Swap(uint64_t(0));
+
+ uint32_t offset(sizeof(Blob) + sizeof(CodeDirectory));
+
+ directory.identOffset = Swap(uint32_t(offset));
+ offset += identifier.size() + 1;
+
+ if (team.empty())
+ directory.teamIDOffset = Swap(uint32_t(0));
+ else {
+ directory.teamIDOffset = Swap(uint32_t(offset));
+ offset += team.size() + 1;
+ }
+
+ offset += LDID_SHA1_DIGEST_LENGTH * special;
+ directory.hashOffset = Swap(uint32_t(offset));
+ offset += LDID_SHA1_DIGEST_LENGTH * normal;
+
+ put(data, &directory, sizeof(directory));
+
+ put(data, identifier.c_str(), identifier.size() + 1);
+ put(data, team.c_str(), team.size() + 1);
+
+ uint8_t storage[special + normal][LDID_SHA1_DIGEST_LENGTH];
+ uint8_t (*hashes)[LDID_SHA1_DIGEST_LENGTH] = storage + special;
+
+ memset(storage, 0, sizeof(*storage) * special);
+
+ _foreach (blob, blobs) {
+ auto local(reinterpret_cast<const Blob *>(&blob.second[0]));
+ sha1((uint8_t *) (hashes - blob.first), local, Swap(local->length));
+ }
+
+ _foreach (slot, posts) {
+ _assert(sizeof(*hashes) == slot.second.size());
+ memcpy(hashes - slot.first, slot.second.data(), slot.second.size());
+ }
+
+ if (normal != 1)
+ for (size_t i = 0; i != normal - 1; ++i)
+ sha1(hashes[i], (PageSize_ * i < overlap.size() ? overlap.data() : top) + PageSize_ * i, PageSize_);
+ if (normal != 0)
+ sha1(hashes[normal - 1], top + PageSize_ * (normal - 1), ((limit - 1) % PageSize_) + 1);
+
+ put(data, storage, sizeof(storage));
+
+ insert(blobs, CSSLOT_CODEDIRECTORY, CSMAGIC_CODEDIRECTORY, data);
+ }
+
+#ifndef LDID_NOSMIME
+ if (!key.empty()) {
+ std::stringbuf data;
+ const std::string &sign(blobs[CSSLOT_CODEDIRECTORY]);
+
+ Stuff stuff(key);
+ Buffer bio(sign);
+
+ Signature signature(stuff, sign);
+ Buffer result(signature);
+ std::string value(result);
+ put(data, value.data(), value.size());
+
+ insert(blobs, CSSLOT_SIGNATURESLOT, CSMAGIC_BLOBWRAPPER, data);
+ }
+#endif
+
+ return put(output, CSMAGIC_EMBEDDED_SIGNATURE, blobs);
+ }));
+}
+
+#ifndef LDID_NOTOOLS
+static void Unsign(void *idata, size_t isize, std::streambuf &output) {
+ Allocate(idata, isize, output, fun([](const MachHeader &mach_header, size_t size) -> size_t {
+ return 0;
+ }), fun([](const MachHeader &mach_header, std::streambuf &output, size_t limit, const std::string &overlap, const char *top) -> size_t {
+ return 0;
+ }));
+}
+
+std::string DiskFolder::Path(const std::string &path) {
+ return path_ + "/" + path;
+}
+
+DiskFolder::DiskFolder(const std::string &path) :
+ path_(path)
+{
+}
+
+DiskFolder::~DiskFolder() {
+ if (!std::uncaught_exception())
+ for (const auto &commit : commit_)
+ Commit(commit.first, commit.second);
+}
+
+void DiskFolder::Find(const std::string &root, const std::string &base, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)>&code) {
+ std::string path(Path(root) + base);
+
+ DIR *dir(opendir(path.c_str()));
+ _assert(dir != NULL);
+ _scope({ _syscall(closedir(dir)); });
+
+ while (auto child = readdir(dir)) {
+ std::string name(child->d_name);
+ if (name == "." || name == "..")
+ continue;
+ if (Starts(name, ".ldid."))
+ continue;
+
+ bool directory;
+
+#ifdef __WIN32__
+ struct stat info;
+ _syscall(stat(path.c_str(), &info));
+ if (false);
+ else if (S_ISDIR(info.st_mode))
+ directory = true;
+ else if (S_ISREG(info.st_mode))
+ directory = false;
+ else
+ _assert_(false, "st_mode=%x", info.st_mode);
+#else
+ switch (child->d_type) {
+ case DT_DIR:
+ directory = true;
+ break;
+ case DT_REG:
+ directory = false;
+ break;
+ default:
+ _assert_(false, "d_type=%u", child->d_type);
+ }
+#endif
+
+ if (directory)
+ Find(root, base + name + "/", code);
+ else
+ code(base + name, fun([&](const Functor<void (std::streambuf &, std::streambuf &)> &code) {
+ std::string access(root + base + name);
+ _assert_(Open(access, fun([&](std::streambuf &data, const void *flag) {
+ NullBuffer save;
+ code(data, save);
+ })), "open(): %s", access.c_str());
+ }));
+ }
+}
+
+void DiskFolder::Save(const std::string &path, const void *flag, const Functor<void (std::streambuf &)> &code) {
+ std::filebuf save;
+ auto from(Path(path));
+ commit_[from] = Temporary(save, from);
+ code(save);
+}
+
+bool DiskFolder::Open(const std::string &path, const Functor<void (std::streambuf &, const void *)> &code) {
+ std::filebuf data;
+ auto result(data.open(Path(path).c_str(), std::ios::binary | std::ios::in));
+ if (result == NULL)
+ return false;
+ _assert(result == &data);
+ code(data, NULL);
+ return true;
+}
+
+void DiskFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)>&code) {
+ Find(path, "", code);
+}
+#endif
+
+SubFolder::SubFolder(Folder &parent, const std::string &path) :
+ parent_(parent),
+ path_(path)
+{
+}
+
+void SubFolder::Save(const std::string &path, const void *flag, const Functor<void (std::streambuf &)> &code) {
+ return parent_.Save(path_ + path, flag, code);
+}
+
+bool SubFolder::Open(const std::string &path, const Functor<void (std::streambuf &, const void *)> &code) {
+ return parent_.Open(path_ + path, code);
+}
+
+void SubFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)> &code) {
+ return parent_.Find(path_ + path, code);
+}
+
+std::string UnionFolder::Map(const std::string &path) {
+ auto remap(remaps_.find(path));
+ if (remap == remaps_.end())
+ return path;
+ return remap->second;
+}
+
+void UnionFolder::Map(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)> &code, const std::string &file, const Functor<void (const Functor<void (std::streambuf &, const void *)> &)> &save) {
+ if (file.size() >= path.size() && file.substr(0, path.size()) == path)
+ code(file.substr(path.size()), fun([&](const Functor<void (std::streambuf &, std::streambuf &)> &code) {
+ save(fun([&](std::streambuf &data, const void *flag) {
+ parent_.Save(file, flag, fun([&](std::streambuf &save) {
+ code(data, save);
+ }));
+ }));
+ }));
+}
+
+UnionFolder::UnionFolder(Folder &parent) :
+ parent_(parent)
+{
+}
+
+void UnionFolder::Save(const std::string &path, const void *flag, const Functor<void (std::streambuf &)> &code) {
+ return parent_.Save(Map(path), flag, code);
+}
+
+bool UnionFolder::Open(const std::string &path, const Functor<void (std::streambuf &, const void *)> &code) {
+ auto file(resets_.find(path));
+ if (file == resets_.end())
+ return parent_.Open(Map(path), code);
+ auto &entry(file->second);
+
+ auto &data(entry.first);
+ data.pubseekpos(0, std::ios::in);
+ code(data, entry.second);
+ return true;
+}
+
+void UnionFolder::Find(const std::string &path, const Functor<void (const std::string &, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &)> &code) {
+ parent_.Find(path, fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &save) {
+ if (deletes_.find(path + name) == deletes_.end())
+ code(name, save);
+ }));
+
+ for (auto &reset : resets_)
+ Map(path, code, reset.first, fun([&](const Functor<void (std::streambuf &, const void *)> &code) {
+ auto &entry(reset.second);
+ entry.first.pubseekpos(0, std::ios::in);
+ code(entry.first, entry.second);
+ }));
+
+ for (auto &remap : remaps_)
+ Map(path, code, remap.first, fun([&](const Functor<void (std::streambuf &, const void *)> &code) {
+ parent_.Open(remap.second, fun([&](std::streambuf &data, const void *flag) {
+ code(data, flag);
+ }));
+ }));
+}
+
+#ifndef LDID_NOTOOLS
+static size_t copy(std::streambuf &source, std::streambuf &target) {
+ size_t total(0);
+ for (;;) {
+ char data[4096];
+ size_t writ(source.sgetn(data, sizeof(data)));
+ if (writ == 0)
+ break;
+ _assert(target.sputn(data, writ) == writ);
+ total += writ;
+ }
+ return total;
+}
+
+#ifndef LDID_NOPLIST
+static plist_t plist(const std::string &data) {
+ plist_t plist(NULL);
+ if (Starts(data, "bplist00"))
+ plist_from_bin(data.data(), data.size(), &plist);
+ else
+ plist_from_xml(data.data(), data.size(), &plist);
+ _assert(plist != NULL);
+ return plist;
+}
+
+static void plist_d(std::streambuf &buffer, const Functor<void (plist_t)> &code) {
+ std::stringbuf data;
+ copy(buffer, data);
+ auto node(plist(data.str()));
+ _scope({ plist_free(node); });
+ _assert(plist_get_node_type(node) == PLIST_DICT);
+ code(node);
+}
+
+static std::string plist_s(plist_t node) {
+ _assert(node != NULL);
+ _assert(plist_get_node_type(node) == PLIST_STRING);
+ char *data;
+ plist_get_string_val(node, &data);
+ _scope({ free(data); });
+ return data;
+}
+#endif
+
+enum Mode {
+ NoMode,
+ OptionalMode,
+ OmitMode,
+ NestedMode,
+ TopMode,
+};
+
+class Expression {
+ private:
+ regex_t regex_;
+
+ public:
+ Expression(const std::string &code) {
+ _assert_(regcomp(®ex_, code.c_str(), REG_EXTENDED | REG_NOSUB) == 0, "regcomp()");
+ }
+
+ ~Expression() {
+ regfree(®ex_);
+ }
+
+ bool operator ()(const std::string &data) const {
+ auto value(regexec(®ex_, data.c_str(), 0, NULL, 0));
+ if (value == REG_NOMATCH)
+ return false;
+ _assert_(value == 0, "regexec()");
+ return true;
+ }
+};
+
+struct Rule {
+ unsigned weight_;
+ Mode mode_;
+ std::string code_;
+
+ mutable std::auto_ptr<Expression> regex_;
+
+ Rule(unsigned weight, Mode mode, const std::string &code) :
+ weight_(weight),
+ mode_(mode),
+ code_(code)
+ {
+ }
+
+ Rule(const Rule &rhs) :
+ weight_(rhs.weight_),
+ mode_(rhs.mode_),
+ code_(rhs.code_)
+ {
+ }
+
+ void Compile() const {
+ regex_.reset(new Expression(code_));
+ }
+
+ bool operator ()(const std::string &data) const {
+ _assert(regex_.get() != NULL);
+ return (*regex_)(data);
+ }
+
+ bool operator <(const Rule &rhs) const {
+ if (weight_ > rhs.weight_)
+ return true;
+ if (weight_ < rhs.weight_)
+ return false;
+ return mode_ > rhs.mode_;
+ }
+};
+
+struct RuleCode {
+ bool operator ()(const Rule *lhs, const Rule *rhs) const {
+ return lhs->code_ < rhs->code_;
+ }
+};
+
+#ifndef LDID_NOPLIST
+void Sign(std::streambuf &buffer, std::vector<char> &hash, std::streambuf &save, const std::string &identifier, const std::string &entitlements, const std::string &key, const Slots &slots) {
+ // XXX: this is a miserable fail
+ std::stringbuf temp;
+ copy(buffer, temp);
+ auto data(temp.str());
+
+ HashProxy proxy(hash, save);
+ Sign(data.data(), data.size(), proxy, identifier, entitlements, key, slots);
+}
+
+std::string Bundle(const std::string &root, Folder &folder, const std::string &key, std::map<std::string, std::vector<char>> &remote, const std::string &entitlements) {
+ std::string executable;
+ std::string identifier;
+
+ static const std::string info("Info.plist");
+
+ _assert_(folder.Open(info, fun([&](std::streambuf &buffer, const void *flag) {
+ plist_d(buffer, fun([&](plist_t node) {
+ executable = plist_s(plist_dict_get_item(node, "CFBundleExecutable"));
+ identifier = plist_s(plist_dict_get_item(node, "CFBundleIdentifier"));
+ }));
+ })), "open(): Info.plist");
+
+ static const std::string directory("_CodeSignature/");
+ static const std::string signature(directory + "CodeResources");
+
+ std::map<std::string, std::multiset<Rule>> versions;
+
+ auto &rules1(versions[""]);
+ auto &rules2(versions["2"]);
+
+ folder.Open(signature, fun([&](std::streambuf &buffer, const void *) {
+ plist_d(buffer, fun([&](plist_t node) {
+ // XXX: maybe attempt to preserve existing rules
+ }));
+ }));
+
+ if (true) {
+ rules1.insert(Rule{1, NoMode, "^"});
+ rules1.insert(Rule{10000, OmitMode, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
+ rules1.insert(Rule{1000, OptionalMode, "^.*\\.lproj/"});
+ rules1.insert(Rule{1100, OmitMode, "^.*\\.lproj/locversion.plist$"});
+ rules1.insert(Rule{10000, OmitMode, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
+ rules1.insert(Rule{1, NoMode, "^version.plist$"});
+ }
+
+ if (true) {
+ rules2.insert(Rule{11, NoMode, ".*\\.dSYM($|/)"});
+ rules2.insert(Rule{20, NoMode, "^"});
+ rules2.insert(Rule{2000, OmitMode, "^(.*/)?\\.DS_Store$"});
+ rules2.insert(Rule{10000, OmitMode, "^(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/|())SC_Info/[^/]+\\.(sinf|supf|supp)$"});
+ rules2.insert(Rule{10, NestedMode, "^(Frameworks|SharedFrameworks|PlugIns|Plug-ins|XPCServices|Helpers|MacOS|Library/(Automator|Spotlight|LoginItems))/"});
+ rules2.insert(Rule{1, NoMode, "^.*"});
+ rules2.insert(Rule{1000, OptionalMode, "^.*\\.lproj/"});
+ rules2.insert(Rule{1100, OmitMode, "^.*\\.lproj/locversion.plist$"});
+ rules2.insert(Rule{20, OmitMode, "^Info\\.plist$"});
+ rules2.insert(Rule{20, OmitMode, "^PkgInfo$"});
+ rules2.insert(Rule{10000, OmitMode, "^Watch/[^/]+\\.app/(Frameworks/[^/]+\\.framework/|PlugIns/[^/]+\\.appex/|PlugIns/[^/]+\\.appex/Frameworks/[^/]+\\.framework/)SC_Info/[^/]+\\.(sinf|supf|supp)$"});
+ rules2.insert(Rule{10, NestedMode, "^[^/]+$"});
+ rules2.insert(Rule{20, NoMode, "^embedded\\.provisionprofile$"});
+ rules2.insert(Rule{20, NoMode, "^version\\.plist$"});
+ }
+
+ std::map<std::string, std::vector<char>> local;
+
+ static Expression nested("^PlugIns/[^/]*\\.appex/Info\\.plist$");
+ static Expression dylib("^[^/]*\\.dylib$");
+
+ folder.Find("", fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &code) {
+ if (!nested(name))
+ return;
+ auto bundle(root + Split(name).dir);
+ SubFolder subfolder(folder, bundle);
+ Bundle(bundle, subfolder, key, local, "");
+ }));
+
+ folder.Find("", fun([&](const std::string &name, const Functor<void (const Functor<void (std::streambuf &, std::streambuf &)> &)> &code) {
+ // BundleDiskRep::adjustResources -> builder.addExclusion
+ if (name == executable || Starts(name, directory) || Starts(name, "_MASReceipt/") || name == "CodeResources")
+ return;
+
+ auto &hash(local[name]);
+ if (!hash.empty())
+ return;
+
+ code(fun([&](std::streambuf &data, std::streambuf &save) {
+ if (dylib(name)) {
+ Slots slots;
+ Sign(data, hash, save, identifier, "", key, slots);
+ } else {
+ HashProxy proxy(hash, save);
+ copy(data, proxy);
+ }
+ }));
+
+ _assert(hash.size() == LDID_SHA1_DIGEST_LENGTH);
+ }));
+
+ auto plist(plist_new_dict());
+ _scope({ plist_free(plist); });
+
+ for (const auto &version : versions) {
+ auto files(plist_new_dict());
+ plist_dict_set_item(plist, ("files" + version.first).c_str(), files);
+
+ for (const auto &rule : version.second)
+ rule.Compile();
+
+ for (const auto &hash : local)
+ for (const auto &rule : version.second)
+ if (rule(hash.first)) {
+ if (rule.mode_ == NoMode)
+ plist_dict_set_item(files, hash.first.c_str(), plist_new_data(hash.second.data(), hash.second.size()));
+ else if (rule.mode_ == OptionalMode) {
+ auto entry(plist_new_dict());
+ plist_dict_set_item(entry, "hash", plist_new_data(hash.second.data(), hash.second.size()));
+ plist_dict_set_item(entry, "optional", plist_new_bool(true));
+ plist_dict_set_item(files, hash.first.c_str(), entry);
+ }
+
+ break;
+ }
+ }
+
+ for (const auto &version : versions) {
+ auto rules(plist_new_dict());
+ plist_dict_set_item(plist, ("rules" + version.first).c_str(), rules);
+
+ std::multiset<const Rule *, RuleCode> ordered;
+ for (const auto &rule : version.second)
+ ordered.insert(&rule);
+
+ for (const auto &rule : ordered)
+ if (rule->weight_ == 1 && rule->mode_ == NoMode)
+ plist_dict_set_item(rules, rule->code_.c_str(), plist_new_bool(true));
+ else {
+ auto entry(plist_new_dict());
+ plist_dict_set_item(rules, rule->code_.c_str(), entry);
+
+ switch (rule->mode_) {
+ case NoMode:
+ break;
+ case OmitMode:
+ plist_dict_set_item(entry, "omit", plist_new_bool(true));
+ break;
+ case OptionalMode:
+ plist_dict_set_item(entry, "optional", plist_new_bool(true));
+ break;
+ case NestedMode:
+ plist_dict_set_item(entry, "nested", plist_new_bool(true));
+ break;
+ case TopMode:
+ plist_dict_set_item(entry, "top", plist_new_bool(true));
+ break;
+ }
+
+ if (rule->weight_ >= 10000)
+ plist_dict_set_item(entry, "weight", plist_new_uint(rule->weight_));
+ else if (rule->weight_ != 1)
+ plist_dict_set_item(entry, "weight", plist_new_real(rule->weight_));
+ }
+ }
+
+ folder.Save(signature, NULL, fun([&](std::streambuf &save) {
+ HashProxy proxy(local[signature], save);
+ char *xml(NULL);
+ uint32_t size;
+ plist_to_xml(plist, &xml, &size);
+ _scope({ free(xml); });
+ put(proxy, xml, size);
+ }));
+
+ folder.Open(executable, fun([&](std::streambuf &buffer, const void *flag) {
+ folder.Save(executable, flag, fun([&](std::streambuf &save) {
+ Slots slots;
+ slots[1] = local.at(info);
+ slots[3] = local.at(signature);
+ Sign(buffer, local[executable], save, identifier, entitlements, key, slots);
+ }));
+ }));
+
+ for (const auto &hash : local)
+ remote[root + hash.first] = hash.second;
+
+ return executable;
+}
+#endif
+
+#endif
+}
+
+#ifndef LDID_NOTOOLS
+int main(int argc, char *argv[]) {
+#ifndef LDID_NOSMIME
+ OpenSSL_add_all_algorithms();
+#endif
+
+ union {
+ uint16_t word;
+ uint8_t byte[2];
+ } endian = {1};
+
+ little_ = endian.byte[0];
+
+ bool flag_r(false);
+ bool flag_e(false);
+
+#ifndef LDID_NOFLAGT
+ bool flag_T(false);
+#endif
+
+ bool flag_S(false);
+ bool flag_s(false);
+
+ bool flag_D(false);
+
+ bool flag_A(false);
+ bool flag_a(false);
+
+ bool flag_u(false);
+
+ uint32_t flag_CPUType(_not(uint32_t));
+ uint32_t flag_CPUSubtype(_not(uint32_t));
+
+ const char *flag_I(NULL);
+
+#ifndef LDID_NOFLAGT
+ bool timeh(false);
+ uint32_t timev(0);
+#endif
+
+ Map entitlements;
+ Map key;
+ ldid::Slots slots;
+
+ std::vector<std::string> files;
+
+ if (argc == 1) {
+ fprintf(stderr, "usage: %s -S[entitlements.xml] <binary>\n", argv[0]);
+ fprintf(stderr, " %s -e MobileSafari\n", argv[0]);
+ fprintf(stderr, " %s -S cat\n", argv[0]);
+ fprintf(stderr, " %s -Stfp.xml gdb\n", argv[0]);
+ exit(0);
+ }
+
+ for (int argi(1); argi != argc; ++argi)
+ if (argv[argi][0] != '-')
+ files.push_back(argv[argi]);
+ else switch (argv[argi][1]) {
+ case 'r':
+ _assert(!flag_s);
+ _assert(!flag_S);
+ flag_r = true;
+ break;
+
+ case 'e': flag_e = true; break;
+
+ case 'E': {
+ const char *slot = argv[argi] + 2;
+ const char *colon = strchr(slot, ':');
+ _assert(colon != NULL);
+ Map file(colon + 1, O_RDONLY, PROT_READ, MAP_PRIVATE);
+ char *arge;
+ unsigned number(strtoul(slot, &arge, 0));
+ _assert(arge == colon);
+ sha1(slots[number], file.data(), file.size());
+ } break;
+
+ case 'D': flag_D = true; break;
+
+ case 'a': flag_a = true; break;
+
+ case 'A':
+ _assert(!flag_A);
+ flag_A = true;
+ if (argv[argi][2] != '\0') {
+ const char *cpu = argv[argi] + 2;
+ const char *colon = strchr(cpu, ':');
+ _assert(colon != NULL);
+ char *arge;
+ flag_CPUType = strtoul(cpu, &arge, 0);
+ _assert(arge == colon);
+ flag_CPUSubtype = strtoul(colon + 1, &arge, 0);
+ _assert(arge == argv[argi] + strlen(argv[argi]));
+ }
+ break;
+
+ case 's':
+ _assert(!flag_r);
+ _assert(!flag_S);
+ flag_s = true;
+ break;
+
+ case 'S':
+ _assert(!flag_r);
+ _assert(!flag_s);
+ flag_S = true;
+ if (argv[argi][2] != '\0') {
+ const char *xml = argv[argi] + 2;
+ entitlements.open(xml, O_RDONLY, PROT_READ, MAP_PRIVATE);
+ }
+ break;
+
+ case 'K':
+ if (argv[argi][2] != '\0')
+ key.open(argv[argi] + 2, O_RDONLY, PROT_READ, MAP_PRIVATE);
+ break;
+
+#ifndef LDID_NOFLAGT
+ case 'T': {
+ flag_T = true;
+ if (argv[argi][2] == '-')
+ timeh = true;
+ else {
+ char *arge;
+ timev = strtoul(argv[argi] + 2, &arge, 0);
+ _assert(arge == argv[argi] + strlen(argv[argi]));
+ }
+ } break;
+#endif
+
+ case 'u': {
+ flag_u = true;
+ } break;
+
+ case 'I': {
+ flag_I = argv[argi] + 2;
+ } break;
+
+ default:
+ goto usage;
+ break;
+ }
+
+ _assert(flag_S || key.empty());
+ _assert(flag_S || flag_I == NULL);
+
+ if (files.empty()) usage: {
+ exit(0);
+ }
+
+ size_t filei(0), filee(0);
+ _foreach (file, files) try {
+ std::string path(file);
+
+ struct stat info;
+ _syscall(stat(path.c_str(), &info));
+
+ if (S_ISDIR(info.st_mode)) {
+#ifndef LDID_NOPLIST
+ _assert(!flag_r);
+ ldid::DiskFolder folder(path);
+ std::map<std::string, std::vector<char>> hashes;
+ path += "/" + Bundle("", folder, key, hashes, entitlements);
+#else
+ _assert(false);
+#endif
+ } else if (flag_S || flag_r) {
+ Map input(path, O_RDONLY, PROT_READ, MAP_PRIVATE);
+
+ std::filebuf output;
+ Split split(path);
+ auto temp(Temporary(output, split));
+
+ if (flag_r)
+ ldid::Unsign(input.data(), input.size(), output);
+ else {
+ std::string identifier(flag_I ?: split.base.c_str());
+ ldid::Sign(input.data(), input.size(), output, identifier, entitlements, key, slots);
+ }
+
+ Commit(path, temp);
+ }
+
+ bool modify(false);
+#ifndef LDID_NOFLAGT
+ if (flag_T)
+ modify = true;
+#endif
+ if (flag_s)
+ modify = true;
+
+ Map mapping(path, modify);
+ FatHeader fat_header(mapping.data(), mapping.size());