summaryrefslogtreecommitdiffstats
path: root/lib/base/netstring.cpp
blob: 60f08c2652f6e7d8f5d3de6bd4795fb7b0e3cc71 (plain)
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
/* Icinga 2 | (c) 2012 Icinga GmbH | GPLv2+ */

#include "base/netstring.hpp"
#include "base/debug.hpp"
#include "base/tlsstream.hpp"
#include <cstdint>
#include <memory>
#include <sstream>
#include <utility>
#include <boost/asio/buffer.hpp>
#include <boost/asio/read.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/asio/write.hpp>

using namespace icinga;

/**
 * Reads data from a stream in netstring format.
 *
 * @param stream The stream to read from.
 * @param[out] str The String that has been read from the IOQueue.
 * @returns true if a complete String was read from the IOQueue, false otherwise.
 * @exception invalid_argument The input stream is invalid.
 * @see https://github.com/PeterScott/netstring-c/blob/master/netstring.c
 */
StreamReadStatus NetString::ReadStringFromStream(const Stream::Ptr& stream, String *str, StreamReadContext& context,
	bool may_wait, ssize_t maxMessageLength)
{
	if (context.Eof)
		return StatusEof;

	if (context.MustRead) {
		if (!context.FillFromStream(stream, may_wait)) {
			context.Eof = true;
			return StatusEof;
		}

		context.MustRead = false;
	}

	size_t header_length = 0;

	for (size_t i = 0; i < context.Size; i++) {
		if (context.Buffer[i] == ':') {
			header_length = i;

			/* make sure there's a header */
			if (header_length == 0)
				BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid NetString (no length specifier)"));

			break;
		} else if (i > 16)
			BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid NetString (missing :)"));
	}

	if (header_length == 0) {
		context.MustRead = true;
		return StatusNeedData;
	}

	/* no leading zeros allowed */
	if (context.Buffer[0] == '0' && isdigit(context.Buffer[1]))
		BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid NetString (leading zero)"));

	size_t len, i;

	len = 0;
	for (i = 0; i < header_length && isdigit(context.Buffer[i]); i++) {
		/* length specifier must have at most 9 characters */
		if (i >= 9)
			BOOST_THROW_EXCEPTION(std::invalid_argument("Length specifier must not exceed 9 characters"));

		len = len * 10 + (context.Buffer[i] - '0');
	}

	/* read the whole message */
	size_t data_length = len + 1;

	if (maxMessageLength >= 0 && data_length > (size_t)maxMessageLength) {
		std::stringstream errorMessage;
		errorMessage << "Max data length exceeded: " << (maxMessageLength / 1024) << " KB";

		BOOST_THROW_EXCEPTION(std::invalid_argument(errorMessage.str()));
	}

	char *data = context.Buffer + header_length + 1;

	if (context.Size < header_length + 1 + data_length) {
		context.MustRead = true;
		return StatusNeedData;
	}

	if (data[len] != ',')
		BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid NetString (missing ,)"));

	*str = String(&data[0], &data[len]);

	context.DropData(header_length + 1 + len + 1);

	return StatusNewItem;
}

/**
 * Writes data into a stream using the netstring format and returns bytes written.
 *
 * @param stream The stream.
 * @param str The String that is to be written.
 *
 * @return The amount of bytes written.
 */
size_t NetString::WriteStringToStream(const Stream::Ptr& stream, const String& str)
{
	std::ostringstream msgbuf;
	WriteStringToStream(msgbuf, str);

	String msg = msgbuf.str();
	stream->Write(msg.CStr(), msg.GetLength());
	return msg.GetLength();
}

/**
 * Reads data from a stream in netstring format.
 *
 * @param stream The stream to read from.
 * @returns The String that has been read from the IOQueue.
 * @exception invalid_argument The input stream is invalid.
 * @see https://github.com/PeterScott/netstring-c/blob/master/netstring.c
 */
