aboutsummaryrefslogtreecommitdiff
path: root/src/serialize.h
diff options
context:
space:
mode:
authorPieter Wuille <pieter.wuille@gmail.com>2014-08-07 23:00:01 +0200
committerPieter Wuille <pieter.wuille@gmail.com>2014-08-09 01:37:16 +0200
commit216e9a4456207f5ae9cd85926521851e11a26d92 (patch)
treeb85c0cd6d085ca32de8122c286cfeb4c8544c19c /src/serialize.h
parent003bbd5f7672d7fd4f40478fd57cc4e03c30f933 (diff)
Add a way to limit deserialized string lengths
and use it for most strings being serialized.
Diffstat (limited to 'src/serialize.h')
-rw-r--r--src/serialize.h39
1 files changed, 37 insertions, 2 deletions
diff --git a/src/serialize.h b/src/serialize.h
index f876efd9b5..2eb69b3ec0 100644
--- a/src/serialize.h
+++ b/src/serialize.h
@@ -334,8 +334,9 @@ I ReadVarInt(Stream& is)
}
}
-#define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
-#define VARINT(obj) REF(WrapVarInt(REF(obj)))
+#define FLATDATA(obj) REF(CFlatData((char*)&(obj), (char*)&(obj) + sizeof(obj)))
+#define VARINT(obj) REF(WrapVarInt(REF(obj)))
+#define LIMITED_STRING(obj,n) REF(LimitedString< n >(REF(obj)))
/** Wrapper for serializing arrays and POD.
*/
@@ -398,6 +399,40 @@ public:
}
};
+template<size_t Limit>
+class LimitedString
+{
+protected:
+ std::string& string;
+public:
+ LimitedString(std::string& string) : string(string) {}
+
+ template<typename Stream>
+ void Unserialize(Stream& s, int, int=0)
+ {
+ size_t size = ReadCompactSize(s);
+ if (size > Limit) {
+ throw std::ios_base::failure("String length limit exceeded");
+ }
+ string.resize(size);
+ if (size != 0)
+ s.read((char*)&string[0], size);
+ }
+
+ template<typename Stream>
+ void Serialize(Stream& s, int, int=0) const
+ {
+ WriteCompactSize(s, string.size());
+ if (!string.empty())
+ s.write((char*)&string[0], string.size());
+ }
+
+ unsigned int GetSerializeSize(int, int=0) const
+ {
+ return GetSizeOfCompactSize(string.size()) + string.size();
+ }
+};
+
template<typename I>
CVarInt<I> WrapVarInt(I& n) { return CVarInt<I>(n); }