Chris@47: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors Chris@47: // Licensed under the MIT License: Chris@47: // Chris@47: // Permission is hereby granted, free of charge, to any person obtaining a copy Chris@47: // of this software and associated documentation files (the "Software"), to deal Chris@47: // in the Software without restriction, including without limitation the rights Chris@47: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Chris@47: // copies of the Software, and to permit persons to whom the Software is Chris@47: // furnished to do so, subject to the following conditions: Chris@47: // Chris@47: // The above copyright notice and this permission notice shall be included in Chris@47: // all copies or substantial portions of the Software. Chris@47: // Chris@47: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR Chris@47: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, Chris@47: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE Chris@47: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER Chris@47: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, Chris@47: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN Chris@47: // THE SOFTWARE. Chris@47: Chris@47: #ifndef CAPNP_ARENA_H_ Chris@47: #define CAPNP_ARENA_H_ Chris@47: Chris@47: #if defined(__GNUC__) && !defined(CAPNP_HEADER_WARNINGS) Chris@47: #pragma GCC system_header Chris@47: #endif Chris@47: Chris@47: #ifndef CAPNP_PRIVATE Chris@47: #error "This header is only meant to be included by Cap'n Proto's own source code." Chris@47: #endif Chris@47: Chris@47: #include Chris@47: #include Chris@47: #include Chris@47: #include Chris@47: #include "common.h" Chris@47: #include "message.h" Chris@47: #include "layout.h" Chris@47: #include Chris@47: Chris@47: #if !CAPNP_LITE Chris@47: #include "capability.h" Chris@47: #endif // !CAPNP_LITE Chris@47: Chris@47: namespace capnp { Chris@47: Chris@47: #if !CAPNP_LITE Chris@47: class ClientHook; Chris@47: #endif // !CAPNP_LITE Chris@47: Chris@47: namespace _ { // private Chris@47: Chris@47: class SegmentReader; Chris@47: class SegmentBuilder; Chris@47: class Arena; Chris@47: class BuilderArena; Chris@47: class ReadLimiter; Chris@47: Chris@47: class Segment; Chris@47: typedef kj::Id SegmentId; Chris@47: Chris@47: class ReadLimiter { Chris@47: // Used to keep track of how much data has been processed from a message, and cut off further Chris@47: // processing if and when a particular limit is reached. This is primarily intended to guard Chris@47: // against maliciously-crafted messages which contain cycles or overlapping structures. Cycles Chris@47: // and overlapping are not permitted by the Cap'n Proto format because in many cases they could Chris@47: // be used to craft a deceptively small message which could consume excessive server resources to Chris@47: // process, perhaps even sending it into an infinite loop. Actually detecting overlaps would be Chris@47: // time-consuming, so instead we just keep track of how many words worth of data structures the Chris@47: // receiver has actually dereferenced and error out if this gets too high. Chris@47: // Chris@47: // This counting takes place as you call getters (for non-primitive values) on the message Chris@47: // readers. If you call the same getter twice, the data it returns may be double-counted. This Chris@47: // should not be a big deal in most cases -- just set the read limit high enough that it will Chris@47: // only trigger in unreasonable cases. Chris@47: // Chris@47: // This class is "safe" to use from multiple threads for its intended use case. Threads may Chris@47: // overwrite each others' changes to the counter, but this is OK because it only means that the Chris@47: // limit is enforced a bit less strictly -- it will still kick in eventually. Chris@47: Chris@47: public: Chris@47: inline explicit ReadLimiter(); // No limit. Chris@47: inline explicit ReadLimiter(WordCount64 limit); // Limit to the given number of words. Chris@47: Chris@47: inline void reset(WordCount64 limit); Chris@47: Chris@47: KJ_ALWAYS_INLINE(bool canRead(WordCount amount, Arena* arena)); Chris@47: Chris@47: void unread(WordCount64 amount); Chris@47: // Adds back some words to the limit. Useful when the caller knows they are double-reading Chris@47: // some data. Chris@47: Chris@47: private: Chris@47: volatile uint64_t limit; Chris@47: // Current limit, decremented each time catRead() is called. Volatile because multiple threads Chris@47: // could be trying to modify it at once. (This is not real thread-safety, but good enough for Chris@47: // the purpose of this class. See class comment.) Chris@47: Chris@47: KJ_DISALLOW_COPY(ReadLimiter); Chris@47: }; Chris@47: Chris@47: #if !CAPNP_LITE Chris@47: class BrokenCapFactory { Chris@47: // Callback for constructing broken caps. We use this so that we can avoid arena.c++ having a Chris@47: // link-time dependency on capability code that lives in libcapnp-rpc. Chris@47: Chris@47: public: Chris@47: virtual kj::Own newBrokenCap(kj::StringPtr description) = 0; Chris@47: virtual kj::Own newNullCap() = 0; Chris@47: }; Chris@47: #endif // !CAPNP_LITE Chris@47: Chris@47: class SegmentReader { Chris@47: public: Chris@47: inline SegmentReader(Arena* arena, SegmentId id, kj::ArrayPtr ptr, Chris@47: ReadLimiter* readLimiter); Chris@47: Chris@47: KJ_ALWAYS_INLINE(bool containsInterval(const void* from, const void* to)); Chris@47: Chris@47: KJ_ALWAYS_INLINE(bool amplifiedRead(WordCount virtualAmount)); Chris@47: // Indicates that the reader should pretend that `virtualAmount` additional data was read even Chris@47: // though no actual pointer was traversed. This is used e.g. when reading a struct list pointer Chris@47: // where the element sizes are zero -- the sender could set the list size arbitrarily high and Chris@47: // cause the receiver to iterate over this list even though the message itself is small, so we Chris@47: // need to defend against DoS attacks based on this. Chris@47: Chris@47: inline Arena* getArena(); Chris@47: inline SegmentId getSegmentId(); Chris@47: Chris@47: inline const word* getStartPtr(); Chris@47: inline WordCount getOffsetTo(const word* ptr); Chris@47: inline WordCount getSize(); Chris@47: Chris@47: inline kj::ArrayPtr getArray(); Chris@47: Chris@47: inline void unread(WordCount64 amount); Chris@47: // Add back some words to the ReadLimiter. Chris@47: Chris@47: private: Chris@47: Arena* arena; Chris@47: SegmentId id; Chris@47: kj::ArrayPtr ptr; Chris@47: ReadLimiter* readLimiter; Chris@47: Chris@47: KJ_DISALLOW_COPY(SegmentReader); Chris@47: Chris@47: friend class SegmentBuilder; Chris@47: }; Chris@47: Chris@47: class SegmentBuilder: public SegmentReader { Chris@47: public: Chris@47: inline SegmentBuilder(BuilderArena* arena, SegmentId id, kj::ArrayPtr ptr, Chris@47: ReadLimiter* readLimiter, size_t wordsUsed = 0); Chris@47: inline SegmentBuilder(BuilderArena* arena, SegmentId id, kj::ArrayPtr ptr, Chris@47: ReadLimiter* readLimiter); Chris@47: inline SegmentBuilder(BuilderArena* arena, SegmentId id, decltype(nullptr), Chris@47: ReadLimiter* readLimiter); Chris@47: Chris@47: KJ_ALWAYS_INLINE(word* allocate(WordCount amount)); Chris@47: Chris@47: KJ_ALWAYS_INLINE(void checkWritable()); Chris@47: // Throw an exception if the segment is read-only (meaning it is a reference to external data). Chris@47: Chris@47: KJ_ALWAYS_INLINE(word* getPtrUnchecked(WordCount offset)); Chris@47: // Get a writable pointer into the segment. Throws an exception if the segment is read-only (i.e. Chris@47: // a reference to external immutable data). Chris@47: Chris@47: inline BuilderArena* getArena(); Chris@47: Chris@47: inline kj::ArrayPtr currentlyAllocated(); Chris@47: Chris@47: inline void reset(); Chris@47: Chris@47: inline bool isWritable() { return !readOnly; } Chris@47: Chris@47: inline void tryTruncate(word* from, word* to); Chris@47: // If `from` points just past the current end of the segment, then move the end back to `to`. Chris@47: // Otherwise, do nothing. Chris@47: Chris@47: inline bool tryExtend(word* from, word* to); Chris@47: // If `from` points just past the current end of the segment, and `to` is within the segment Chris@47: // boundaries, then move the end up to `to` and return true. Otherwise, do nothing and return Chris@47: // false. Chris@47: Chris@47: private: Chris@47: word* pos; Chris@47: // Pointer to a pointer to the current end point of the segment, i.e. the location where the Chris@47: // next object should be allocated. Chris@47: Chris@47: bool readOnly; Chris@47: Chris@47: void throwNotWritable(); Chris@47: Chris@47: KJ_DISALLOW_COPY(SegmentBuilder); Chris@47: }; Chris@47: Chris@47: class Arena { Chris@47: public: Chris@47: virtual ~Arena() noexcept(false); Chris@47: Chris@47: virtual SegmentReader* tryGetSegment(SegmentId id) = 0; Chris@47: // Gets the segment with the given ID, or return nullptr if no such segment exists. Chris@47: Chris@47: virtual void reportReadLimitReached() = 0; Chris@47: // Called to report that the read limit has been reached. See ReadLimiter, below. This invokes Chris@47: // the VALIDATE_INPUT() macro which may throw an exception; if it returns normally, the caller Chris@47: // will need to continue with default values. Chris@47: }; Chris@47: Chris@47: class ReaderArena final: public Arena { Chris@47: public: Chris@47: ReaderArena(MessageReader* message); Chris@47: ~ReaderArena() noexcept(false); Chris@47: KJ_DISALLOW_COPY(ReaderArena); Chris@47: Chris@47: // implements Arena ------------------------------------------------ Chris@47: SegmentReader* tryGetSegment(SegmentId id) override; Chris@47: void reportReadLimitReached() override; Chris@47: Chris@47: private: Chris@47: MessageReader* message; Chris@47: ReadLimiter readLimiter; Chris@47: Chris@47: // Optimize for single-segment messages so that small messages are handled quickly. Chris@47: SegmentReader segment0; Chris@47: Chris@47: typedef std::unordered_map> SegmentMap; Chris@47: kj::MutexGuarded>> moreSegments; Chris@47: // We need to mutex-guard the segment map because we lazily initialize segments when they are Chris@47: // first requested, but a Reader is allowed to be used concurrently in multiple threads. Luckily Chris@47: // this only applies to large messages. Chris@47: // Chris@47: // TODO(perf): Thread-local thing instead? Some kind of lockless map? Or do sharing of data Chris@47: // in a different way, where you have to construct a new MessageReader in each thread (but Chris@47: // possibly backed by the same data)? Chris@47: }; Chris@47: Chris@47: class BuilderArena final: public Arena { Chris@47: // A BuilderArena that does not allow the injection of capabilities. Chris@47: Chris@47: public: Chris@47: explicit BuilderArena(MessageBuilder* message); Chris@47: BuilderArena(MessageBuilder* message, kj::ArrayPtr segments); Chris@47: ~BuilderArena() noexcept(false); Chris@47: KJ_DISALLOW_COPY(BuilderArena); Chris@47: Chris@47: inline SegmentBuilder* getRootSegment() { return &segment0; } Chris@47: Chris@47: kj::ArrayPtr> getSegmentsForOutput(); Chris@47: // Get an array of all the segments, suitable for writing out. This only returns the allocated Chris@47: // portion of each segment, whereas tryGetSegment() returns something that includes Chris@47: // not-yet-allocated space. Chris@47: Chris@47: inline CapTableBuilder* getLocalCapTable() { Chris@47: // Return a CapTableBuilder that merely implements local loopback. That is, you can set Chris@47: // capabilities, then read the same capabilities back, but there is no intent ever to transmit Chris@47: // these capabilities. A MessageBuilder that isn't imbued with some other CapTable uses this Chris@47: // by default. Chris@47: // Chris@47: // TODO(cleanup): It's sort of a hack that this exists. In theory, perhaps, unimbued Chris@47: // MessageBuilders should throw exceptions on any attempt to access capability fields, like Chris@47: // unimbued MessageReaders do. However, lots of code exists which uses MallocMessageBuilder Chris@47: // as a temporary holder for data to be copied in and out (without being serialized), and it Chris@47: // is expected that such data can include capabilities, which is admittedly reasonable. Chris@47: // Therefore, all MessageBuilders must have a cap table by default. Arguably we should Chris@47: // deprecate this usage and instead define a new helper type for this exact purpose. Chris@47: Chris@47: return &localCapTable; Chris@47: } Chris@47: Chris@47: SegmentBuilder* getSegment(SegmentId id); Chris@47: // Get the segment with the given id. Crashes or throws an exception if no such segment exists. Chris@47: Chris@47: struct AllocateResult { Chris@47: SegmentBuilder* segment; Chris@47: word* words; Chris@47: }; Chris@47: Chris@47: AllocateResult allocate(WordCount amount); Chris@47: // Find a segment with at least the given amount of space available and allocate the space. Chris@47: // Note that allocating directly from a particular segment is much faster, but allocating from Chris@47: // the arena is guaranteed to succeed. Therefore callers should try to allocate from a specific Chris@47: // segment first if there is one, then fall back to the arena. Chris@47: Chris@47: SegmentBuilder* addExternalSegment(kj::ArrayPtr content); Chris@47: // Add a new segment to the arena which points to some existing memory region. The segment is Chris@47: // assumed to be completley full; the arena will never allocate from it. In fact, the segment Chris@47: // is considered read-only. Any attempt to get a Builder pointing into this segment will throw Chris@47: // an exception. Readers are allowed, however. Chris@47: // Chris@47: // This can be used to inject some external data into a message without a copy, e.g. embedding a Chris@47: // large mmap'd file into a message as `Data` without forcing that data to actually be read in Chris@47: // from disk (until the message itself is written out). `Orphanage` provides the public API for Chris@47: // this feature. Chris@47: Chris@47: // implements Arena ------------------------------------------------ Chris@47: SegmentReader* tryGetSegment(SegmentId id) override; Chris@47: void reportReadLimitReached() override; Chris@47: Chris@47: private: Chris@47: MessageBuilder* message; Chris@47: ReadLimiter dummyLimiter; Chris@47: Chris@47: class LocalCapTable: public CapTableBuilder { Chris@47: #if !CAPNP_LITE Chris@47: public: Chris@47: kj::Maybe> extractCap(uint index) override; Chris@47: uint injectCap(kj::Own&& cap) override; Chris@47: void dropCap(uint index) override; Chris@47: Chris@47: private: Chris@47: kj::Vector>> capTable; Chris@47: #endif // ! CAPNP_LITE Chris@47: }; Chris@47: Chris@47: LocalCapTable localCapTable; Chris@47: Chris@47: SegmentBuilder segment0; Chris@47: kj::ArrayPtr segment0ForOutput; Chris@47: Chris@47: struct MultiSegmentState { Chris@47: kj::Vector> builders; Chris@47: kj::Vector> forOutput; Chris@47: }; Chris@47: kj::Maybe> moreSegments; Chris@47: Chris@47: SegmentBuilder* segmentWithSpace = nullptr; Chris@47: // When allocating, look for space in this segment first before resorting to allocating a new Chris@47: // segment. This is not necessarily the last segment because addExternalSegment() may add a Chris@47: // segment that is already-full, in which case we don't update this pointer. Chris@47: Chris@47: template // Can be `word` or `const word`. Chris@47: SegmentBuilder* addSegmentInternal(kj::ArrayPtr content); Chris@47: }; Chris@47: Chris@47: // ======================================================================================= Chris@47: Chris@47: inline ReadLimiter::ReadLimiter() Chris@47: : limit(kj::maxValue) {} Chris@47: Chris@47: inline ReadLimiter::ReadLimiter(WordCount64 limit): limit(limit / WORDS) {} Chris@47: Chris@47: inline void ReadLimiter::reset(WordCount64 limit) { this->limit = limit / WORDS; } Chris@47: Chris@47: inline bool ReadLimiter::canRead(WordCount amount, Arena* arena) { Chris@47: // Be careful not to store an underflowed value into `limit`, even if multiple threads are Chris@47: // decrementing it. Chris@47: uint64_t current = limit; Chris@47: if (KJ_UNLIKELY(amount / WORDS > current)) { Chris@47: arena->reportReadLimitReached(); Chris@47: return false; Chris@47: } else { Chris@47: limit = current - amount / WORDS; Chris@47: return true; Chris@47: } Chris@47: } Chris@47: Chris@47: // ------------------------------------------------------------------- Chris@47: Chris@47: inline SegmentReader::SegmentReader(Arena* arena, SegmentId id, kj::ArrayPtr ptr, Chris@47: ReadLimiter* readLimiter) Chris@47: : arena(arena), id(id), ptr(ptr), readLimiter(readLimiter) {} Chris@47: Chris@47: inline bool SegmentReader::containsInterval(const void* from, const void* to) { Chris@47: return from >= this->ptr.begin() && to <= this->ptr.end() && from <= to && Chris@47: readLimiter->canRead( Chris@47: intervalLength(reinterpret_cast(from), Chris@47: reinterpret_cast(to)) / BYTES_PER_WORD, Chris@47: arena); Chris@47: } Chris@47: Chris@47: inline bool SegmentReader::amplifiedRead(WordCount virtualAmount) { Chris@47: return readLimiter->canRead(virtualAmount, arena); Chris@47: } Chris@47: Chris@47: inline Arena* SegmentReader::getArena() { return arena; } Chris@47: inline SegmentId SegmentReader::getSegmentId() { return id; } Chris@47: inline const word* SegmentReader::getStartPtr() { return ptr.begin(); } Chris@47: inline WordCount SegmentReader::getOffsetTo(const word* ptr) { Chris@47: return intervalLength(this->ptr.begin(), ptr); Chris@47: } Chris@47: inline WordCount SegmentReader::getSize() { return ptr.size() * WORDS; } Chris@47: inline kj::ArrayPtr SegmentReader::getArray() { return ptr; } Chris@47: inline void SegmentReader::unread(WordCount64 amount) { readLimiter->unread(amount); } Chris@47: Chris@47: // ------------------------------------------------------------------- Chris@47: Chris@47: inline SegmentBuilder::SegmentBuilder( Chris@47: BuilderArena* arena, SegmentId id, kj::ArrayPtr ptr, ReadLimiter* readLimiter, Chris@47: size_t wordsUsed) Chris@47: : SegmentReader(arena, id, ptr, readLimiter), pos(ptr.begin() + wordsUsed), readOnly(false) {} Chris@47: inline SegmentBuilder::SegmentBuilder( Chris@47: BuilderArena* arena, SegmentId id, kj::ArrayPtr ptr, ReadLimiter* readLimiter) Chris@47: : SegmentReader(arena, id, ptr, readLimiter), Chris@47: // const_cast is safe here because the member won't ever be dereferenced because it appears Chris@47: // to point to the end of the segment anyway. Chris@47: pos(const_cast(ptr.end())), Chris@47: readOnly(true) {} Chris@47: inline SegmentBuilder::SegmentBuilder(BuilderArena* arena, SegmentId id, decltype(nullptr), Chris@47: ReadLimiter* readLimiter) Chris@47: : SegmentReader(arena, id, nullptr, readLimiter), pos(nullptr), readOnly(false) {} Chris@47: Chris@47: inline word* SegmentBuilder::allocate(WordCount amount) { Chris@47: if (intervalLength(pos, ptr.end()) < amount) { Chris@47: // Not enough space in the segment for this allocation. Chris@47: return nullptr; Chris@47: } else { Chris@47: // Success. Chris@47: word* result = pos; Chris@47: pos = pos + amount; Chris@47: return result; Chris@47: } Chris@47: } Chris@47: Chris@47: inline void SegmentBuilder::checkWritable() { Chris@47: if (KJ_UNLIKELY(readOnly)) throwNotWritable(); Chris@47: } Chris@47: Chris@47: inline word* SegmentBuilder::getPtrUnchecked(WordCount offset) { Chris@47: return const_cast(ptr.begin() + offset); Chris@47: } Chris@47: Chris@47: inline BuilderArena* SegmentBuilder::getArena() { Chris@47: // Down-cast safe because SegmentBuilder's constructor always initializes its SegmentReader base Chris@47: // class with an Arena pointer that actually points to a BuilderArena. Chris@47: return static_cast(arena); Chris@47: } Chris@47: Chris@47: inline kj::ArrayPtr SegmentBuilder::currentlyAllocated() { Chris@47: return kj::arrayPtr(ptr.begin(), pos - ptr.begin()); Chris@47: } Chris@47: Chris@47: inline void SegmentBuilder::reset() { Chris@47: word* start = getPtrUnchecked(0 * WORDS); Chris@47: memset(start, 0, (pos - start) * sizeof(word)); Chris@47: pos = start; Chris@47: } Chris@47: Chris@47: inline void SegmentBuilder::tryTruncate(word* from, word* to) { Chris@47: if (pos == from) pos = to; Chris@47: } Chris@47: Chris@47: inline bool SegmentBuilder::tryExtend(word* from, word* to) { Chris@47: // Careful about overflow. Chris@47: if (pos == from && to <= ptr.end() && to >= from) { Chris@47: pos = to; Chris@47: return true; Chris@47: } else { Chris@47: return false; Chris@47: } Chris@47: } Chris@47: Chris@47: } // namespace _ (private) Chris@47: } // namespace capnp Chris@47: Chris@47: #endif // CAPNP_ARENA_H_