1 /*
2 * nghttp2 - HTTP/2 C Library
3 *
4 * Copyright (c) 2014 Tatsuhiro Tsujikawa
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining
7 * a copy of this software and associated documentation files (the
8 * "Software"), to deal in the Software without restriction, including
9 * without limitation the rights to use, copy, modify, merge, publish,
10 * distribute, sublicense, and/or sell copies of the Software, and to
11 * permit persons to whom the Software is furnished to do so, subject to
12 * the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be
15 * included in all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
20 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
21 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
22 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
23 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 */
25 #ifndef MEMCHUNK_H
26 #define MEMCHUNK_H
27
28 #include "nghttp2_config.h"
29
30 #include <limits.h>
31 #ifdef _WIN32
32 /* Structure for scatter/gather I/O. */
33 struct iovec {
34 void *iov_base; /* Pointer to data. */
35 size_t iov_len; /* Length of data. */
36 };
37 #else // !_WIN32
38 # include <sys/uio.h>
39 #endif // !_WIN32
40
41 #include <cassert>
42 #include <cstring>
43 #include <memory>
44 #include <array>
45 #include <algorithm>
46 #include <string>
47 #include <utility>
48
49 #include "template.h"
50
51 namespace nghttp2 {
52
53 #define DEFAULT_WR_IOVCNT 16
54
55 #if defined(IOV_MAX) && IOV_MAX < DEFAULT_WR_IOVCNT
56 # define MAX_WR_IOVCNT IOV_MAX
57 #else // !defined(IOV_MAX) || IOV_MAX >= DEFAULT_WR_IOVCNT
58 # define MAX_WR_IOVCNT DEFAULT_WR_IOVCNT
59 #endif // !defined(IOV_MAX) || IOV_MAX >= DEFAULT_WR_IOVCNT
60
61 template <size_t N> struct Memchunk {
MemchunkMemchunk62 Memchunk(Memchunk *next_chunk)
63 : pos(std::begin(buf)), last(pos), knext(next_chunk), next(nullptr) {}
lenMemchunk64 size_t len() const { return last - pos; }
leftMemchunk65 size_t left() const { return std::end(buf) - last; }
resetMemchunk66 void reset() { pos = last = std::begin(buf); }
67 std::array<uint8_t, N> buf;
68 uint8_t *pos, *last;
69 Memchunk *knext;
70 Memchunk *next;
71 static const size_t size = N;
72 };
73
74 template <typename T> struct Pool {
PoolPool75 Pool() : pool(nullptr), freelist(nullptr), poolsize(0), freelistsize(0) {}
~PoolPool76 ~Pool() { clear(); }
getPool77 T *get() {
78 if (freelist) {
79 auto m = freelist;
80 freelist = freelist->next;
81 m->next = nullptr;
82 m->reset();
83 freelistsize -= T::size;
84 return m;
85 }
86
87 pool = new T{pool};
88 poolsize += T::size;
89 return pool;
90 }
recyclePool91 void recycle(T *m) {
92 m->next = freelist;
93 freelist = m;
94 freelistsize += T::size;
95 }
clearPool96 void clear() {
97 freelist = nullptr;
98 freelistsize = 0;
99 for (auto p = pool; p;) {
100 auto knext = p->knext;
101 delete p;
102 p = knext;
103 }
104 pool = nullptr;
105 poolsize = 0;
106 }
107 using value_type = T;
108 T *pool;
109 T *freelist;
110 size_t poolsize;
111 size_t freelistsize;
112 };
113
114 template <typename Memchunk> struct Memchunks {
MemchunksMemchunks115 Memchunks(Pool<Memchunk> *pool)
116 : pool(pool),
117 head(nullptr),
118 tail(nullptr),
119 len(0),
120 mark(nullptr),
121 mark_pos(nullptr),
122 mark_offset(0) {}
123 Memchunks(const Memchunks &) = delete;
MemchunksMemchunks124 Memchunks(Memchunks &&other) noexcept
125 : pool{other.pool}, // keep other.pool
126 head{std::exchange(other.head, nullptr)},
127 tail{std::exchange(other.tail, nullptr)},
128 len{std::exchange(other.len, 0)},
129 mark{std::exchange(other.mark, nullptr)},
130 mark_pos{std::exchange(other.mark_pos, nullptr)},
131 mark_offset{std::exchange(other.mark_offset, 0)} {}
132 Memchunks &operator=(const Memchunks &) = delete;
133 Memchunks &operator=(Memchunks &&other) noexcept {
134 if (this == &other) {
135 return *this;
136 }
137
138 reset();
139
140 pool = other.pool;
141 head = std::exchange(other.head, nullptr);
142 tail = std::exchange(other.tail, nullptr);
143 len = std::exchange(other.len, 0);
144 mark = std::exchange(other.mark, nullptr);
145 mark_pos = std::exchange(other.mark_pos, nullptr);
146 mark_offset = std::exchange(other.mark_offset, 0);
147
148 return *this;
149 }
~MemchunksMemchunks150 ~Memchunks() {
151 if (!pool) {
152 return;
153 }
154 for (auto m = head; m;) {
155 auto next = m->next;
156 pool->recycle(m);
157 m = next;
158 }
159 }
appendMemchunks160 size_t append(char c) {
161 if (!tail) {
162 head = tail = pool->get();
163 } else if (tail->left() == 0) {
164 tail->next = pool->get();
165 tail = tail->next;
166 }
167 *tail->last++ = c;
168 ++len;
169 return 1;
170 }
appendMemchunks171 size_t append(const void *src, size_t count) {
172 if (count == 0) {
173 return 0;
174 }
175
176 auto first = static_cast<const uint8_t *>(src);
177 auto last = first + count;
178
179 if (!tail) {
180 head = tail = pool->get();
181 }
182
183 for (;;) {
184 auto n = std::min(static_cast<size_t>(last - first), tail->left());
185 tail->last = std::copy_n(first, n, tail->last);
186 first += n;
187 len += n;
188 if (first == last) {
189 break;
190 }
191
192 tail->next = pool->get();
193 tail = tail->next;
194 }
195
196 return count;
197 }
appendMemchunks198 template <size_t N> size_t append(const char (&s)[N]) {
199 return append(s, N - 1);
200 }
appendMemchunks201 size_t append(const std::string &s) { return append(s.c_str(), s.size()); }
appendMemchunks202 size_t append(const StringRef &s) { return append(s.c_str(), s.size()); }
appendMemchunks203 size_t append(const ImmutableString &s) {
204 return append(s.c_str(), s.size());
205 }
copyMemchunks206 size_t copy(Memchunks &dest) {
207 auto m = head;
208 while (m) {
209 dest.append(m->pos, m->len());
210 m = m->next;
211 }
212 return len;
213 }
removeMemchunks214 size_t remove(void *dest, size_t count) {
215 assert(mark == nullptr);
216
217 if (!tail || count == 0) {
218 return 0;
219 }
220
221 auto first = static_cast<uint8_t *>(dest);
222 auto last = first + count;
223
224 auto m = head;
225
226 while (m) {
227 auto next = m->next;
228 auto n = std::min(static_cast<size_t>(last - first), m->len());
229
230 assert(m->len());
231 first = std::copy_n(m->pos, n, first);
232 m->pos += n;
233 len -= n;
234 if (m->len() > 0) {
235 break;
236 }
237 pool->recycle(m);
238 m = next;
239 }
240 head = m;
241 if (head == nullptr) {
242 tail = nullptr;
243 }
244
245 return first - static_cast<uint8_t *>(dest);
246 }
removeMemchunks247 size_t remove(Memchunks &dest, size_t count) {
248 assert(mark == nullptr);
249
250 if (!tail || count == 0) {
251 return 0;
252 }
253
254 auto left = count;
255 auto m = head;
256
257 while (m) {
258 auto next = m->next;
259 auto n = std::min(left, m->len());
260
261 assert(m->len());
262 dest.append(m->pos, n);
263 m->pos += n;
264 len -= n;
265 left -= n;
266 if (m->len() > 0) {
267 break;
268 }
269 pool->recycle(m);
270 m = next;
271 }
272 head = m;
273 if (head == nullptr) {
274 tail = nullptr;
275 }
276
277 return count - left;
278 }
removeMemchunks279 size_t remove(Memchunks &dest) {
280 assert(pool == dest.pool);
281 assert(mark == nullptr);
282
283 if (head == nullptr) {
284 return 0;
285 }
286
287 auto n = len;
288
289 if (dest.tail == nullptr) {
290 dest.head = head;
291 } else {
292 dest.tail->next = head;
293 }
294
295 dest.tail = tail;
296 dest.len += len;
297
298 head = tail = nullptr;
299 len = 0;
300
301 return n;
302 }
drainMemchunks303 size_t drain(size_t count) {
304 assert(mark == nullptr);
305
306 auto ndata = count;
307 auto m = head;
308 while (m) {
309 auto next = m->next;
310 auto n = std::min(count, m->len());
311 m->pos += n;
312 count -= n;
313 len -= n;
314 if (m->len() > 0) {
315 break;
316 }
317
318 pool->recycle(m);
319 m = next;
320 }
321 head = m;
322 if (head == nullptr) {
323 tail = nullptr;
324 }
325 return ndata - count;
326 }
drain_markMemchunks327 size_t drain_mark(size_t count) {
328 auto ndata = count;
329 auto m = head;
330 while (m) {
331 auto next = m->next;
332 auto n = std::min(count, m->len());
333 m->pos += n;
334 count -= n;
335 len -= n;
336 mark_offset -= n;
337
338 if (m->len() > 0) {
339 assert(mark != m || m->pos <= mark_pos);
340 break;
341 }
342 if (mark == m) {
343 assert(m->pos <= mark_pos);
344
345 mark = nullptr;
346 mark_pos = nullptr;
347 mark_offset = 0;
348 }
349
350 pool->recycle(m);
351 m = next;
352 }
353 head = m;
354 if (head == nullptr) {
355 tail = nullptr;
356 }
357 return ndata - count;
358 }
riovecMemchunks359 int riovec(struct iovec *iov, int iovcnt) const {
360 if (!head) {
361 return 0;
362 }
363 auto m = head;
364 int i;
365 for (i = 0; i < iovcnt && m; ++i, m = m->next) {
366 iov[i].iov_base = m->pos;
367 iov[i].iov_len = m->len();
368 }
369 return i;
370 }
riovec_markMemchunks371 int riovec_mark(struct iovec *iov, int iovcnt) {
372 if (!head || iovcnt == 0) {
373 return 0;
374 }
375
376 int i = 0;
377 Memchunk *m;
378 if (mark) {
379 if (mark_pos != mark->last) {
380 iov[0].iov_base = mark_pos;
381 iov[0].iov_len = mark->len() - (mark_pos - mark->pos);
382
383 mark_pos = mark->last;
384 mark_offset += iov[0].iov_len;
385 i = 1;
386 }
387 m = mark->next;
388 } else {
389 i = 0;
390 m = head;
391 }
392
393 for (; i < iovcnt && m; ++i, m = m->next) {
394 iov[i].iov_base = m->pos;
395 iov[i].iov_len = m->len();
396
397 mark = m;
398 mark_pos = m->last;
399 mark_offset += m->len();
400 }
401
402 return i;
403 }
rleftMemchunks404 size_t rleft() const { return len; }
rleft_markMemchunks405 size_t rleft_mark() const { return len - mark_offset; }
resetMemchunks406 void reset() {
407 for (auto m = head; m;) {
408 auto next = m->next;
409 pool->recycle(m);
410 m = next;
411 }
412 len = 0;
413 head = tail = mark = nullptr;
414 mark_pos = nullptr;
415 mark_offset = 0;
416 }
417
418 Pool<Memchunk> *pool;
419 Memchunk *head, *tail;
420 size_t len;
421 Memchunk *mark;
422 uint8_t *mark_pos;
423 size_t mark_offset;
424 };
425
426 // Wrapper around Memchunks to offer "peeking" functionality.
427 template <typename Memchunk> struct PeekMemchunks {
PeekMemchunksPeekMemchunks428 PeekMemchunks(Pool<Memchunk> *pool)
429 : memchunks(pool),
430 cur(nullptr),
431 cur_pos(nullptr),
432 cur_last(nullptr),
433 len(0),
434 peeking(true) {}
435 PeekMemchunks(const PeekMemchunks &) = delete;
PeekMemchunksPeekMemchunks436 PeekMemchunks(PeekMemchunks &&other) noexcept
437 : memchunks{std::move(other.memchunks)},
438 cur{std::exchange(other.cur, nullptr)},
439 cur_pos{std::exchange(other.cur_pos, nullptr)},
440 cur_last{std::exchange(other.cur_last, nullptr)},
441 len{std::exchange(other.len, 0)},
442 peeking{std::exchange(other.peeking, true)} {}
443 PeekMemchunks &operator=(const PeekMemchunks &) = delete;
444 PeekMemchunks &operator=(PeekMemchunks &&other) noexcept {
445 if (this == &other) {
446 return *this;
447 }
448
449 memchunks = std::move(other.memchunks);
450 cur = std::exchange(other.cur, nullptr);
451 cur_pos = std::exchange(other.cur_pos, nullptr);
452 cur_last = std::exchange(other.cur_last, nullptr);
453 len = std::exchange(other.len, 0);
454 peeking = std::exchange(other.peeking, true);
455
456 return *this;
457 }
appendPeekMemchunks458 size_t append(const void *src, size_t count) {
459 count = memchunks.append(src, count);
460 len += count;
461 return count;
462 }
removePeekMemchunks463 size_t remove(void *dest, size_t count) {
464 if (!peeking) {
465 count = memchunks.remove(dest, count);
466 len -= count;
467 return count;
468 }
469
470 if (count == 0 || len == 0) {
471 return 0;
472 }
473
474 if (!cur) {
475 cur = memchunks.head;
476 cur_pos = cur->pos;
477 }
478
479 // cur_last could be updated in append
480 cur_last = cur->last;
481
482 if (cur_pos == cur_last) {
483 assert(cur->next);
484 cur = cur->next;
485 }
486
487 auto first = static_cast<uint8_t *>(dest);
488 auto last = first + count;
489
490 for (;;) {
491 auto n = std::min(last - first, cur_last - cur_pos);
492
493 first = std::copy_n(cur_pos, n, first);
494 cur_pos += n;
495 len -= n;
496
497 if (first == last) {
498 break;
499 }
500 assert(cur_pos == cur_last);
501 if (!cur->next) {
502 break;
503 }
504 cur = cur->next;
505 cur_pos = cur->pos;
506 cur_last = cur->last;
507 }
508 return first - static_cast<uint8_t *>(dest);
509 }
rleftPeekMemchunks510 size_t rleft() const { return len; }
rleft_bufferedPeekMemchunks511 size_t rleft_buffered() const { return memchunks.rleft(); }
disable_peekPeekMemchunks512 void disable_peek(bool drain) {
513 if (!peeking) {
514 return;
515 }
516 if (drain) {
517 auto n = rleft_buffered() - rleft();
518 memchunks.drain(n);
519 assert(len == memchunks.rleft());
520 } else {
521 len = memchunks.rleft();
522 }
523 cur = nullptr;
524 cur_pos = cur_last = nullptr;
525 peeking = false;
526 }
resetPeekMemchunks527 void reset() {
528 memchunks.reset();
529 cur = nullptr;
530 cur_pos = cur_last = nullptr;
531 len = 0;
532 peeking = true;
533 }
534 Memchunks<Memchunk> memchunks;
535 // Pointer to the Memchunk currently we are reading/writing.
536 Memchunk *cur;
537 // Region inside cur, we have processed to cur_pos.
538 uint8_t *cur_pos, *cur_last;
539 // This is the length we have left unprocessed. len <=
540 // memchunk.rleft() must hold.
541 size_t len;
542 // true if peeking is enabled. Initially it is true.
543 bool peeking;
544 };
545
546 using Memchunk16K = Memchunk<16_k>;
547 using MemchunkPool = Pool<Memchunk16K>;
548 using DefaultMemchunks = Memchunks<Memchunk16K>;
549 using DefaultPeekMemchunks = PeekMemchunks<Memchunk16K>;
550
limit_iovec(struct iovec * iov,int iovcnt,size_t max)551 inline int limit_iovec(struct iovec *iov, int iovcnt, size_t max) {
552 if (max == 0) {
553 return 0;
554 }
555 for (int i = 0; i < iovcnt; ++i) {
556 auto d = std::min(max, iov[i].iov_len);
557 iov[i].iov_len = d;
558 max -= d;
559 if (max == 0) {
560 return i + 1;
561 }
562 }
563 return iovcnt;
564 }
565
566 // MemchunkBuffer is similar to Buffer, but it uses pooled Memchunk
567 // for its underlying buffer.
568 template <typename Memchunk> struct MemchunkBuffer {
MemchunkBufferMemchunkBuffer569 MemchunkBuffer(Pool<Memchunk> *pool) : pool(pool), chunk(nullptr) {}
570 MemchunkBuffer(const MemchunkBuffer &) = delete;
MemchunkBufferMemchunkBuffer571 MemchunkBuffer(MemchunkBuffer &&other) noexcept
572 : pool(other.pool), chunk(other.chunk) {
573 other.chunk = nullptr;
574 }
575 MemchunkBuffer &operator=(const MemchunkBuffer &) = delete;
576 MemchunkBuffer &operator=(MemchunkBuffer &&other) noexcept {
577 if (this == &other) {
578 return *this;
579 }
580
581 pool = other.pool;
582 chunk = other.chunk;
583
584 other.chunk = nullptr;
585
586 return *this;
587 }
588
~MemchunkBufferMemchunkBuffer589 ~MemchunkBuffer() {
590 if (!pool || !chunk) {
591 return;
592 }
593 pool->recycle(chunk);
594 }
595
596 // Ensures that the underlying buffer is allocated.
ensure_chunkMemchunkBuffer597 void ensure_chunk() {
598 if (chunk) {
599 return;
600 }
601 chunk = pool->get();
602 }
603
604 // Releases the underlying buffer.
release_chunkMemchunkBuffer605 void release_chunk() {
606 if (!chunk) {
607 return;
608 }
609 pool->recycle(chunk);
610 chunk = nullptr;
611 }
612
613 // Returns true if the underlying buffer is allocated.
chunk_availMemchunkBuffer614 bool chunk_avail() const { return chunk != nullptr; }
615
616 // The functions below must be called after the underlying buffer is
617 // allocated (use ensure_chunk).
618
619 // MemchunkBuffer provides the same interface functions with Buffer.
620 // Since we has chunk as a member variable, pos and last are
621 // implemented as wrapper functions.
622
posMemchunkBuffer623 uint8_t *pos() const { return chunk->pos; }
lastMemchunkBuffer624 uint8_t *last() const { return chunk->last; }
625
rleftMemchunkBuffer626 size_t rleft() const { return chunk->len(); }
wleftMemchunkBuffer627 size_t wleft() const { return chunk->left(); }
writeMemchunkBuffer628 size_t write(const void *src, size_t count) {
629 count = std::min(count, wleft());
630 auto p = static_cast<const uint8_t *>(src);
631 chunk->last = std::copy_n(p, count, chunk->last);
632 return count;
633 }
writeMemchunkBuffer634 size_t write(size_t count) {
635 count = std::min(count, wleft());
636 chunk->last += count;
637 return count;
638 }
drainMemchunkBuffer639 size_t drain(size_t count) {
640 count = std::min(count, rleft());
641 chunk->pos += count;
642 return count;
643 }
drain_resetMemchunkBuffer644 size_t drain_reset(size_t count) {
645 count = std::min(count, rleft());
646 std::copy(chunk->pos + count, chunk->last, std::begin(chunk->buf));
647 chunk->last = std::begin(chunk->buf) + (chunk->last - (chunk->pos + count));
648 chunk->pos = std::begin(chunk->buf);
649 return count;
650 }
resetMemchunkBuffer651 void reset() { chunk->reset(); }
beginMemchunkBuffer652 uint8_t *begin() { return std::begin(chunk->buf); }
653 uint8_t &operator[](size_t n) { return chunk->buf[n]; }
654 const uint8_t &operator[](size_t n) const { return chunk->buf[n]; }
655
656 Pool<Memchunk> *pool;
657 Memchunk *chunk;
658 };
659
660 using DefaultMemchunkBuffer = MemchunkBuffer<Memchunk16K>;
661
662 } // namespace nghttp2
663
664 #endif // MEMCHUNK_H
665