+ pad(output, allocation.limit_ - allocation.size_);
+ position += allocation.limit_ - allocation.size_;
+
+ size_t saved(save(mach_header, output, allocation.limit_, overlap, top));
+ if (allocation.alloc_ > saved)
+ pad(output, allocation.alloc_ - saved);
+ position += allocation.alloc_;
+ }
+}
+
+}
+
+typedef std::map<uint32_t, std::string> Blobs;
+
+static void insert(Blobs &blobs, uint32_t slot, const std::stringbuf &buffer) {
+ auto value(buffer.str());
+ std::swap(blobs[slot], value);
+}
+
+static void insert(Blobs &blobs, uint32_t slot, uint32_t magic, const std::stringbuf &buffer) {
+ auto value(buffer.str());
+ Blob blob;
+ blob.magic = Swap(magic);
+ blob.length = Swap(uint32_t(sizeof(blob) + value.size()));
+ value.insert(0, reinterpret_cast<char *>(&blob), sizeof(blob));
+ std::swap(blobs[slot], value);
+}
+
+static size_t put(std::streambuf &output, uint32_t magic, const Blobs &blobs) {
+ size_t total(0);
+ _foreach (blob, blobs)
+ total += blob.second.size();
+
+ struct SuperBlob super;
+ super.blob.magic = Swap(magic);
+ super.blob.length = Swap(uint32_t(sizeof(SuperBlob) + blobs.size() * sizeof(BlobIndex) + total));
+ super.count = Swap(uint32_t(blobs.size()));
+ put(output, &super, sizeof(super));
+
+ size_t offset(sizeof(SuperBlob) + sizeof(BlobIndex) * blobs.size());
+
+ _foreach (blob, blobs) {
+ BlobIndex index;
+ index.type = Swap(blob.first);
+ index.offset = Swap(uint32_t(offset));
+ put(output, &index, sizeof(index));
+ offset += blob.second.size();
+ }
+
+ _foreach (blob, blobs)
+ put(output, blob.second.data(), blob.second.size());
+
+ return offset;
+}
+
+#ifndef LDID_NOSMIME
+class Buffer {
+ private:
+ BIO *bio_;
+
+ public:
+ Buffer(BIO *bio) :
+ bio_(bio)
+ {
+ _assert(bio_ != NULL);
+ }
+
+ Buffer() :
+ bio_(BIO_new(BIO_s_mem()))
+ {
+ }
+
+ Buffer(const char *data, size_t size) :
+ Buffer(BIO_new_mem_buf(const_cast<char *>(data), size))
+ {
+ }
+
+ Buffer(const std::string &data) :
+ Buffer(data.data(), data.size())
+ {
+ }
+
+ Buffer(PKCS7 *pkcs) :
+ Buffer()
+ {
+ _assert(i2d_PKCS7_bio(bio_, pkcs) != 0);
+ }
+
+ ~Buffer() {
+ BIO_free_all(bio_);
+ }
+
+ operator BIO *() const {
+ return bio_;
+ }
+
+ explicit operator std::string() const {
+ char *data;
+ auto size(BIO_get_mem_data(bio_, &data));
+ return std::string(data, size);
+ }
+};
+
+class Stuff {
+ private:
+ PKCS12 *value_;
+ EVP_PKEY *key_;
+ X509 *cert_;
+ STACK_OF(X509) *ca_;
+
+ public:
+ Stuff(BIO *bio) :
+ value_(d2i_PKCS12_bio(bio, NULL)),
+ ca_(NULL)
+ {
+ _assert(value_ != NULL);
+ _assert(PKCS12_parse(value_, "", &key_, &cert_, &ca_) != 0);
+ _assert(key_ != NULL);
+ _assert(cert_ != NULL);
+ }
+
+ Stuff(const std::string &data) :
+ Stuff(Buffer(data))
+ {
+ }
+
+ ~Stuff() {
+ sk_X509_pop_free(ca_, X509_free);
+ X509_free(cert_);
+ EVP_PKEY_free(key_);
+ PKCS12_free(value_);
+ }
+
+ operator PKCS12 *() const {
+ return value_;
+ }
+
+ operator EVP_PKEY *() const {
+ return key_;
+ }
+
+ operator X509 *() const {
+ return cert_;
+ }
+
+ operator STACK_OF(X509) *() const {
+ return ca_;
+ }
+};
+
+class Signature {
+ private:
+ PKCS7 *value_;
+
+ public:
+ Signature(const Stuff &stuff, const Buffer &data) :
+ value_(PKCS7_sign(stuff, stuff, stuff, data, PKCS7_BINARY | PKCS7_DETACHED))
+ {
+ _assert(value_ != NULL);
+ }
+
+ ~Signature() {
+ PKCS7_free(value_);
+ }
+
+ operator PKCS7 *() const {
+ return value_;
+ }
+};
+#endif
+
+class NullBuffer :
+ public std::streambuf
+{
+ public:
+ virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
+ return size;
+ }
+
+ virtual int_type overflow(int_type next) {
+ return next;
+ }
+};
+
+class HashBuffer :
+ public std::streambuf
+{
+ private:
+ std::vector<char> &hash_;
+ LDID_SHA1_CTX context_;
+
+ public:
+ HashBuffer(std::vector<char> &hash) :
+ hash_(hash)
+ {
+ LDID_SHA1_Init(&context_);
+ }
+
+ ~HashBuffer() {
+ hash_.resize(LDID_SHA1_DIGEST_LENGTH);
+ LDID_SHA1_Final(reinterpret_cast<uint8_t *>(hash_.data()), &context_);
+ }
+
+ virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
+ LDID_SHA1_Update(&context_, data, size);
+ return size;
+ }
+
+ virtual int_type overflow(int_type next) {
+ if (next == traits_type::eof())
+ return sync();
+ char value(next);
+ xsputn(&value, 1);
+ return next;
+ }
+};
+
+class HashProxy :
+ public HashBuffer
+{
+ private:
+ std::streambuf &buffer_;
+
+ public:
+ HashProxy(std::vector<char> &hash, std::streambuf &buffer) :
+ HashBuffer(hash),
+ buffer_(buffer)
+ {
+ }
+
+ virtual std::streamsize xsputn(const char_type *data, std::streamsize size) {
+ _assert(HashBuffer::xsputn(data, size) == size);
+ return buffer_.sputn(data, size);
+ }
+};
+
+#ifndef LDID_NOTOOLS
+static bool Starts(const std::string &lhs, const std::string &rhs) {
+ return lhs.size() >= rhs.size() && lhs.compare(0, rhs.size(), rhs) == 0;
+}
+
+class Split {
+ public:
+ std::string dir;
+ std::string base;
+
+ Split(const std::string &path) {
+ size_t slash(path.rfind('/'));
+ if (slash == std::string::npos)
+ base = path;
+ else {
+ dir = path.substr(0, slash + 1);
+ base = path.substr(slash + 1);
+ }
+ }
+};
+
+static void mkdir_p(const std::string &path) {
+ if (path.empty())
+ return;
+#ifdef __WIN32__
+ if (_syscall(mkdir(path.c_str()), EEXIST) == -EEXIST)
+ return;
+#else
+ if (_syscall(mkdir(path.c_str(), 0755), EEXIST) == -EEXIST)
+ return;
+#endif
+ auto slash(path.rfind('/', path.size() - 1));
+ if (slash == std::string::npos)
+ return;
+ mkdir_p(path.substr(0, slash));
+}
+
+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;