String NetString::ReadStringFromStream(const Shared<AsioTlsStream>::Ptr& stream,
	ssize_t maxMessageLength)
{
	namespace asio = boost::asio;

	size_t len = 0;
	bool leadingZero = false;

	for (uint_fast8_t readBytes = 0;; ++readBytes) {
		char byte = 0;

		{
			asio::mutable_buffer byteBuf (&byte, 1);
			asio::read(*stream, byteBuf);
		}

		if (isdigit(byte)) {
			if (readBytes == 9) {
				BOOST_THROW_EXCEPTION(std::invalid_argument("Length specifier must not exceed 9 characters"));
			}

			if (leadingZero) {
				BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid NetString (leading zero)"));
			}

			len = len * 10u + size_t(byte - '0');

			if (!readBytes && byte == '0') {
				leadingZero = true;
			}
		} else if (byte == ':') {
			if (!readBytes) {
				BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid NetString (no length specifier)"));
			}

			break;
		} else {
			BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid NetString (missing :)"));
		}
	}

	if (maxMessageLength >= 0 && len > maxMessageLength) {
		std::stringstream errorMessage;
		errorMessage << "Max data length exceeded: " << (maxMessageLength / 1024) << " KB";

		BOOST_THROW_EXCEPTION(std::invalid_argument(errorMessage.str()));
	}

	String payload;

	if (len) {
		payload.Append(len, 0);

		asio::mutable_buffer payloadBuf (&*payload.Begin(), payload.GetLength());
		asio::read(*stream, payloadBuf);
	}

	char trailer = 0;

	{
		asio::mutable_buffer trailerBuf (&trailer, 1);
		asio::read(*stream, trailerBuf);
	}

	if (trailer != ',') {
		BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid NetString (missing ,)"));
	}

	return payload;
}

/**
 * Reads data from a stream in netstring format.
 *
 * @param stream The stream to read from.
 * @returns The String that has been read from the IOQueue.
 * @exception invalid_argument The input stream is invalid.
 * @see https://github.com/PeterScott/netstring-c/blob/master/netstring.c
 */
String NetString::ReadStringFromStream(const Shared<AsioTlsStream>::Ptr& stream,
	boost::asio::yield_context yc, ssize_t maxMessageLength)
{
	namespace asio = boost::asio;

	size_t len = 0;
	bool leadingZero = false;

	for (uint_fast8_t readBytes = 0;; ++readBytes) {
		char byte = 0;

		{
			asio::mutable_buffer byteBuf (&byte, 1);
			asio::async_read(*stream, byteBuf, yc);
		}

		if (isdigit(byte)) {
			if (readBytes == 9) {
				BOOST_THROW_EXCEPTION(std::invalid_argument("Length specifier must not exceed 9 characters"));
			}

			if (leadingZero) {
				BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid NetString (leading zero)"));
			}

			len = len * 10u + size_t(byte - '0');

			if (!readBytes && byte == '0') {
				leadingZero = true;
			}
		} else if (byte == ':') {
			if (!readBytes) {
				BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid NetString (no length specifier)"));
			}

			break;
		} else {
			BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid NetString (missing :)"));
		}
	}

	if (maxMessageLength >= 0 && len > maxMessageLength) {
		std::stringstream errorMessage;
		errorMessage << "Max data length exceeded: " << (maxMessageLength / 1024) << " KB";

		BOOST_THROW_EXCEPTION(std::invalid_argument(errorMessage.str()));
	}

	String payload;

	if (len) {
		payload.Append(len, 0);

		asio::mutable_buffer payloadBuf (&*payload.Begin(), payload.GetLength());
		asio::async_read(*stream, payloadBuf, yc);
	}

	char trailer = 0;

	{
		asio::mutable_buffer trailerBuf (&trailer, 1);
		asio::async_read(*stream, trailerBuf, yc);
	}

	if (trailer != ',') {
		BOOST_THROW_EXCEPTION(std::invalid_argument("Invalid NetString (missing ,)"));
	}

	return payload;
}

/**
 * Writes data into a stream using the netstring format and returns bytes written.
 *
 * @param stream The stream.
 * @param str The String that is to be written.
 *
 * @return The amount of bytes written.
 */
size_t NetString::WriteStringToStream(const Shared<AsioTlsStream>::Ptr& stream, const String& str)
{
	namespace asio = boost::asio;

	std::ostringstream msgbuf;
	WriteStringToStream(msgbuf, str);

	String msg = msgbuf.str();
	asio::const_buffer msgBuf (msg.CStr(), msg.GetLength());

	asio::write(*stream, msgBuf);

	return msg.GetLength();
}

/**
 * Writes data into a stream using the netstring format and returns bytes written.
 *
 * @param stream The stream.
 * @param str The String that is to be written.
 *
 * @return The amount of bytes written.
 */
size_t NetString::WriteStringToStream(const Shared<AsioTlsStream>::Ptr& stream, const String& str, boost::asio::yield_context yc)
{
	namespace asio = boost::asio;

	std::ostringstream msgbuf;
	WriteStringToStream(msgbuf, str);

	String msg = msgbuf.str();
	asio::const_buffer msgBuf (msg.CStr(), msg.GetLength());

	asio::async_write(*stream, msgBuf, yc);

	return msg.GetLength();
}

/**
 * Writes data into a stream using the netstring format.
 *
 * @param stream The stream.
 * @param str The String that is to be written.
 */
void NetString::WriteStringToStream(std::ostream& stream, const String& str)
{
	stream << str.GetLength() << ":" << str << ",";
}