File: bencode.hpp

package info (click to toggle)
libtorrent-rasterbar 2.0.11-1
  • links: PTS
  • area: main
  • in suites: forky, trixie
  • size: 18,304 kB
  • sloc: cpp: 190,670; python: 7,142; makefile: 1,374; ansic: 574; sh: 317; xml: 104
file content (408 lines) | stat: -rw-r--r-- 10,325 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
/*

Copyright (c) 2003-2005, 2007-2009, 2012-2019, Arvid Norberg
Copyright (c) 2016, Alden Torres
Copyright (c) 2019, Amir Abrams
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#ifndef TORRENT_BENCODE_HPP_INCLUDED
#define TORRENT_BENCODE_HPP_INCLUDED

// OVERVIEW
//
// Bencoding is a common representation in bittorrent used for dictionary,
// list, int and string hierarchies. It's used to encode .torrent files and
// some messages in the network protocol. libtorrent also uses it to store
// settings, resume data and other session state.
//
// Strings in bencoded structures do not necessarily represent text.
// Strings are raw byte buffers of a certain length. If a string is meant to be
// interpreted as text, it is required to be UTF-8 encoded. See `BEP 3`_.
//
// The function for decoding bencoded data bdecode(), returning a bdecode_node.
// This function builds a tree that points back into the original buffer. The
// returned bdecode_node will not be valid once the buffer it was parsed out of
// is discarded.
//
// It's possible to construct an entry from a bdecode_node, if a structure needs
// to be altered and re-encoded.

#include <string>
#include <iterator> // for distance

#include "libtorrent/config.hpp"
#include "libtorrent/entry.hpp"
#include "libtorrent/assert.hpp"
#include "libtorrent/io.hpp" // for write_string
#include "libtorrent/string_util.hpp" // for is_digit

namespace libtorrent {

#if TORRENT_ABI_VERSION == 1
	using invalid_encoding = system_error;
#endif

namespace aux {

	template <class OutIt, class In, typename Cond
		= typename std::enable_if<std::is_integral<In>::value>::type>
	int write_integer(OutIt& out, In data)
	{
		entry::integer_type const val = entry::integer_type(data);
		TORRENT_ASSERT(data == In(val));
		// the stack allocated buffer for keeping the
		// decimal representation of the number can
		// not hold number bigger than this:
		static_assert(sizeof(entry::integer_type) <= 8, "64 bit integers required");
		static_assert(sizeof(data) <= sizeof(entry::integer_type), "input data too big, see entry::integer_type");
		std::array<char, 21> buf;
		auto const str = integer_to_str(buf, val);
		for (char const c : str)
		{
			*out = c;
			++out;
		}
		return static_cast<int>(str.size());
	}

	template <class OutIt>
	void write_char(OutIt& out, char c)
	{
		*out = c;
		++out;
	}

	template <class InIt>
	std::string read_until(InIt& in, InIt end, char end_token, bool& err)
	{
		std::string ret;
		if (in == end)
		{
			err = true;
			return ret;
		}
		while (*in != end_token)
		{
			ret += *in;
			++in;
			if (in == end)
			{
				err = true;
				return ret;
			}
		}
		return ret;
	}

	template<class InIt>
	void read_string(InIt& in, InIt end, int len, std::string& str, bool& err)
	{
		TORRENT_ASSERT(len >= 0);
		for (int i = 0; i < len; ++i)
		{
			if (in == end)
			{
				err = true;
				return;
			}
			str += *in;
			++in;
		}
	}

	template<class OutIt>
	int bencode_recursive(OutIt& out, const entry& e)
	{
		int ret = 0;
		switch(e.type())
		{
		case entry::int_t:
			write_char(out, 'i');
			ret += write_integer(out, e.integer());
			write_char(out, 'e');
			ret += 2;
			break;
		case entry::string_t:
			ret += write_integer(out, e.string().length());
			write_char(out, ':');
			ret += write_string(e.string(), out);
			ret += 1;
			break;
		case entry::list_t:
			write_char(out, 'l');
			for (auto const& i : e.list())
				ret += bencode_recursive(out, i);
			write_char(out, 'e');
			ret += 2;
			break;
		case entry::dictionary_t:
			write_char(out, 'd');
			for (auto const& i : e.dict())
			{
				// write key
				ret += write_integer(out, i.first.length());
				write_char(out, ':');
				ret += write_string(i.first, out);
				// write value
				ret += bencode_recursive(out, i.second);
				ret += 1;
			}
			write_char(out, 'e');
			ret += 2;
			break;
		case entry::preformatted_t:
			std::copy(e.preformatted().begin(), e.preformatted().end(), out);
			ret += static_cast<int>(e.preformatted().size());
			break;
		case entry::undefined_t:

			// empty string
			write_char(out, '0');
			write_char(out, ':');

			ret += 2;
			break;
		}
		return ret;
	}
#if TORRENT_ABI_VERSION == 1
	template<class InIt>
	void bdecode_recursive(InIt& in, InIt end, entry& ret, bool& err, int depth)
	{
		if (depth >= 100)
		{
			err = true;
			return;
		}

		if (in == end)
		{
			err = true;
#if TORRENT_USE_ASSERTS
			ret.m_type_queried = false;
#endif
			return;
		}
		switch (*in)
		{

		// ----------------------------------------------
		// integer
		case 'i':
			{
			++in; // 'i'
			std::string const val = read_until(in, end, 'e', err);
			if (err) return;
			TORRENT_ASSERT(*in == 'e');
			++in; // 'e'
			ret = entry(entry::int_t);
			char* end_pointer;
			ret.integer() = std::strtoll(val.c_str(), &end_pointer, 10);
#if TORRENT_USE_ASSERTS
			ret.m_type_queried = false;
#endif
			if (end_pointer == val.c_str())
			{
				err = true;
				return;
			}
			}
			break;

		// ----------------------------------------------
		// list
		case 'l':
			ret = entry(entry::list_t);
			++in; // 'l'
			while (*in != 'e')
			{
				ret.list().emplace_back();
				entry& e = ret.list().back();
				bdecode_recursive(in, end, e, err, depth + 1);
				if (err)
				{
#if TORRENT_USE_ASSERTS
					ret.m_type_queried = false;
#endif
					return;
				}
				if (in == end)
				{
					err = true;
#if TORRENT_USE_ASSERTS
					ret.m_type_queried = false;
#endif
					return;
				}
			}
#if TORRENT_USE_ASSERTS
			ret.m_type_queried = false;
#endif
			TORRENT_ASSERT(*in == 'e');
			++in; // 'e'
			break;

		// ----------------------------------------------
		// dictionary
		case 'd':
			ret = entry(entry::dictionary_t);
			++in; // 'd'
			while (*in != 'e')
			{
				entry key;
				bdecode_recursive(in, end, key, err, depth + 1);
				if (err || key.type() != entry::string_t)
				{
#if TORRENT_USE_ASSERTS
					ret.m_type_queried = false;
#endif
					return;
				}
				entry& e = ret[key.string()];
				bdecode_recursive(in, end, e, err, depth + 1);
				if (err)
				{
#if TORRENT_USE_ASSERTS
					ret.m_type_queried = false;
#endif
					return;
				}
				if (in == end)
				{
					err = true;
#if TORRENT_USE_ASSERTS
					ret.m_type_queried = false;
#endif
					return;
				}
			}
#if TORRENT_USE_ASSERTS
			ret.m_type_queried = false;
#endif
			TORRENT_ASSERT(*in == 'e');
			++in; // 'e'
			break;

		// ----------------------------------------------
		// string
		default:
			static_assert(sizeof(*in) == 1, "Input iterator to 8 bit data required");
			if (is_digit(char(*in)))
			{
				std::string len_s = read_until(in, end, ':', err);
				if (err)
				{
#if TORRENT_USE_ASSERTS
					ret.m_type_queried = false;
#endif
					return;
				}
				TORRENT_ASSERT(*in == ':');
				++in; // ':'
				int len = atoi(len_s.c_str());
				ret = entry(entry::string_t);
				read_string(in, end, len, ret.string(), err);
				if (err)
				{
#if TORRENT_USE_ASSERTS
					ret.m_type_queried = false;
#endif
					return;
				}
			}
			else
			{
				err = true;
#if TORRENT_USE_ASSERTS
				ret.m_type_queried = false;
#endif
				return;
			}
#if TORRENT_USE_ASSERTS
			ret.m_type_queried = false;
#endif
		}
	}
#endif // TORRENT_ABI_VERSION
}

	// This function will encode data to bencoded form.
	//
	// The entry_ class is the internal representation of the bencoded data
	// and it can be used to retrieve information, an entry_ can also be build by
	// the program and given to ``bencode()`` to encode it into the ``OutIt``
	// iterator.
	//
	// ``OutIt`` is an OutputIterator_. It's a template and usually
	// instantiated as ostream_iterator_ or back_insert_iterator_. This
	// function assumes the value_type of the iterator is a ``char``.
	// In order to encode entry ``e`` into a buffer, do::
	//
	//	std::vector<char> buf;
	//	bencode(std::back_inserter(buf), e);
	//
	// .. _OutputIterator:  https://en.cppreference.com/w/cpp/named_req/OutputIterator
	// .. _ostream_iterator: https://en.cppreference.com/w/cpp/iterator/ostream_iterator
	// .. _back_insert_iterator: https://en.cppreference.com/w/cpp/iterator/back_insert_iterator
	template<class OutIt> int bencode(OutIt out, const entry& e)
	{
		return aux::bencode_recursive(out, e);
	}

#if TORRENT_ABI_VERSION == 1
	template<class InIt>
	TORRENT_DEPRECATED
	entry bdecode(InIt start, InIt end)
	{
		entry e;
		bool err = false;
		aux::bdecode_recursive(start, end, e, err, 0);
		TORRENT_ASSERT(e.m_type_queried == false);
		if (err) return entry();
		return e;
	}
	template<class InIt>
	TORRENT_DEPRECATED
	entry bdecode(InIt start, InIt end
		, typename std::iterator_traits<InIt>::difference_type& len)
	{
		entry e;
		bool err = false;
		InIt s = start;
		aux::bdecode_recursive(start, end, e, err, 0);
		len = std::distance(s, start);
		TORRENT_ASSERT(len >= 0);
		if (err) return entry();
		return e;
	}
#endif
}

#endif // TORRENT_BENCODE_HPP_INCLUDED