Imported Upstream version 1.46.0
[platform/upstream/nghttp2.git] / src / util.h
1 /*
2  * nghttp2 - HTTP/2 C Library
3  *
4  * Copyright (c) 2012 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 UTIL_H
26 #define UTIL_H
27
28 #include "nghttp2_config.h"
29
30 #ifdef HAVE_UNISTD_H
31 #  include <unistd.h>
32 #endif // HAVE_UNISTD_H
33 #include <getopt.h>
34 #ifdef HAVE_NETDB_H
35 #  include <netdb.h>
36 #endif // HAVE_NETDB_H
37
38 #include <cmath>
39 #include <cstring>
40 #include <cassert>
41 #include <vector>
42 #include <string>
43 #include <algorithm>
44 #include <sstream>
45 #include <memory>
46 #include <chrono>
47 #include <map>
48 #include <random>
49
50 #include "url-parser/url_parser.h"
51
52 #include "template.h"
53 #include "network.h"
54 #include "allocator.h"
55
56 namespace nghttp2 {
57
58 constexpr auto NGHTTP2_H2_ALPN = StringRef::from_lit("\x2h2");
59 constexpr auto NGHTTP2_H2 = StringRef::from_lit("h2");
60
61 // The additional HTTP/2 protocol ALPN protocol identifier we also
62 // supports for our applications to make smooth migration into final
63 // h2 ALPN ID.
64 constexpr auto NGHTTP2_H2_16_ALPN = StringRef::from_lit("\x5h2-16");
65 constexpr auto NGHTTP2_H2_16 = StringRef::from_lit("h2-16");
66
67 constexpr auto NGHTTP2_H2_14_ALPN = StringRef::from_lit("\x5h2-14");
68 constexpr auto NGHTTP2_H2_14 = StringRef::from_lit("h2-14");
69
70 constexpr auto NGHTTP2_H1_1_ALPN = StringRef::from_lit("\x8http/1.1");
71 constexpr auto NGHTTP2_H1_1 = StringRef::from_lit("http/1.1");
72
73 constexpr size_t NGHTTP2_MAX_UINT64_DIGITS = str_size("18446744073709551615");
74
75 namespace util {
76
77 extern const char UPPER_XDIGITS[];
78
79 inline bool is_alpha(const char c) {
80   return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z');
81 }
82
83 inline bool is_digit(const char c) { return '0' <= c && c <= '9'; }
84
85 inline bool is_hex_digit(const char c) {
86   return is_digit(c) || ('A' <= c && c <= 'F') || ('a' <= c && c <= 'f');
87 }
88
89 // Returns true if |s| is hex string.
90 bool is_hex_string(const StringRef &s);
91
92 bool in_rfc3986_unreserved_chars(const char c);
93
94 bool in_rfc3986_sub_delims(const char c);
95
96 // Returns true if |c| is in token (HTTP-p1, Section 3.2.6)
97 bool in_token(char c);
98
99 bool in_attr_char(char c);
100
101 // Returns integer corresponding to hex notation |c|.  If
102 // is_hex_digit(c) is false, it returns 256.
103 uint32_t hex_to_uint(char c);
104
105 std::string percent_encode(const unsigned char *target, size_t len);
106
107 std::string percent_encode(const std::string &target);
108
109 // percent-encode path component of URI |s|.
110 std::string percent_encode_path(const std::string &s);
111
112 template <typename InputIt>
113 std::string percent_decode(InputIt first, InputIt last) {
114   std::string result;
115   result.resize(last - first);
116   auto p = std::begin(result);
117   for (; first != last; ++first) {
118     if (*first != '%') {
119       *p++ = *first;
120       continue;
121     }
122
123     if (first + 1 != last && first + 2 != last && is_hex_digit(*(first + 1)) &&
124         is_hex_digit(*(first + 2))) {
125       *p++ = (hex_to_uint(*(first + 1)) << 4) + hex_to_uint(*(first + 2));
126       first += 2;
127       continue;
128     }
129
130     *p++ = *first;
131   }
132   result.resize(p - std::begin(result));
133   return result;
134 }
135
136 StringRef percent_decode(BlockAllocator &balloc, const StringRef &src);
137
138 // Percent encode |target| if character is not in token or '%'.
139 StringRef percent_encode_token(BlockAllocator &balloc, const StringRef &target);
140
141 template <typename OutputIt>
142 OutputIt percent_encode_token(OutputIt it, const StringRef &target) {
143   for (auto first = std::begin(target); first != std::end(target); ++first) {
144     uint8_t c = *first;
145
146     if (c != '%' && in_token(c)) {
147       *it++ = c;
148       continue;
149     }
150
151     *it++ = '%';
152     *it++ = UPPER_XDIGITS[c >> 4];
153     *it++ = UPPER_XDIGITS[(c & 0x0f)];
154   }
155
156   return it;
157 }
158
159 // Returns the number of bytes written by percent_encode_token with
160 // the same |target| parameter.  The return value does not include a
161 // terminal NUL byte.
162 size_t percent_encode_tokenlen(const StringRef &target);
163
164 // Returns quotedString version of |target|.  Currently, this function
165 // just replace '"' with '\"'.
166 StringRef quote_string(BlockAllocator &balloc, const StringRef &target);
167
168 template <typename OutputIt>
169 OutputIt quote_string(OutputIt it, const StringRef &target) {
170   for (auto c : target) {
171     if (c == '"') {
172       *it++ = '\\';
173       *it++ = '"';
174     } else {
175       *it++ = c;
176     }
177   }
178
179   return it;
180 }
181
182 // Returns the number of bytes written by quote_string with the same
183 // |target| parameter.  The return value does not include a terminal
184 // NUL byte.
185 size_t quote_stringlen(const StringRef &target);
186
187 std::string format_hex(const unsigned char *s, size_t len);
188
189 template <size_t N> std::string format_hex(const unsigned char (&s)[N]) {
190   return format_hex(s, N);
191 }
192
193 template <size_t N> std::string format_hex(const std::array<uint8_t, N> &s) {
194   return format_hex(s.data(), s.size());
195 }
196
197 StringRef format_hex(BlockAllocator &balloc, const StringRef &s);
198
199 static constexpr char LOWER_XDIGITS[] = "0123456789abcdef";
200
201 template <typename OutputIt>
202 OutputIt format_hex(OutputIt it, const StringRef &s) {
203   for (auto cc : s) {
204     uint8_t c = cc;
205     *it++ = LOWER_XDIGITS[c >> 4];
206     *it++ = LOWER_XDIGITS[c & 0xf];
207   }
208
209   return it;
210 }
211
212 // decode_hex decodes hex string |s|, returns the decoded byte string.
213 // This function assumes |s| is hex string, that is is_hex_string(s)
214 // == true.
215 StringRef decode_hex(BlockAllocator &balloc, const StringRef &s);
216
217 template <typename OutputIt>
218 OutputIt decode_hex(OutputIt d_first, const StringRef &s) {
219   for (auto it = std::begin(s); it != std::end(s); it += 2) {
220     *d_first++ = (hex_to_uint(*it) << 4) | hex_to_uint(*(it + 1));
221   }
222
223   return d_first;
224 }
225
226 // Returns given time |t| from epoch in HTTP Date format (e.g., Mon,
227 // 10 Oct 2016 10:25:58 GMT).
228 std::string http_date(time_t t);
229 // Writes given time |t| from epoch in HTTP Date format into the
230 // buffer pointed by |res|.  The buffer must be at least 29 bytes
231 // long.  This function returns the one beyond the last position.
232 char *http_date(char *res, time_t t);
233
234 // Returns given time |t| from epoch in Common Log format (e.g.,
235 // 03/Jul/2014:00:19:38 +0900)
236 std::string common_log_date(time_t t);
237 // Writes given time |t| from epoch in Common Log format into the
238 // buffer pointed by |res|.  The buffer must be at least 26 bytes
239 // long.  This function returns the one beyond the last position.
240 char *common_log_date(char *res, time_t t);
241
242 // Returns given millisecond |ms| from epoch in ISO 8601 format (e.g.,
243 // 2014-11-15T12:58:24.741Z or 2014-11-15T12:58:24.741+09:00)
244 std::string iso8601_date(int64_t ms);
245 // Writes given time |t| from epoch in ISO 8601 format into the buffer
246 // pointed by |res|.  The buffer must be at least 29 bytes long.  This
247 // function returns the one beyond the last position.
248 char *iso8601_date(char *res, int64_t ms);
249
250 // Writes given time |t| from epoch in ISO 8601 basic format into the
251 // buffer pointed by |res|.  The buffer must be at least 24 bytes
252 // long.  This function returns the one beyond the last position.
253 char *iso8601_basic_date(char *res, int64_t ms);
254
255 time_t parse_http_date(const StringRef &s);
256
257 // Parses time formatted as "MMM DD HH:MM:SS YYYY [GMT]" (e.g., Feb 3
258 // 00:55:52 2015 GMT), which is specifically used by OpenSSL
259 // ASN1_TIME_print().
260 time_t parse_openssl_asn1_time_print(const StringRef &s);
261
262 char upcase(char c);
263
264 inline char lowcase(char c) {
265   constexpr static unsigned char tbl[] = {
266       0,   1,   2,   3,   4,   5,   6,   7,   8,   9,   10,  11,  12,  13,  14,
267       15,  16,  17,  18,  19,  20,  21,  22,  23,  24,  25,  26,  27,  28,  29,
268       30,  31,  32,  33,  34,  35,  36,  37,  38,  39,  40,  41,  42,  43,  44,
269       45,  46,  47,  48,  49,  50,  51,  52,  53,  54,  55,  56,  57,  58,  59,
270       60,  61,  62,  63,  64,  'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j',
271       'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y',
272       'z', 91,  92,  93,  94,  95,  96,  97,  98,  99,  100, 101, 102, 103, 104,
273       105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119,
274       120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134,
275       135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
276       150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164,
277       165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179,
278       180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194,
279       195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209,
280       210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224,
281       225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
282       240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254,
283       255,
284   };
285   return tbl[static_cast<unsigned char>(c)];
286 }
287
288 template <typename InputIterator1, typename InputIterator2>
289 bool starts_with(InputIterator1 first1, InputIterator1 last1,
290                  InputIterator2 first2, InputIterator2 last2) {
291   if (last1 - first1 < last2 - first2) {
292     return false;
293   }
294   return std::equal(first2, last2, first1);
295 }
296
297 template <typename S, typename T> bool starts_with(const S &a, const T &b) {
298   return starts_with(a.begin(), a.end(), b.begin(), b.end());
299 }
300
301 struct CaseCmp {
302   bool operator()(char lhs, char rhs) const {
303     return lowcase(lhs) == lowcase(rhs);
304   }
305 };
306
307 template <typename InputIterator1, typename InputIterator2>
308 bool istarts_with(InputIterator1 first1, InputIterator1 last1,
309                   InputIterator2 first2, InputIterator2 last2) {
310   if (last1 - first1 < last2 - first2) {
311     return false;
312   }
313   return std::equal(first2, last2, first1, CaseCmp());
314 }
315
316 template <typename S, typename T> bool istarts_with(const S &a, const T &b) {
317   return istarts_with(a.begin(), a.end(), b.begin(), b.end());
318 }
319
320 template <typename T, typename CharT, size_t N>
321 bool istarts_with_l(const T &a, const CharT (&b)[N]) {
322   return istarts_with(a.begin(), a.end(), b, b + N - 1);
323 }
324
325 template <typename InputIterator1, typename InputIterator2>
326 bool ends_with(InputIterator1 first1, InputIterator1 last1,
327                InputIterator2 first2, InputIterator2 last2) {
328   if (last1 - first1 < last2 - first2) {
329     return false;
330   }
331   return std::equal(first2, last2, last1 - (last2 - first2));
332 }
333
334 template <typename T, typename S> bool ends_with(const T &a, const S &b) {
335   return ends_with(a.begin(), a.end(), b.begin(), b.end());
336 }
337
338 template <typename T, typename CharT, size_t N>
339 bool ends_with_l(const T &a, const CharT (&b)[N]) {
340   return ends_with(a.begin(), a.end(), b, b + N - 1);
341 }
342
343 template <typename InputIterator1, typename InputIterator2>
344 bool iends_with(InputIterator1 first1, InputIterator1 last1,
345                 InputIterator2 first2, InputIterator2 last2) {
346   if (last1 - first1 < last2 - first2) {
347     return false;
348   }
349   return std::equal(first2, last2, last1 - (last2 - first2), CaseCmp());
350 }
351
352 template <typename T, typename S> bool iends_with(const T &a, const S &b) {
353   return iends_with(a.begin(), a.end(), b.begin(), b.end());
354 }
355
356 template <typename T, typename CharT, size_t N>
357 bool iends_with_l(const T &a, const CharT (&b)[N]) {
358   return iends_with(a.begin(), a.end(), b, b + N - 1);
359 }
360
361 template <typename InputIt1, typename InputIt2>
362 bool strieq(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2) {
363   if (std::distance(first1, last1) != std::distance(first2, last2)) {
364     return false;
365   }
366
367   return std::equal(first1, last1, first2, CaseCmp());
368 }
369
370 template <typename T, typename S> bool strieq(const T &a, const S &b) {
371   return strieq(a.begin(), a.end(), b.begin(), b.end());
372 }
373
374 template <typename CharT, typename InputIt, size_t N>
375 bool strieq_l(const CharT (&a)[N], InputIt b, size_t blen) {
376   return strieq(a, a + (N - 1), b, b + blen);
377 }
378
379 template <typename CharT, size_t N, typename T>
380 bool strieq_l(const CharT (&a)[N], const T &b) {
381   return strieq(a, a + (N - 1), b.begin(), b.end());
382 }
383
384 template <typename InputIt1, typename InputIt2>
385 bool streq(InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2) {
386   if (std::distance(first1, last1) != std::distance(first2, last2)) {
387     return false;
388   }
389   return std::equal(first1, last1, first2);
390 }
391
392 template <typename T, typename S> bool streq(const T &a, const S &b) {
393   return streq(a.begin(), a.end(), b.begin(), b.end());
394 }
395
396 template <typename CharT, typename InputIt, size_t N>
397 bool streq_l(const CharT (&a)[N], InputIt b, size_t blen) {
398   return streq(a, a + (N - 1), b, b + blen);
399 }
400
401 template <typename CharT, size_t N, typename T>
402 bool streq_l(const CharT (&a)[N], const T &b) {
403   return streq(a, a + (N - 1), b.begin(), b.end());
404 }
405
406 // Returns true if |a| contains |b|.  If both |a| and |b| are empty,
407 // this function returns false.
408 template <typename S, typename T> bool strifind(const S &a, const T &b) {
409   return std::search(a.begin(), a.end(), b.begin(), b.end(), CaseCmp()) !=
410          a.end();
411 }
412
413 template <typename InputIt> void inp_strlower(InputIt first, InputIt last) {
414   std::transform(first, last, first, lowcase);
415 }
416
417 // Lowercase |s| in place.
418 inline void inp_strlower(std::string &s) {
419   inp_strlower(std::begin(s), std::end(s));
420 }
421
422 // Returns string representation of |n| with 2 fractional digits.
423 std::string dtos(double n);
424
425 template <typename T> std::string utos(T n) {
426   std::string res;
427   if (n == 0) {
428     res = "0";
429     return res;
430   }
431   size_t nlen = 0;
432   for (auto t = n; t; t /= 10, ++nlen)
433     ;
434   res.resize(nlen);
435   for (; n; n /= 10) {
436     res[--nlen] = (n % 10) + '0';
437   }
438   return res;
439 }
440
441 template <typename T, typename OutputIt> OutputIt utos(OutputIt dst, T n) {
442   if (n == 0) {
443     *dst++ = '0';
444     return dst;
445   }
446   size_t nlen = 0;
447   for (auto t = n; t; t /= 10, ++nlen)
448     ;
449   auto p = dst + nlen;
450   auto res = p;
451   for (; n; n /= 10) {
452     *--p = (n % 10) + '0';
453   }
454   return res;
455 }
456
457 template <typename T>
458 StringRef make_string_ref_uint(BlockAllocator &balloc, T n) {
459   auto iov = make_byte_ref(balloc, NGHTTP2_MAX_UINT64_DIGITS + 1);
460   auto p = iov.base;
461   p = util::utos(p, n);
462   *p = '\0';
463   return StringRef{iov.base, p};
464 }
465
466 template <typename T> std::string utos_unit(T n) {
467   char u = 0;
468   if (n >= (1 << 30)) {
469     u = 'G';
470     n /= (1 << 30);
471   } else if (n >= (1 << 20)) {
472     u = 'M';
473     n /= (1 << 20);
474   } else if (n >= (1 << 10)) {
475     u = 'K';
476     n /= (1 << 10);
477   }
478   if (u == 0) {
479     return utos(n);
480   }
481   return utos(n) + u;
482 }
483
484 // Like utos_unit(), but 2 digits fraction part is followed.
485 template <typename T> std::string utos_funit(T n) {
486   char u = 0;
487   int b = 0;
488   if (n >= (1 << 30)) {
489     u = 'G';
490     b = 30;
491   } else if (n >= (1 << 20)) {
492     u = 'M';
493     b = 20;
494   } else if (n >= (1 << 10)) {
495     u = 'K';
496     b = 10;
497   }
498   if (b == 0) {
499     return utos(n);
500   }
501   return dtos(static_cast<double>(n) / (1 << b)) + u;
502 }
503
504 template <typename T> std::string utox(T n) {
505   std::string res;
506   if (n == 0) {
507     res = "0";
508     return res;
509   }
510   int i = 0;
511   T t = n;
512   for (; t; t /= 16, ++i)
513     ;
514   res.resize(i);
515   --i;
516   for (; n; --i, n /= 16) {
517     res[i] = UPPER_XDIGITS[(n & 0x0f)];
518   }
519   return res;
520 }
521
522 void to_token68(std::string &base64str);
523
524 StringRef to_base64(BlockAllocator &balloc, const StringRef &token68str);
525
526 void show_candidates(const char *unkopt, const option *options);
527
528 bool has_uri_field(const http_parser_url &u, http_parser_url_fields field);
529
530 bool fieldeq(const char *uri1, const http_parser_url &u1, const char *uri2,
531              const http_parser_url &u2, http_parser_url_fields field);
532
533 bool fieldeq(const char *uri, const http_parser_url &u,
534              http_parser_url_fields field, const char *t);
535
536 bool fieldeq(const char *uri, const http_parser_url &u,
537              http_parser_url_fields field, const StringRef &t);
538
539 StringRef get_uri_field(const char *uri, const http_parser_url &u,
540                         http_parser_url_fields field);
541
542 uint16_t get_default_port(const char *uri, const http_parser_url &u);
543
544 bool porteq(const char *uri1, const http_parser_url &u1, const char *uri2,
545             const http_parser_url &u2);
546
547 void write_uri_field(std::ostream &o, const char *uri, const http_parser_url &u,
548                      http_parser_url_fields field);
549
550 bool numeric_host(const char *hostname);
551
552 bool numeric_host(const char *hostname, int family);
553
554 // Returns numeric address string of |addr|.  If getnameinfo() is
555 // failed, "unknown" is returned.
556 std::string numeric_name(const struct sockaddr *sa, socklen_t salen);
557
558 // Returns string representation of numeric address and port of
559 // |addr|.  If address family is AF_UNIX, this return path to UNIX
560 // domain socket.  Otherwise, the format is like <HOST>:<PORT>.  For
561 // IPv6 address, address is enclosed by square brackets ([]).
562 std::string to_numeric_addr(const Address *addr);
563
564 std::string to_numeric_addr(const struct sockaddr *sa, socklen_t salen);
565
566 // Sets |port| to |addr|.
567 void set_port(Address &addr, uint16_t port);
568
569 // Returns ASCII dump of |data| of length |len|.  Only ASCII printable
570 // characters are preserved.  Other characters are replaced with ".".
571 std::string ascii_dump(const uint8_t *data, size_t len);
572
573 // Returns absolute path of executable path.  If argc == 0 or |cwd| is
574 // nullptr, this function returns nullptr.  If argv[0] starts with
575 // '/', this function returns argv[0].  Oterwise return cwd + "/" +
576 // argv[0].  If non-null is returned, it is NULL-terminated string and
577 // dynamically allocated by malloc.  The caller is responsible to free
578 // it.
579 char *get_exec_path(int argc, char **const argv, const char *cwd);
580
581 // Validates path so that it does not contain directory traversal
582 // vector.  Returns true if path is safe.  The |path| must start with
583 // "/" otherwise returns false.  This function should be called after
584 // percent-decode was performed.
585 bool check_path(const std::string &path);
586
587 // Returns the |tv| value as 64 bit integer using a microsecond as an
588 // unit.
589 int64_t to_time64(const timeval &tv);
590
591 // Returns true if ALPN ID |proto| is supported HTTP/2 protocol
592 // identifier.
593 bool check_h2_is_selected(const StringRef &proto);
594
595 // Selects h2 protocol ALPN ID if one of supported h2 versions are
596 // present in |in| of length inlen.  Returns true if h2 version is
597 // selected.
598 bool select_h2(const unsigned char **out, unsigned char *outlen,
599                const unsigned char *in, unsigned int inlen);
600
601 // Selects protocol ALPN ID if one of identifiers contained in |protolist| is
602 // present in |in| of length inlen.  Returns true if identifier is
603 // selected.
604 bool select_protocol(const unsigned char **out, unsigned char *outlen,
605                      const unsigned char *in, unsigned int inlen,
606                      std::vector<std::string> proto_list);
607
608 // Returns default ALPN protocol list, which only contains supported
609 // HTTP/2 protocol identifier.
610 std::vector<unsigned char> get_default_alpn();
611
612 // Parses delimited strings in |s| and returns the array of substring,
613 // delimited by |delim|.  The any white spaces around substring are
614 // treated as a part of substring.
615 std::vector<std::string> parse_config_str_list(const StringRef &s,
616                                                char delim = ',');
617
618 // Parses delimited strings in |s| and returns Substrings in |s|
619 // delimited by |delim|.  The any white spaces around substring are
620 // treated as a part of substring.
621 std::vector<StringRef> split_str(const StringRef &s, char delim);
622
623 // Behaves like split_str, but this variant splits at most |n| - 1
624 // times and returns at most |n| sub-strings.  If |n| is zero, it
625 // falls back to split_str.
626 std::vector<StringRef> split_str(const StringRef &s, char delim, size_t n);
627
628 // Writes given time |tp| in Common Log format (e.g.,
629 // 03/Jul/2014:00:19:38 +0900) in buffer pointed by |out|.  The buffer
630 // must be at least 27 bytes, including terminal NULL byte.  Expected
631 // type of |tp| is std::chrono::time_point.  This function returns
632 // StringRef wrapping the buffer pointed by |out|, and this string is
633 // terminated by NULL.
634 template <typename T> StringRef format_common_log(char *out, const T &tp) {
635   auto t =
636       std::chrono::duration_cast<std::chrono::seconds>(tp.time_since_epoch());
637   auto p = common_log_date(out, t.count());
638   *p = '\0';
639   return StringRef{out, p};
640 }
641
642 // Returns given time |tp| in ISO 8601 format (e.g.,
643 // 2014-11-15T12:58:24.741Z or 2014-11-15T12:58:24.741+09:00).
644 // Expected type of |tp| is std::chrono::time_point
645 template <typename T> std::string format_iso8601(const T &tp) {
646   auto t = std::chrono::duration_cast<std::chrono::milliseconds>(
647       tp.time_since_epoch());
648   return iso8601_date(t.count());
649 }
650
651 // Writes given time |tp| in ISO 8601 format (e.g.,
652 // 2014-11-15T12:58:24.741Z or 2014-11-15T12:58:24.741+09:00) in
653 // buffer pointed by |out|.  The buffer must be at least 30 bytes,
654 // including terminal NULL byte.  Expected type of |tp| is
655 // std::chrono::time_point.  This function returns StringRef wrapping
656 // the buffer pointed by |out|, and this string is terminated by NULL.
657 template <typename T> StringRef format_iso8601(char *out, const T &tp) {
658   auto t = std::chrono::duration_cast<std::chrono::milliseconds>(
659       tp.time_since_epoch());
660   auto p = iso8601_date(out, t.count());
661   *p = '\0';
662   return StringRef{out, p};
663 }
664
665 // Writes given time |tp| in ISO 8601 basic format (e.g.,
666 // 20141115T125824.741Z or 20141115T125824.741+0900) in buffer pointed
667 // by |out|.  The buffer must be at least 25 bytes, including terminal
668 // NULL byte.  Expected type of |tp| is std::chrono::time_point.  This
669 // function returns StringRef wrapping the buffer pointed by |out|,
670 // and this string is terminated by NULL.
671 template <typename T> StringRef format_iso8601_basic(char *out, const T &tp) {
672   auto t = std::chrono::duration_cast<std::chrono::milliseconds>(
673       tp.time_since_epoch());
674   auto p = iso8601_basic_date(out, t.count());
675   *p = '\0';
676   return StringRef{out, p};
677 }
678
679 // Writes given time |tp| in HTTP Date format (e.g., Mon, 10 Oct 2016
680 // 10:25:58 GMT) in buffer pointed by |out|.  The buffer must be at
681 // least 30 bytes, including terminal NULL byte.  Expected type of
682 // |tp| is std::chrono::time_point.  This function returns StringRef
683 // wrapping the buffer pointed by |out|, and this string is terminated
684 // by NULL.
685 template <typename T> StringRef format_http_date(char *out, const T &tp) {
686   auto t =
687       std::chrono::duration_cast<std::chrono::seconds>(tp.time_since_epoch());
688   auto p = http_date(out, t.count());
689   *p = '\0';
690   return StringRef{out, p};
691 }
692
693 // Return the system precision of the template parameter |Clock| as
694 // a nanosecond value of type |Rep|
695 template <typename Clock, typename Rep> Rep clock_precision() {
696   std::chrono::duration<Rep, std::nano> duration = typename Clock::duration(1);
697
698   return duration.count();
699 }
700
701 int make_socket_closeonexec(int fd);
702 int make_socket_nonblocking(int fd);
703 int make_socket_nodelay(int fd);
704
705 int create_nonblock_socket(int family);
706 int create_nonblock_udp_socket(int family);
707
708 int bind_any_addr_udp(int fd, int family);
709
710 bool check_socket_connected(int fd);
711
712 // Returns the error code (errno) by inspecting SO_ERROR of given
713 // |fd|.  This function returns the error code if it succeeds, or -1.
714 // Returning 0 means no error.
715 int get_socket_error(int fd);
716
717 // Returns true if |host| is IPv6 numeric address (e.g., ::1)
718 bool ipv6_numeric_addr(const char *host);
719
720 // Parses NULL terminated string |s| as unsigned integer and returns
721 // the parsed integer.  Additionally, if |s| ends with 'k', 'm', 'g'
722 // and its upper case characters, multiply the integer by 1024, 1024 *
723 // 1024 and 1024 * 1024 respectively.  If there is an error, returns
724 // -1.
725 int64_t parse_uint_with_unit(const char *s);
726 // The following overload does not require |s| is NULL terminated.
727 int64_t parse_uint_with_unit(const uint8_t *s, size_t len);
728 int64_t parse_uint_with_unit(const StringRef &s);
729
730 // Parses NULL terminated string |s| as unsigned integer and returns
731 // the parsed integer.  If there is an error, returns -1.
732 int64_t parse_uint(const char *s);
733 // The following overload does not require |s| is NULL terminated.
734 int64_t parse_uint(const uint8_t *s, size_t len);
735 int64_t parse_uint(const std::string &s);
736 int64_t parse_uint(const StringRef &s);
737
738 // Parses NULL terminated string |s| as unsigned integer and returns
739 // the parsed integer casted to double.  If |s| ends with "s", the
740 // parsed value's unit is a second.  If |s| ends with "ms", the unit
741 // is millisecond.  Similarly, it also supports 'm' and 'h' for
742 // minutes and hours respectively.  If none of them are given, the
743 // unit is second.  This function returns
744 // std::numeric_limits<double>::infinity() if error occurs.
745 double parse_duration_with_unit(const char *s);
746 // The following overload does not require |s| is NULL terminated.
747 double parse_duration_with_unit(const uint8_t *s, size_t len);
748 double parse_duration_with_unit(const StringRef &s);
749
750 // Returns string representation of time duration |t|.  If t has
751 // fractional part (at least more than or equal to 1e-3), |t| is
752 // multiplied by 1000 and the unit "ms" is appended.  Otherwise, |t|
753 // is left as is and "s" is appended.
754 std::string duration_str(double t);
755
756 // Returns string representation of time duration |t|.  It appends
757 // unit after the formatting.  The available units are s, ms and us.
758 // The unit which is equal to or less than |t| is used and 2
759 // fractional digits follow.
760 std::string format_duration(const std::chrono::microseconds &u);
761
762 // Just like above, but this takes |t| as seconds.
763 std::string format_duration(double t);
764
765 // The maximum buffer size including terminal NULL to store the result
766 // of make_hostport.
767 constexpr size_t max_hostport = NI_MAXHOST + /* [] for IPv6 */ 2 + /* : */ 1 +
768                                 /* port */ 5 + /* terminal NULL */ 1;
769
770 // Just like make_http_hostport(), but doesn't treat 80 and 443
771 // specially.
772 StringRef make_hostport(BlockAllocator &balloc, const StringRef &host,
773                         uint16_t port);
774
775 template <typename OutputIt>
776 StringRef make_hostport(OutputIt first, const StringRef &host, uint16_t port) {
777   auto ipv6 = ipv6_numeric_addr(host.c_str());
778   auto serv = utos(port);
779   auto p = first;
780
781   if (ipv6) {
782     *p++ = '[';
783   }
784
785   p = std::copy(std::begin(host), std::end(host), p);
786
787   if (ipv6) {
788     *p++ = ']';
789   }
790
791   *p++ = ':';
792
793   p = std::copy(std::begin(serv), std::end(serv), p);
794
795   *p = '\0';
796
797   return StringRef{first, p};
798 }
799
800 // Creates "host:port" string using given |host| and |port|.  If
801 // |host| is numeric IPv6 address (e.g., ::1), it is enclosed by "["
802 // and "]".  If |port| is 80 or 443, port part is omitted.
803 StringRef make_http_hostport(BlockAllocator &balloc, const StringRef &host,
804                              uint16_t port);
805
806 template <typename OutputIt>
807 StringRef make_http_hostport(OutputIt first, const StringRef &host,
808                              uint16_t port) {
809   if (port != 80 && port != 443) {
810     return make_hostport(first, host, port);
811   }
812
813   auto ipv6 = ipv6_numeric_addr(host.c_str());
814   auto p = first;
815
816   if (ipv6) {
817     *p++ = '[';
818   }
819
820   p = std::copy(std::begin(host), std::end(host), p);
821
822   if (ipv6) {
823     *p++ = ']';
824   }
825
826   *p = '\0';
827
828   return StringRef{first, p};
829 }
830
831 // Dumps |src| of length |len| in the format similar to `hexdump -C`.
832 void hexdump(FILE *out, const uint8_t *src, size_t len);
833
834 // Copies 2 byte unsigned integer |n| in host byte order to |buf| in
835 // network byte order.
836 void put_uint16be(uint8_t *buf, uint16_t n);
837
838 // Copies 4 byte unsigned integer |n| in host byte order to |buf| in
839 // network byte order.
840 void put_uint32be(uint8_t *buf, uint32_t n);
841
842 // Retrieves 2 byte unsigned integer stored in |data| in network byte
843 // order and returns it in host byte order.
844 uint16_t get_uint16(const uint8_t *data);
845
846 // Retrieves 4 byte unsigned integer stored in |data| in network byte
847 // order and returns it in host byte order.
848 uint32_t get_uint32(const uint8_t *data);
849
850 // Retrieves 8 byte unsigned integer stored in |data| in network byte
851 // order and returns it in host byte order.
852 uint64_t get_uint64(const uint8_t *data);
853
854 // Reads mime types file (see /etc/mime.types), and stores extension
855 // -> MIME type map in |res|.  This function returns 0 if it succeeds,
856 // or -1.
857 int read_mime_types(std::map<std::string, std::string> &res,
858                     const char *filename);
859
860 // Fills random alpha and digit byte to the range [|first|, |last|).
861 // Returns the one beyond the |last|.
862 template <typename OutputIt, typename Generator>
863 OutputIt random_alpha_digit(OutputIt first, OutputIt last, Generator &gen) {
864   // If we use uint8_t instead char, gcc 6.2.0 complains by shouting
865   // char-array initialized from wide string.
866   static constexpr char s[] =
867       "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
868   std::uniform_int_distribution<> dis(0, 26 * 2 + 10 - 1);
869   for (; first != last; ++first) {
870     *first = s[dis(gen)];
871   }
872   return first;
873 }
874
875 // Fills random bytes to the range [|first|, |last|).
876 template <typename OutputIt, typename Generator>
877 void random_bytes(OutputIt first, OutputIt last, Generator &gen) {
878   std::uniform_int_distribution<> dis(0, 255);
879   std::generate(first, last, [&dis, &gen]() { return dis(gen); });
880 }
881
882 template <typename OutputIterator, typename CharT, size_t N>
883 OutputIterator copy_lit(OutputIterator it, CharT (&s)[N]) {
884   return std::copy_n(s, N - 1, it);
885 }
886
887 // Returns x**y
888 double int_pow(double x, size_t y);
889
890 uint32_t hash32(const StringRef &s);
891
892 // Computes SHA-256 of |s|, and stores it in |buf|.  This function
893 // returns 0 if it succeeds, or -1.
894 int sha256(uint8_t *buf, const StringRef &s);
895
896 // Computes SHA-1 of |s|, and stores it in |buf|.  This function
897 // returns 0 if it succeeds, or -1.
898 int sha1(uint8_t *buf, const StringRef &s);
899
900 // Returns host from |hostport|.  If host cannot be found in
901 // |hostport|, returns empty string.  The returned string might not be
902 // NULL-terminated.
903 StringRef extract_host(const StringRef &hostport);
904
905 // split_hostport splits host and port in |hostport|.  Unlike
906 // extract_host, square brackets enclosing host name is stripped.  If
907 // port is not available, it returns empty string in the second
908 // string.  The returned string might not be NULL-terminated.  On any
909 // error, it returns a pair which has empty strings.
910 std::pair<StringRef, StringRef> split_hostport(const StringRef &hostport);
911
912 // Returns new std::mt19937 object.
913 std::mt19937 make_mt19937();
914
915 // daemonize calls daemon(3).  If __APPLE__ is defined, it implements
916 // daemon() using fork().
917 int daemonize(int nochdir, int noclose);
918
919 #ifdef ENABLE_HTTP3
920 int msghdr_get_local_addr(Address &dest, msghdr *msg, int family);
921 #endif // ENABLE_HTTP3
922
923 } // namespace util
924
925 } // namespace nghttp2
926
927 #endif // UTIL_H