+
+ operator std::string() const {
+ return std::string(static_cast<char *>(data_), size_);
+ }
+};
+
+namespace ldid {
+
+static void Allocate(const void *idata, size_t isize, std::streambuf &output, const Functor<size_t (size_t)> &allocate, const Functor<size_t (std::streambuf &output, size_t, const std::string &, const char *)> &save) {
+ FatHeader source(const_cast<void *>(idata), isize);
+
+ size_t offset(0);
+ if (source.IsFat())
+ offset += sizeof(fat_header) + sizeof(fat_arch) * source.Swap(source->nfat_arch);
+
+ std::vector<CodesignAllocation> allocations;
+ _foreach (mach_header, source.GetMachHeaders()) {
+ struct linkedit_data_command *signature(NULL);
+ struct symtab_command *symtab(NULL);
+
+ _foreach (load_command, mach_header.GetLoadCommands()) {
+ uint32_t cmd(mach_header.Swap(load_command->cmd));
+ if (false);
+ else if (cmd == LC_CODE_SIGNATURE)
+ signature = reinterpret_cast<struct linkedit_data_command *>(load_command);
+ else if (cmd == LC_SYMTAB)
+ symtab = reinterpret_cast<struct symtab_command *>(load_command);
+ }
+
+ size_t size;
+ if (signature == NULL)
+ size = mach_header.GetSize();
+ else {
+ size = mach_header.Swap(signature->dataoff);
+ _assert(size <= mach_header.GetSize());
+ }
+
+ if (symtab != NULL) {
+ auto end(mach_header.Swap(symtab->stroff) + mach_header.Swap(symtab->strsize));
+ _assert(end <= size);
+ _assert(end >= size - 0x10);
+ size = end;
+ }
+
+ size_t alloc(allocate(size));
+
+ auto *fat_arch(mach_header.GetFatArch());
+ uint32_t align(fat_arch == NULL ? 0 : source.Swap(fat_arch->align));
+ offset = Align(offset, 1 << align);
+
+ uint32_t limit(size);
+ if (alloc != 0)
+ limit = Align(limit, 0x10);
+
+ allocations.push_back(CodesignAllocation(mach_header, offset, size, limit, alloc, align));
+ offset += size + alloc;
+ offset = Align(offset, 0x10);
+ }
+
+ size_t position(0);
+
+ if (source.IsFat()) {
+ fat_header fat_header;
+ fat_header.magic = Swap(FAT_MAGIC);
+ fat_header.nfat_arch = Swap(uint32_t(allocations.size()));
+ put(output, &fat_header, sizeof(fat_header));
+ position += sizeof(fat_header);
+
+ _foreach (allocation, allocations) {
+ auto &mach_header(allocation.mach_header_);
+
+ fat_arch fat_arch;
+ fat_arch.cputype = Swap(mach_header->cputype);
+ fat_arch.cpusubtype = Swap(mach_header->cpusubtype);
+ fat_arch.offset = Swap(allocation.offset_);
+ fat_arch.size = Swap(allocation.limit_ + allocation.alloc_);
+ fat_arch.align = Swap(allocation.align_);
+ put(output, &fat_arch, sizeof(fat_arch));
+ position += sizeof(fat_arch);
+ }
+ }
+
+ _foreach (allocation, allocations) {
+ auto &mach_header(allocation.mach_header_);
+
+ pad(output, allocation.offset_ - position);
+ position = allocation.offset_;
+
+ std::vector<std::string> commands;
+
+ _foreach (load_command, mach_header.GetLoadCommands()) {
+ std::string copy(reinterpret_cast<const char *>(load_command), load_command->cmdsize);
+
+ switch (mach_header.Swap(load_command->cmd)) {
+ case LC_CODE_SIGNATURE:
+ continue;
+ break;
+
+ case LC_SEGMENT: {
+ auto segment_command(reinterpret_cast<struct segment_command *>(©[0]));
+ if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
+ break;
+ size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
+ segment_command->filesize = size;
+ segment_command->vmsize = Align(size, PageSize_);
+ } break;
+
+ case LC_SEGMENT_64: {
+ auto segment_command(reinterpret_cast<struct segment_command_64 *>(©[0]));
+ if (strncmp(segment_command->segname, "__LINKEDIT", 16) != 0)
+ break;
+ size_t size(mach_header.Swap(allocation.limit_ + allocation.alloc_ - mach_header.Swap(segment_command->fileoff)));
+ segment_command->filesize = size;
+ segment_command->vmsize = Align(size, PageSize_);
+ } break;
+ }
+
+ 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(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);
+ }
+};
+
+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()));
+}
+
+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) {
+ Allocate(idata, isize, output, fun([&](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 (!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);
+
+ uint32_t normal((size + PageSize_ - 1) / PageSize_);
+ alloc = Align(alloc + (special + normal) * LDID_SHA1_DIGEST_LENGTH, 16);
+ return alloc;
+ }), fun([&](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;
+
+ uint32_t special(0);
+ _foreach (blob, blobs)
+ special = std::max(special, blob.first);
+ _foreach (slot, slots)
+ special = std::max(special, slot.first);
+ uint32_t normal((limit + PageSize_ - 1) / PageSize_);
+
+ CodeDirectory directory;
+ directory.version = Swap(uint32_t(0x00020001));
+ directory.flags = Swap(uint32_t(0));
+ directory.hashOffset = Swap(uint32_t(sizeof(Blob) + sizeof(CodeDirectory) + identifier.size() + 1 + LDID_SHA1_DIGEST_LENGTH * special));
+ directory.identOffset = Swap(uint32_t(sizeof(Blob) + sizeof(CodeDirectory)));
+ 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));
+ put(data, &directory, sizeof(directory));
+
+ put(data, identifier.c_str(), identifier.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, slots) {
+ _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);
+ }));
+}
+
+static void Unsign(void *idata, size_t isize, std::streambuf &output) {
+ Allocate(idata, isize, output, fun([](size_t size) -> size_t {
+ return 0;
+ }), fun([](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) {
+ NullBuffer save;
+ code(data, save);
+ })), "open(): %s", access.c_str());
+ }));
+ }
+}
+
+void DiskFolder::Save(const std::string &path, 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 &)> &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);
+ 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);
+}
+
+SubFolder::SubFolder(Folder &parent, const std::string &path) :
+ parent_(parent),
+ path_(path)
+{
+}
+
+void SubFolder::Save(const std::string &path, const Functor<void (std::streambuf &)> &code) {
+ return parent_.Save(path_ + path, code);
+}
+
+bool SubFolder::Open(const std::string &path, const Functor<void (std::streambuf &)> &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);
+}
+
+UnionFolder::UnionFolder(Folder &parent) :
+ parent_(parent)
+{
+}
+
+void UnionFolder::Save(const std::string &path, const Functor<void (std::streambuf &)> &code) {
+ return parent_.Save(path, code);
+}
+
+bool UnionFolder::Open(const std::string &path, const Functor<void (std::streambuf &)> &code) {
+ auto file(files_.find(path));
+ if (file == files_.end())
+ return parent_.Open(path, code);
+
+ auto &data(file->second);
+ data.pubseekpos(0, std::ios::in);
+ code(data);
+ 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 (files_.find(name) == files_.end())
+ code(name, save);
+ }));
+
+ for (auto &file : files_)
+ code(file.first, fun([&](const Functor<void (std::streambuf &, std::streambuf &)> &code) {
+ parent_.Save(file.first, fun([&](std::streambuf &save) {
+ file.second.pubseekpos(0, std::ios::in);
+ code(file.second, save);
+ }));
+ }));
+}
+
+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_;
+ }