]> Git Repo - VerusCoin.git/blob - src/streams.h
Implement CSecureDataStream for streaming CKeyingMaterial
[VerusCoin.git] / src / streams.h
1 // Copyright (c) 2009-2010 Satoshi Nakamoto
2 // Copyright (c) 2009-2013 The Bitcoin Core developers
3 // Distributed under the MIT software license, see the accompanying
4 // file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6 #ifndef BITCOIN_STREAMS_H
7 #define BITCOIN_STREAMS_H
8
9 #include "support/allocators/zeroafterfree.h"
10 #include "serialize.h"
11
12 #include <algorithm>
13 #include <assert.h>
14 #include <ios>
15 #include <limits>
16 #include <map>
17 #include <set>
18 #include <stdint.h>
19 #include <stdio.h>
20 #include <string>
21 #include <string.h>
22 #include <utility>
23 #include <vector>
24
25 /** Double ended buffer combining vector and stream-like interfaces.
26  *
27  * >> and << read and write unformatted data using the above serialization templates.
28  * Fills with data in linear time; some stringstream implementations take N^2 time.
29  */
30 template<typename SerializeType>
31 class CBaseDataStream
32 {
33 protected:
34     typedef SerializeType vector_type;
35     vector_type vch;
36     unsigned int nReadPos;
37 public:
38     int nType;
39     int nVersion;
40
41     typedef typename vector_type::allocator_type   allocator_type;
42     typedef typename vector_type::size_type        size_type;
43     typedef typename vector_type::difference_type  difference_type;
44     typedef typename vector_type::reference        reference;
45     typedef typename vector_type::const_reference  const_reference;
46     typedef typename vector_type::value_type       value_type;
47     typedef typename vector_type::iterator         iterator;
48     typedef typename vector_type::const_iterator   const_iterator;
49     typedef typename vector_type::reverse_iterator reverse_iterator;
50
51     explicit CBaseDataStream(int nTypeIn, int nVersionIn)
52     {
53         Init(nTypeIn, nVersionIn);
54     }
55
56     CBaseDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
57     {
58         Init(nTypeIn, nVersionIn);
59     }
60
61 #if !defined(_MSC_VER) || _MSC_VER >= 1300
62     CBaseDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) : vch(pbegin, pend)
63     {
64         Init(nTypeIn, nVersionIn);
65     }
66 #endif
67
68     CBaseDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
69     {
70         Init(nTypeIn, nVersionIn);
71     }
72
73     CBaseDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
74     {
75         Init(nTypeIn, nVersionIn);
76     }
77
78     CBaseDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) : vch(vchIn.begin(), vchIn.end())
79     {
80         Init(nTypeIn, nVersionIn);
81     }
82
83     void Init(int nTypeIn, int nVersionIn)
84     {
85         nReadPos = 0;
86         nType = nTypeIn;
87         nVersion = nVersionIn;
88     }
89
90     CBaseDataStream& operator+=(const CBaseDataStream& b)
91     {
92         vch.insert(vch.end(), b.begin(), b.end());
93         return *this;
94     }
95
96     friend CBaseDataStream operator+(const CBaseDataStream& a, const CBaseDataStream& b)
97     {
98         CBaseDataStream ret = a;
99         ret += b;
100         return (ret);
101     }
102
103     std::string str() const
104     {
105         return (std::string(begin(), end()));
106     }
107
108
109     //
110     // Vector subset
111     //
112     const_iterator begin() const                     { return vch.begin() + nReadPos; }
113     iterator begin()                                 { return vch.begin() + nReadPos; }
114     const_iterator end() const                       { return vch.end(); }
115     iterator end()                                   { return vch.end(); }
116     size_type size() const                           { return vch.size() - nReadPos; }
117     bool empty() const                               { return vch.size() == nReadPos; }
118     void resize(size_type n, value_type c=0)         { vch.resize(n + nReadPos, c); }
119     void reserve(size_type n)                        { vch.reserve(n + nReadPos); }
120     const_reference operator[](size_type pos) const  { return vch[pos + nReadPos]; }
121     reference operator[](size_type pos)              { return vch[pos + nReadPos]; }
122     void clear()                                     { vch.clear(); nReadPos = 0; }
123     iterator insert(iterator it, const char& x=char()) { return vch.insert(it, x); }
124     void insert(iterator it, size_type n, const char& x) { vch.insert(it, n, x); }
125
126     void insert(iterator it, std::vector<char>::const_iterator first, std::vector<char>::const_iterator last)
127     {
128         assert(last - first >= 0);
129         if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
130         {
131             // special case for inserting at the front when there's room
132             nReadPos -= (last - first);
133             memcpy(&vch[nReadPos], &first[0], last - first);
134         }
135         else
136             vch.insert(it, first, last);
137     }
138
139 #if !defined(_MSC_VER) || _MSC_VER >= 1300
140     void insert(iterator it, const char* first, const char* last)
141     {
142         assert(last - first >= 0);
143         if (it == vch.begin() + nReadPos && (unsigned int)(last - first) <= nReadPos)
144         {
145             // special case for inserting at the front when there's room
146             nReadPos -= (last - first);
147             memcpy(&vch[nReadPos], &first[0], last - first);
148         }
149         else
150             vch.insert(it, first, last);
151     }
152 #endif
153
154     iterator erase(iterator it)
155     {
156         if (it == vch.begin() + nReadPos)
157         {
158             // special case for erasing from the front
159             if (++nReadPos >= vch.size())
160             {
161                 // whenever we reach the end, we take the opportunity to clear the buffer
162                 nReadPos = 0;
163                 return vch.erase(vch.begin(), vch.end());
164             }
165             return vch.begin() + nReadPos;
166         }
167         else
168             return vch.erase(it);
169     }
170
171     iterator erase(iterator first, iterator last)
172     {
173         if (first == vch.begin() + nReadPos)
174         {
175             // special case for erasing from the front
176             if (last == vch.end())
177             {
178                 nReadPos = 0;
179                 return vch.erase(vch.begin(), vch.end());
180             }
181             else
182             {
183                 nReadPos = (last - vch.begin());
184                 return last;
185             }
186         }
187         else
188             return vch.erase(first, last);
189     }
190
191     inline void Compact()
192     {
193         vch.erase(vch.begin(), vch.begin() + nReadPos);
194         nReadPos = 0;
195     }
196
197     bool Rewind(size_type n)
198     {
199         // Rewind by n characters if the buffer hasn't been compacted yet
200         if (n > nReadPos)
201             return false;
202         nReadPos -= n;
203         return true;
204     }
205
206
207     //
208     // Stream subset
209     //
210     bool eof() const             { return size() == 0; }
211     CBaseDataStream* rdbuf()         { return this; }
212     int in_avail()               { return size(); }
213
214     void SetType(int n)          { nType = n; }
215     int GetType()                { return nType; }
216     void SetVersion(int n)       { nVersion = n; }
217     int GetVersion()             { return nVersion; }
218     void ReadVersion()           { *this >> nVersion; }
219     void WriteVersion()          { *this << nVersion; }
220
221     CBaseDataStream& read(char* pch, size_t nSize)
222     {
223         // Read from the beginning of the buffer
224         unsigned int nReadPosNext = nReadPos + nSize;
225         if (nReadPosNext >= vch.size())
226         {
227             if (nReadPosNext > vch.size())
228             {
229                 throw std::ios_base::failure("CBaseDataStream::read(): end of data");
230             }
231             memcpy(pch, &vch[nReadPos], nSize);
232             nReadPos = 0;
233             vch.clear();
234             return (*this);
235         }
236         memcpy(pch, &vch[nReadPos], nSize);
237         nReadPos = nReadPosNext;
238         return (*this);
239     }
240
241     CBaseDataStream& ignore(int nSize)
242     {
243         // Ignore from the beginning of the buffer
244         assert(nSize >= 0);
245         unsigned int nReadPosNext = nReadPos + nSize;
246         if (nReadPosNext >= vch.size())
247         {
248             if (nReadPosNext > vch.size())
249                 throw std::ios_base::failure("CBaseDataStream::ignore(): end of data");
250             nReadPos = 0;
251             vch.clear();
252             return (*this);
253         }
254         nReadPos = nReadPosNext;
255         return (*this);
256     }
257
258     CBaseDataStream& write(const char* pch, size_t nSize)
259     {
260         // Write to the end of the buffer
261         vch.insert(vch.end(), pch, pch + nSize);
262         return (*this);
263     }
264
265     template<typename Stream>
266     void Serialize(Stream& s, int nType, int nVersion) const
267     {
268         // Special case: stream << stream concatenates like stream += stream
269         if (!vch.empty())
270             s.write((char*)&vch[0], vch.size() * sizeof(vch[0]));
271     }
272
273     template<typename T>
274     unsigned int GetSerializeSize(const T& obj)
275     {
276         // Tells the size of the object if serialized to this stream
277         return ::GetSerializeSize(obj, nType, nVersion);
278     }
279
280     template<typename T>
281     CBaseDataStream& operator<<(const T& obj)
282     {
283         // Serialize to this stream
284         ::Serialize(*this, obj, nType, nVersion);
285         return (*this);
286     }
287
288     template<typename T>
289     CBaseDataStream& operator>>(T& obj)
290     {
291         // Unserialize from this stream
292         ::Unserialize(*this, obj, nType, nVersion);
293         return (*this);
294     }
295
296     void GetAndClear(CSerializeData &data) {
297         data.insert(data.end(), begin(), end());
298         clear();
299     }
300 };
301
302 class CDataStream : public CBaseDataStream<CSerializeData>
303 {
304 public:
305     explicit CDataStream(int nTypeIn, int nVersionIn) : CBaseDataStream(nTypeIn, nVersionIn) { }
306
307     CDataStream(const_iterator pbegin, const_iterator pend, int nTypeIn, int nVersionIn) :
308             CBaseDataStream(pbegin, pend, nTypeIn, nVersionIn) { }
309
310 #if !defined(_MSC_VER) || _MSC_VER >= 1300
311     CDataStream(const char* pbegin, const char* pend, int nTypeIn, int nVersionIn) :
312             CBaseDataStream(pbegin, pend, nTypeIn, nVersionIn) { }
313 #endif
314
315     CDataStream(const vector_type& vchIn, int nTypeIn, int nVersionIn) :
316             CBaseDataStream(vchIn, nTypeIn, nVersionIn) { }
317
318     CDataStream(const std::vector<char>& vchIn, int nTypeIn, int nVersionIn) :
319             CBaseDataStream(vchIn, nTypeIn, nVersionIn) { }
320
321     CDataStream(const std::vector<unsigned char>& vchIn, int nTypeIn, int nVersionIn) :
322             CBaseDataStream(vchIn, nTypeIn, nVersionIn) { }
323
324 };
325
326
327
328
329
330
331
332
333
334
335 /** Non-refcounted RAII wrapper for FILE*
336  *
337  * Will automatically close the file when it goes out of scope if not null.
338  * If you're returning the file pointer, return file.release().
339  * If you need to close the file early, use file.fclose() instead of fclose(file).
340  */
341 class CAutoFile
342 {
343 private:
344     // Disallow copies
345     CAutoFile(const CAutoFile&);
346     CAutoFile& operator=(const CAutoFile&);
347
348     int nType;
349     int nVersion;
350         
351     FILE* file; 
352
353 public:
354     CAutoFile(FILE* filenew, int nTypeIn, int nVersionIn)
355     {
356         file = filenew;
357         nType = nTypeIn;
358         nVersion = nVersionIn;
359     }
360
361     ~CAutoFile()
362     {
363         fclose();
364     }
365
366     void fclose()
367     {
368         if (file) {
369             ::fclose(file);
370             file = NULL;
371         }
372     }
373
374     /** Get wrapped FILE* with transfer of ownership.
375      * @note This will invalidate the CAutoFile object, and makes it the responsibility of the caller
376      * of this function to clean up the returned FILE*.
377      */
378     FILE* release()             { FILE* ret = file; file = NULL; return ret; }
379
380     /** Get wrapped FILE* without transfer of ownership.
381      * @note Ownership of the FILE* will remain with this class. Use this only if the scope of the
382      * CAutoFile outlives use of the passed pointer.
383      */
384     FILE* Get() const           { return file; }
385
386     /** Return true if the wrapped FILE* is NULL, false otherwise.
387      */
388     bool IsNull() const         { return (file == NULL); }
389
390     //
391     // Stream subset
392     //
393     void SetType(int n)          { nType = n; }
394     int GetType()                { return nType; }
395     void SetVersion(int n)       { nVersion = n; }
396     int GetVersion()             { return nVersion; }
397     void ReadVersion()           { *this >> nVersion; }
398     void WriteVersion()          { *this << nVersion; }
399
400     CAutoFile& read(char* pch, size_t nSize)
401     {
402         if (!file)
403             throw std::ios_base::failure("CAutoFile::read: file handle is NULL");
404         if (fread(pch, 1, nSize, file) != nSize)
405             throw std::ios_base::failure(feof(file) ? "CAutoFile::read: end of file" : "CAutoFile::read: fread failed");
406         return (*this);
407     }
408
409     CAutoFile& write(const char* pch, size_t nSize)
410     {
411         if (!file)
412             throw std::ios_base::failure("CAutoFile::write: file handle is NULL");
413         if (fwrite(pch, 1, nSize, file) != nSize)
414             throw std::ios_base::failure("CAutoFile::write: write failed");
415         return (*this);
416     }
417
418     template<typename T>
419     unsigned int GetSerializeSize(const T& obj)
420     {
421         // Tells the size of the object if serialized to this stream
422         return ::GetSerializeSize(obj, nType, nVersion);
423     }
424
425     template<typename T>
426     CAutoFile& operator<<(const T& obj)
427     {
428         // Serialize to this stream
429         if (!file)
430             throw std::ios_base::failure("CAutoFile::operator<<: file handle is NULL");
431         ::Serialize(*this, obj, nType, nVersion);
432         return (*this);
433     }
434
435     template<typename T>
436     CAutoFile& operator>>(T& obj)
437     {
438         // Unserialize from this stream
439         if (!file)
440             throw std::ios_base::failure("CAutoFile::operator>>: file handle is NULL");
441         ::Unserialize(*this, obj, nType, nVersion);
442         return (*this);
443     }
444 };
445
446 /** Non-refcounted RAII wrapper around a FILE* that implements a ring buffer to
447  *  deserialize from. It guarantees the ability to rewind a given number of bytes.
448  *
449  *  Will automatically close the file when it goes out of scope if not null.
450  *  If you need to close the file early, use file.fclose() instead of fclose(file).
451  */
452 class CBufferedFile
453 {
454 private:
455     // Disallow copies
456     CBufferedFile(const CBufferedFile&);
457     CBufferedFile& operator=(const CBufferedFile&);
458
459     int nType;
460     int nVersion;
461
462     FILE *src;            // source file
463     uint64_t nSrcPos;     // how many bytes have been read from source
464     uint64_t nReadPos;    // how many bytes have been read from this
465     uint64_t nReadLimit;  // up to which position we're allowed to read
466     uint64_t nRewind;     // how many bytes we guarantee to rewind
467     std::vector<char> vchBuf; // the buffer
468
469 protected:
470     // read data from the source to fill the buffer
471     bool Fill() {
472         unsigned int pos = nSrcPos % vchBuf.size();
473         unsigned int readNow = vchBuf.size() - pos;
474         unsigned int nAvail = vchBuf.size() - (nSrcPos - nReadPos) - nRewind;
475         if (nAvail < readNow)
476             readNow = nAvail;
477         if (readNow == 0)
478             return false;
479         size_t read = fread((void*)&vchBuf[pos], 1, readNow, src);
480         if (read == 0) {
481             throw std::ios_base::failure(feof(src) ? "CBufferedFile::Fill: end of file" : "CBufferedFile::Fill: fread failed");
482         } else {
483             nSrcPos += read;
484             return true;
485         }
486     }
487
488 public:
489     CBufferedFile(FILE *fileIn, uint64_t nBufSize, uint64_t nRewindIn, int nTypeIn, int nVersionIn) :
490         nSrcPos(0), nReadPos(0), nReadLimit((uint64_t)(-1)), nRewind(nRewindIn), vchBuf(nBufSize, 0)
491     {
492         src = fileIn;
493         nType = nTypeIn;
494         nVersion = nVersionIn;
495     }
496
497     ~CBufferedFile()
498     {
499         fclose();
500     }
501
502     void fclose()
503     {
504         if (src) {
505             ::fclose(src);
506             src = NULL;
507         }
508     }
509
510     // check whether we're at the end of the source file
511     bool eof() const {
512         return nReadPos == nSrcPos && feof(src);
513     }
514
515     // read a number of bytes
516     CBufferedFile& read(char *pch, size_t nSize) {
517         if (nSize + nReadPos > nReadLimit)
518             throw std::ios_base::failure("Read attempted past buffer limit");
519         if (nSize + nRewind > vchBuf.size())
520             throw std::ios_base::failure("Read larger than buffer size");
521         while (nSize > 0) {
522             if (nReadPos == nSrcPos)
523                 Fill();
524             unsigned int pos = nReadPos % vchBuf.size();
525             size_t nNow = nSize;
526             if (nNow + pos > vchBuf.size())
527                 nNow = vchBuf.size() - pos;
528             if (nNow + nReadPos > nSrcPos)
529                 nNow = nSrcPos - nReadPos;
530             memcpy(pch, &vchBuf[pos], nNow);
531             nReadPos += nNow;
532             pch += nNow;
533             nSize -= nNow;
534         }
535         return (*this);
536     }
537
538     // return the current reading position
539     uint64_t GetPos() {
540         return nReadPos;
541     }
542
543     // rewind to a given reading position
544     bool SetPos(uint64_t nPos) {
545         nReadPos = nPos;
546         if (nReadPos + nRewind < nSrcPos) {
547             nReadPos = nSrcPos - nRewind;
548             return false;
549         } else if (nReadPos > nSrcPos) {
550             nReadPos = nSrcPos;
551             return false;
552         } else {
553             return true;
554         }
555     }
556
557     bool Seek(uint64_t nPos) {
558         long nLongPos = nPos;
559         if (nPos != (uint64_t)nLongPos)
560             return false;
561         if (fseek(src, nLongPos, SEEK_SET))
562             return false;
563         nLongPos = ftell(src);
564         nSrcPos = nLongPos;
565         nReadPos = nLongPos;
566         return true;
567     }
568
569     // prevent reading beyond a certain position
570     // no argument removes the limit
571     bool SetLimit(uint64_t nPos = (uint64_t)(-1)) {
572         if (nPos < nReadPos)
573             return false;
574         nReadLimit = nPos;
575         return true;
576     }
577
578     template<typename T>
579     CBufferedFile& operator>>(T& obj) {
580         // Unserialize from this stream
581         ::Unserialize(*this, obj, nType, nVersion);
582         return (*this);
583     }
584
585     // search for a given byte in the stream, and remain positioned on it
586     void FindByte(char ch) {
587         while (true) {
588             if (nReadPos == nSrcPos)
589                 Fill();
590             if (vchBuf[nReadPos % vchBuf.size()] == ch)
591                 break;
592             nReadPos++;
593         }
594     }
595 };
596
597 #endif // BITCOIN_STREAMS_H
This page took 0.057239 seconds and 4 git commands to generate.