+ commands.push_back(copy);
+ }
+
+ if (allocation.alloc_ != 0) {
+ linkedit_data_command signature;
+ signature.cmd = mach_header.Swap(LC_CODE_SIGNATURE);
+ signature.cmdsize = mach_header.Swap(uint32_t(sizeof(signature)));
+ signature.dataoff = mach_header.Swap(allocation.limit_);
+ signature.datasize = mach_header.Swap(allocation.alloc_);
+ commands.push_back(std::string(reinterpret_cast<const char *>(&signature), sizeof(signature)));
+ }
+
+ size_t begin(position);
+
+ uint32_t after(0);
+ _foreach(command, commands)
+ after += command.size();
+
+ std::stringbuf altern;
+
+ struct mach_header header(*mach_header);
+ header.ncmds = mach_header.Swap(uint32_t(commands.size()));
+ header.sizeofcmds = mach_header.Swap(after);
+ put(output, &header, sizeof(header));
+ put(altern, &header, sizeof(header));
+ position += sizeof(header);
+
+ if (mach_header.Bits64()) {
+ auto pad(mach_header.Swap(uint32_t(0)));
+ put(output, &pad, sizeof(pad));
+ put(altern, &pad, sizeof(pad));
+ position += sizeof(pad);
+ }
+
+ _foreach(command, commands) {
+ put(output, command.data(), command.size());
+ put(altern, command.data(), command.size());
+ position += command.size();
+ }
+
+ uint32_t before(mach_header.Swap(mach_header->sizeofcmds));
+ if (before > after) {
+ pad(output, before - after);
+ pad(altern, before - after);
+ position += before - after;
+ }
+
+ auto top(reinterpret_cast<char *>(mach_header.GetBase()));
+
+ std::string overlap(altern.str());
+ overlap.append(top + overlap.size(), Align(overlap.size(), 0x1000) - overlap.size());
+
+ put(output, top + (position - begin), allocation.size_ - (position - begin));
+ position = begin + allocation.size_;
+
+ 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);
+ }));
+ }));
+ }));
+}