Debian Codegraph @

src/capnp/serialize-async-test.c++

raw
1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
2 // Licensed under the MIT License:
3 //
4 // Permission is hereby granted, free of charge, to any person obtaining a copy
5 // of this software and associated documentation files (the "Software"), to deal
6 // in the Software without restriction, including without limitation the rights
7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8 // copies of the Software, and to permit persons to whom the Software is
9 // furnished to do so, subject to the following conditions:
10 //
11 // The above copyright notice and this permission notice shall be included in
12 // all copies or substantial portions of the Software.
13 //
14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20 // THE SOFTWARE.
21
22 #ifndef _GNU_SOURCE
23 #define _GNU_SOURCE
24 #endif
25
26 #if _WIN32
27 #include <kj/win32-api-version.h>
28 #endif
29
30 #include "serialize-async.h"
31 #include "serialize.h"
32 #include <kj/debug.h>
33 #include <kj/thread.h>
34 #include <stdlib.h>
35 #include <kj/miniposix.h>
36 #include "test-util.h"
37 #include <kj/compat/gtest.h>
38 #include <kj/io.h>
39
40 #if _WIN32
41 #include <winsock2.h>
42 #include <kj/windows-sanity.h>
43 namespace kj {
44 namespace _ {
45 int win32Socketpair(SOCKET socks[2]);
46 }
47 }
48 #else
49 #include <sys/socket.h>
50 #endif
51
52 namespace capnp {
53 namespace _ { // private
54 namespace {
55
56 #if _WIN32
57 inline void delay() { Sleep(5); }
58 #else
59 inline void delay() { usleep(5000); }
60 #endif
61
62 class FragmentingOutputStream: public kj::OutputStream {
63 public:
64 FragmentingOutputStream(kj::OutputStream& inner): inner(inner) {}
65
66 void write(const void* buffer, size_t size) override {
67 while (size > 0) {
68 delay();
69 size_t n = rand() % size + 1;
70 inner.write(buffer, n);
71 buffer = reinterpret_cast<const byte*>(buffer) + n;
72 size -= n;
73 }
74 }
75
76 private:
77 kj::OutputStream& inner;
78 };
79
80 class TestMessageBuilder: public MallocMessageBuilder {
81 // A MessageBuilder that tries to allocate an exact number of total segments, by allocating
82 // minimum-size segments until it reaches the number, then allocating one large segment to
83 // finish.
84
85 public:
86 explicit TestMessageBuilder(uint desiredSegmentCount)
87 : MallocMessageBuilder(0, AllocationStrategy::FIXED_SIZE),
88 desiredSegmentCount(desiredSegmentCount) {}
89 ~TestMessageBuilder() {
90 EXPECT_EQ(0u, desiredSegmentCount);
91 }
92
93 kj::ArrayPtr<word> allocateSegment(uint minimumSize) override {
94 if (desiredSegmentCount <= 1) {
95 if (desiredSegmentCount < 1) {
96 ADD_FAILURE() << "Allocated more segments than desired.";
97 } else {
98 --desiredSegmentCount;
99 }
100 return MallocMessageBuilder::allocateSegment(8192);
101 } else {
102 --desiredSegmentCount;
103 return MallocMessageBuilder::allocateSegment(minimumSize);
104 }
105 }
106
107 private:
108 uint desiredSegmentCount;
109 };
110
111 class PipeWithSmallBuffer {
112 public:
113 #ifdef _WIN32
114 #define KJ_SOCKCALL KJ_WINSOCK
115 #ifndef SHUT_WR
116 #define SHUT_WR SD_SEND
117 #endif
118 #define socketpair(family, type, flags, fds) kj::_::win32Socketpair(fds)
119 #else
120 #define KJ_SOCKCALL KJ_SYSCALL
121 #endif
122
123 PipeWithSmallBuffer() {
124 // Use a socketpair rather than a pipe so that we can set the buffer size extremely small.
125 KJ_SOCKCALL(socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
126
127 KJ_SOCKCALL(shutdown(fds[0], SHUT_WR));
128 // Note: OSX reports ENOTCONN if we also try to shutdown(fds[1], SHUT_RD).
129
130 // Request that the buffer size be as small as possible, to force the event loop to kick in.
131 // FUN STUFF:
132 // - On Linux, the kernel rounds up to the smallest size it permits, so we can ask for a size of
133 // zero.
134 // - On OSX, the kernel reports EINVAL on zero, but will dutifully use a 1-byte buffer if we
135 // set the size to 1. This tends to cause stack overflows due to ridiculously long promise
136 // chains.
137 // - Cygwin will apparently actually use a buffer size of 0 and therefore block forever waiting
138 // for buffer space.
139 // - GNU HURD throws ENOPROTOOPT for SO_RCVBUF. Apparently, technically, a Unix domain socket
140 // has only one buffer, and it's controlled via SO_SNDBUF on the other end. OK, we'll ignore
141 // errors on SO_RCVBUF, then.
142 //
143 // Anyway, we now use 127 to avoid these issues (but also to screw around with non-word-boundary
144 // writes).
145 uint small = 127;
146 setsockopt(fds[0], SOL_SOCKET, SO_RCVBUF, (const char*)&small, sizeof(small));
147 KJ_SOCKCALL(setsockopt(fds[1], SOL_SOCKET, SO_SNDBUF, (const char*)&small, sizeof(small)));
148 }
149 ~PipeWithSmallBuffer() {
150 #if _WIN32
151 closesocket(fds[0]);
152 closesocket(fds[1]);
153 #else
154 close(fds[0]);
155 close(fds[1]);
156 #endif
157 }
158
159 inline int operator[](uint index) { return fds[index]; }
160
161 private:
162 #ifdef _WIN32
163 SOCKET fds[2];
164 #else
165 int fds[2];
166 #endif
167 };
168
169 #if _WIN32
170 // Sockets on win32 are not file descriptors. Ugh.
171 //
172 // TODO(cleanup): Maybe put these somewhere reusable? kj/io.h is inappropriate since we don't
173 // really want to link against winsock.
174
175 class SocketOutputStream: public kj::OutputStream {
176 public:
177 explicit SocketOutputStream(SOCKET fd): fd(fd) {}
178
179 void write(const void* buffer, size_t size) override {
180 const char* ptr = reinterpret_cast<const char*>(buffer);
181 while (size > 0) {
182 kj::miniposix::ssize_t n;
183 KJ_SOCKCALL(n = send(fd, ptr, size, 0));
184 size -= n;
185 ptr += n;
186 }
187 }
188
189 private:
190 SOCKET fd;
191 };
192
193 class SocketInputStream: public kj::InputStream {
194 public:
195 explicit SocketInputStream(SOCKET fd): fd(fd) {}
196
197 size_t tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
198 char* ptr = reinterpret_cast<char*>(buffer);
199 size_t total = 0;
200 while (total < minBytes) {
201 kj::miniposix::ssize_t n;
202 KJ_SOCKCALL(n = recv(fd, ptr, maxBytes, 0));
203 total += n;
204 maxBytes -= n;
205 ptr += n;
206 }
207 return total;
208 }
209
210 private:
211 SOCKET fd;
212 };
213 #else // _WIN32
214 typedef kj::FdOutputStream SocketOutputStream;
215 typedef kj::FdInputStream SocketInputStream;
216 #endif // _WIN32, else
217
218 TEST(SerializeAsyncTest, ParseAsync) {
219 PipeWithSmallBuffer fds;
220 auto ioContext = kj::setupAsyncIo();
221 auto input = ioContext.lowLevelProvider->wrapInputFd(fds[0]);
222 SocketOutputStream rawOutput(fds[1]);
223 FragmentingOutputStream output(rawOutput);
224
225 TestMessageBuilder message(1);
226 initTestMessage(message.getRoot<TestAllTypes>());
227
228 kj::Thread thread([&]() {
229 writeMessage(output, message);
230 });
231
232 auto received = readMessage(*input).wait(ioContext.waitScope);
233
234 checkTestMessage(received->getRoot<TestAllTypes>());
235 }
236
237 TEST(SerializeAsyncTest, ParseAsyncOddSegmentCount) {
238 PipeWithSmallBuffer fds;
239 auto ioContext = kj::setupAsyncIo();
240 auto input = ioContext.lowLevelProvider->wrapInputFd(fds[0]);
241 SocketOutputStream rawOutput(fds[1]);
242 FragmentingOutputStream output(rawOutput);
243
244 TestMessageBuilder message(7);
245 initTestMessage(message.getRoot<TestAllTypes>());
246
247 kj::Thread thread([&]() {
248 writeMessage(output, message);
249 });
250
251 auto received = readMessage(*input).wait(ioContext.waitScope);
252
253 checkTestMessage(received->getRoot<TestAllTypes>());
254 }
255
256 TEST(SerializeAsyncTest, ParseAsyncEvenSegmentCount) {
257 PipeWithSmallBuffer fds;
258 auto ioContext = kj::setupAsyncIo();
259 auto input = ioContext.lowLevelProvider->wrapInputFd(fds[0]);
260 SocketOutputStream rawOutput(fds[1]);
261 FragmentingOutputStream output(rawOutput);
262
263 TestMessageBuilder message(10);
264 initTestMessage(message.getRoot<TestAllTypes>());
265
266 kj::Thread thread([&]() {
267 writeMessage(output, message);
268 });
269
270 auto received = readMessage(*input).wait(ioContext.waitScope);
271
272 checkTestMessage(received->getRoot<TestAllTypes>());
273 }
274
275 TEST(SerializeAsyncTest, WriteAsync) {
276 PipeWithSmallBuffer fds;
277 auto ioContext = kj::setupAsyncIo();
278 auto output = ioContext.lowLevelProvider->wrapOutputFd(fds[1]);
279
280 TestMessageBuilder message(1);
281 auto root = message.getRoot<TestAllTypes>();
282 auto list = root.initStructList(16);
283 for (auto element: list) {
284 initTestMessage(element);
285 }
286
287 kj::Thread thread([&]() {
288 SocketInputStream input(fds[0]);
289 InputStreamMessageReader reader(input);
290 auto listReader = reader.getRoot<TestAllTypes>().getStructList();
291 EXPECT_EQ(list.size(), listReader.size());
292 for (auto element: listReader) {
293 checkTestMessage(element);
294 }
295 });
296
297 writeMessage(*output, message).wait(ioContext.waitScope);
298 }
299
300 TEST(SerializeAsyncTest, WriteAsyncOddSegmentCount) {
301 PipeWithSmallBuffer fds;
302 auto ioContext = kj::setupAsyncIo();
303 auto output = ioContext.lowLevelProvider->wrapOutputFd(fds[1]);
304
305 TestMessageBuilder message(7);
306 auto root = message.getRoot<TestAllTypes>();
307 auto list = root.initStructList(16);
308 for (auto element: list) {
309 initTestMessage(element);
310 }
311
312 kj::Thread thread([&]() {
313 SocketInputStream input(fds[0]);
314 InputStreamMessageReader reader(input);
315 auto listReader = reader.getRoot<TestAllTypes>().getStructList();
316 EXPECT_EQ(list.size(), listReader.size());
317 for (auto element: listReader) {
318 checkTestMessage(element);
319 }
320 });
321
322 writeMessage(*output, message).wait(ioContext.waitScope);
323 }
324
325 TEST(SerializeAsyncTest, WriteAsyncEvenSegmentCount) {
326 PipeWithSmallBuffer fds;
327 auto ioContext = kj::setupAsyncIo();
328 auto output = ioContext.lowLevelProvider->wrapOutputFd(fds[1]);
329
330 TestMessageBuilder message(10);
331 auto root = message.getRoot<TestAllTypes>();
332 auto list = root.initStructList(16);
333 for (auto element: list) {
334 initTestMessage(element);
335 }
336
337 kj::Thread thread([&]() {
338 SocketInputStream input(fds[0]);
339 InputStreamMessageReader reader(input);
340 auto listReader = reader.getRoot<TestAllTypes>().getStructList();
341 EXPECT_EQ(list.size(), listReader.size());
342 for (auto element: listReader) {
343 checkTestMessage(element);
344 }
345 });
346
347 writeMessage(*output, message).wait(ioContext.waitScope);
348 }
349
350 TEST(SerializeAsyncTest, WriteMultipleMessagesAsync) {
351 PipeWithSmallBuffer fds;
352 auto ioContext = kj::setupAsyncIo();
353 auto output = ioContext.lowLevelProvider->wrapOutputFd(fds[1]);
354
355 const int numMessages = 5;
356 const int baseListSize = 16;
357 auto messages = kj::heapArrayBuilder<TestMessageBuilder>(numMessages);
358 for (int i = 0; i < numMessages; ++i) {
359 messages.add(i+1);
360 auto root = messages[i].getRoot<TestAllTypes>();
361 auto list = root.initStructList(baseListSize+i);
362 for (auto element: list) {
363 initTestMessage(element);
364 }
365 }
366
367 kj::Thread thread([&]() {
368 SocketInputStream input(fds[0]);
369 for (int i = 0; i < numMessages; ++i) {
370 InputStreamMessageReader reader(input);
371 auto listReader = reader.getRoot<TestAllTypes>().getStructList();
372 EXPECT_EQ(baseListSize+i, listReader.size());
373 for (auto element: listReader) {
374 checkTestMessage(element);
375 }
376 }
377 });
378
379 auto msgs = kj::heapArray<capnp::MessageBuilder*>(numMessages);
380 for (int i = 0; i < numMessages; ++i) {
381 msgs[i] = &messages[i];
382 }
383 writeMessages(*output, msgs).wait(ioContext.waitScope);
384 }
385
386 void writeSmallMessage(kj::OutputStream& output, kj::StringPtr text) {
387 capnp::MallocMessageBuilder message;
388 message.getRoot<test::TestAnyPointer>().getAnyPointerField().setAs<Text>(text);
389 writeMessage(output, message);
390 }
391
392 void expectSmallMessage(MessageStream& stream, kj::StringPtr text, kj::WaitScope& waitScope) {
393 auto msg = stream.readMessage().wait(waitScope);
394 KJ_EXPECT(msg->getRoot<test::TestAnyPointer>().getAnyPointerField().getAs<Text>() == text);
395 }
396
397 void writeBigMessage(kj::OutputStream& output) {
398 capnp::MallocMessageBuilder message(4); // first segment is small
399 initTestMessage(message.getRoot<test::TestAllTypes>());
400 writeMessage(output, message);
401 }
402
403 void expectBigMessage(MessageStream& stream, kj::WaitScope& waitScope) {
404 auto msg = stream.readMessage().wait(waitScope);
405 checkTestMessage(msg->getRoot<test::TestAllTypes>());
406 }
407
408 KJ_TEST("BufferedMessageStream basics") {
409 // Encode input data.
410 kj::VectorOutputStream data;
411
412 writeSmallMessage(data, "foo");
413
414 KJ_EXPECT(data.getArray().size() / sizeof(word) == 4);
415
416 // A big message (more than half a buffer)
417 writeBigMessage(data);
418
419 KJ_EXPECT(data.getArray().size() / sizeof(word) > 16);
420
421 writeSmallMessage(data, "bar");
422 writeSmallMessage(data, "baz");
423 writeSmallMessage(data, "qux");
424
425 // Run the test.
426 kj::EventLoop loop;
427 kj::WaitScope waitScope(loop);
428
429 auto pipe = kj::newTwoWayPipe();
430 auto writePromise = pipe.ends[1]->write(data.getArray().begin(), data.getArray().size());
431
432 uint callbackCallCount = 0;
433 auto callback = [&](MessageReader& reader) {
434 ++callbackCallCount;
435 return false;
436 };
437
438 BufferedMessageStream stream(*pipe.ends[0], callback, 16);
439 expectSmallMessage(stream, "foo", waitScope);
440 KJ_EXPECT(callbackCallCount == 1);
441
442 KJ_EXPECT(!writePromise.poll(waitScope));
443
444 expectBigMessage(stream, waitScope);
445 KJ_EXPECT(callbackCallCount == 1); // no callback on big message
446
447 KJ_EXPECT(!writePromise.poll(waitScope));
448
449 expectSmallMessage(stream, "bar", waitScope);
450 KJ_EXPECT(callbackCallCount == 2);
451
452 // All data is now in the buffer, so this part is done.
453 KJ_EXPECT(writePromise.poll(waitScope));
454
455 expectSmallMessage(stream, "baz", waitScope);
456 expectSmallMessage(stream, "qux", waitScope);
457 KJ_EXPECT(callbackCallCount == 4);
458
459 auto eofPromise = stream.MessageStream::tryReadMessage();
460 KJ_EXPECT(!eofPromise.poll(waitScope));
461
462 pipe.ends[1]->shutdownWrite();
463 KJ_EXPECT(eofPromise.wait(waitScope) == nullptr);
464 }
465
466 KJ_TEST("BufferedMessageStream fragmented reads") {
467 // Encode input data.
468 kj::VectorOutputStream data;
469 writeBigMessage(data);
470
471 // Run the test.
472 kj::EventLoop loop;
473 kj::WaitScope waitScope(loop);
474
475 auto pipe = kj::newTwoWayPipe();
476 auto callback = [&](MessageReader& reader) {
477 return false;
478 };
479 BufferedMessageStream stream(*pipe.ends[0], callback, 16);
480
481 // Arrange to read a big message.
482 auto readPromise = stream.MessageStream::tryReadMessage();
483 KJ_EXPECT(!readPromise.poll(waitScope));
484
485 auto remainingData = data.getArray();
486
487 // Write 5 bytes. This won't even fulfill the first read's minBytes.
488 pipe.ends[1]->write(remainingData.begin(), 5).wait(waitScope);
489 remainingData = remainingData.slice(5, remainingData.size());
490 KJ_EXPECT(!readPromise.poll(waitScope));
491
492 // Write 4 more. Now the MessageStream will only see the first word which contains the first
493 // segment size. This size is small so the MessageStream won't yet fall back to
494 // readEntireMessage().
495 pipe.ends[1]->write(remainingData.begin(), 4).wait(waitScope);
496 remainingData = remainingData.slice(4, remainingData.size());
497 KJ_EXPECT(!readPromise.poll(waitScope));
498
499 // Drip 10 more bytes. Now the MessageStream will realize that it needs to try
500 // readEntireMessage().
501 pipe.ends[1]->write(remainingData.begin(), 10).wait(waitScope);
502 remainingData = remainingData.slice(10, remainingData.size());
503 KJ_EXPECT(!readPromise.poll(waitScope));
504
505 // Give it all except the last byte.
506 pipe.ends[1]->write(remainingData.begin(), remainingData.size() - 1).wait(waitScope);
507 remainingData = remainingData.slice(remainingData.size() - 1, remainingData.size());
508 KJ_EXPECT(!readPromise.poll(waitScope));
509
510 // Finish it off.
511 pipe.ends[1]->write(remainingData.begin(), 1).wait(waitScope);
512 KJ_ASSERT(readPromise.poll(waitScope));
513
514 auto msg = readPromise.wait(waitScope);
515 checkTestMessage(KJ_ASSERT_NONNULL(msg)->getRoot<test::TestAllTypes>());
516 }
517
518 KJ_TEST("BufferedMessageStream many small messages") {
519 // Encode input data.
520 kj::VectorOutputStream data;
521
522 for (auto i: kj::zeroTo(16)) {
523 // Intentionally make these 5 words each so they cross buffer boundaries.
524 writeSmallMessage(data, kj::str("12345678-", i));
525 KJ_EXPECT(data.getArray().size() / sizeof(word) == (i+1) * 5);
526 }
527
528 // Run the test.
529 kj::EventLoop loop;
530 kj::WaitScope waitScope(loop);
531
532 auto pipe = kj::newTwoWayPipe();
533 auto writePromise = pipe.ends[1]->write(data.getArray().begin(), data.getArray().size())
534 .then([&]() {
535 // Write some garbage at the end.
536 return pipe.ends[1]->write("bogus", 5);
537 }).then([&]() {
538 // EOF.
539 return pipe.ends[1]->shutdownWrite();
540 }).eagerlyEvaluate(nullptr);
541
542 uint callbackCallCount = 0;
543 auto callback = [&](MessageReader& reader) {
544 ++callbackCallCount;
545 return false;
546 };
547
548 BufferedMessageStream stream(*pipe.ends[0], callback, 16);
549
550 for (auto i: kj::zeroTo(16)) {
551 // Intentionally make these 5 words each so they cross buffer boundaries.
552 expectSmallMessage(stream, kj::str("12345678-", i), waitScope);
553 KJ_EXPECT(callbackCallCount == i + 1);
554 }
555
556 KJ_EXPECT_THROW(DISCONNECTED, stream.MessageStream::tryReadMessage().wait(waitScope));
557 KJ_EXPECT(callbackCallCount == 16);
558 }
559
560 // TODO(test): We should probably test BufferedMessageStream's FD handling here... but really it
561 // gets tested well enough by rpc-twoparty-test.
562
563 // Test for security bug: security-advisories/2026-03-10-0-segment-count-overflow.md
564 KJ_TEST("large segment counts are rejected -- even UINT_MAX") {
565 kj::EventLoop loop;
566 kj::WaitScope ws(loop);
567
568 // Construct a message with segment count of UINT_MAX, which previously led to an integer
569 // overflow leading to a zero-byte allocation, into which a pointer was written (buffer overrun,
570 // though fortunately benign on all known memory allocators; see advisory).
571 const byte BYTES[] = {0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0};
572
573 auto pipe = kj::newOneWayPipe();
574 auto writePromise = pipe.out->write(BYTES, sizeof(BYTES));
575
576 KJ_EXPECT_THROW_MESSAGE("Message has too many segments.",
577 readMessage(*pipe.in).wait(ws));
578 }
579
580 } // namespace
581 } // namespace _ (private)
582 } // namespace capnp