2 * nghttp2 - HTTP/2 C Library
4 * Copyright (c) 2012 Tatsuhiro Tsujikawa
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:
14 * The above copyright notice and this permission notice shall be
15 * included in all copies or substantial portions of the Software.
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.
28 #include "nghttp2_config.h"
32 #endif // HAVE_UNISTD_H
36 #endif // HAVE_NETDB_H
50 #include "url-parser/url_parser.h"
54 #include "allocator.h"
58 constexpr auto NGHTTP2_H2_ALPN = StringRef::from_lit("\x2h2");
59 constexpr auto NGHTTP2_H2 = StringRef::from_lit("h2");
61 // The additional HTTP/2 protocol ALPN protocol identifier we also
62 // supports for our applications to make smooth migration into final
64 constexpr auto NGHTTP2_H2_16_ALPN = StringRef::from_lit("\x5h2-16");
65 constexpr auto NGHTTP2_H2_16 = StringRef::from_lit("h2-16");
67 constexpr auto NGHTTP2_H2_14_ALPN = StringRef::from_lit("\x5h2-14");
68 constexpr auto NGHTTP2_H2_14 = StringRef::from_lit("h2-14");
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");
73 constexpr size_t NGHTTP2_MAX_UINT64_DIGITS = str_size("18446744073709551615");
77 extern const char UPPER_XDIGITS[];
79 inline bool is_alpha(const char c) {
80 return ('A' <= c && c <= 'Z') || ('a' <= c && c <= 'z');
83 inline bool is_digit(const char c) { return '0' <= c && c <= '9'; }
85 inline bool is_hex_digit(const char c) {
86 return is_digit(c) || ('A' <= c && c <= 'F') || ('a' <= c && c <= 'f');
89 // Returns true if |s| is hex string.
90 bool is_hex_string(const StringRef &s);
92 bool in_rfc3986_unreserved_chars(const char c);
94 bool in_rfc3986_sub_delims(const char c);
96 // Returns true if |c| is in token (HTTP-p1, Section 3.2.6)
97 bool in_token(char c);
99 bool in_attr_char(char c);
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);
105 std::string percent_encode(const unsigned char *target, size_t len);
107 std::string percent_encode(const std::string &target);
109 // percent-encode path component of URI |s|.
110 std::string percent_encode_path(const std::string &s);
112 template <typename InputIt>
113 std::string percent_decode(InputIt first, InputIt last) {
115 result.resize(last - first);
116 auto p = std::begin(result);
117 for (; first != last; ++first) {
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));
132 result.resize(p - std::begin(result));
136 StringRef percent_decode(BlockAllocator &balloc, const StringRef &src);
138 // Percent encode |target| if character is not in token or '%'.
139 StringRef percent_encode_token(BlockAllocator &balloc, const StringRef &target);
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) {
146 if (c != '%' && in_token(c)) {
152 *it++ = UPPER_XDIGITS[c >> 4];
153 *it++ = UPPER_XDIGITS[(c & 0x0f)];
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);
164 // Returns quotedString version of |target|. Currently, this function
165 // just replace '"' with '\"'.
166 StringRef quote_string(BlockAllocator &balloc, const StringRef &target);
168 template <typename OutputIt>
169 OutputIt quote_string(OutputIt it, const StringRef &target) {
170 for (auto c : target) {
182 // Returns the number of bytes written by quote_string with the same
183 // |target| parameter. The return value does not include a terminal
185 size_t quote_stringlen(const StringRef &target);
187 std::string format_hex(const unsigned char *s, size_t len);
189 template <size_t N> std::string format_hex(const unsigned char (&s)[N]) {
190 return format_hex(s, N);
193 template <size_t N> std::string format_hex(const std::array<uint8_t, N> &s) {
194 return format_hex(s.data(), s.size());
197 StringRef format_hex(BlockAllocator &balloc, const StringRef &s);
199 static constexpr char LOWER_XDIGITS[] = "0123456789abcdef";
201 template <typename OutputIt>
202 OutputIt format_hex(OutputIt it, const StringRef &s) {
205 *it++ = LOWER_XDIGITS[c >> 4];
206 *it++ = LOWER_XDIGITS[c & 0xf];
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)
215 StringRef decode_hex(BlockAllocator &balloc, const StringRef &s);
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));
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);
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);
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);
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);
255 time_t parse_http_date(const StringRef &s);
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);
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,
285 return tbl[static_cast<unsigned char>(c)];
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) {
294 return std::equal(first2, last2, first1);
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());
302 bool operator()(char lhs, char rhs) const {
303 return lowcase(lhs) == lowcase(rhs);
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) {
313 return std::equal(first2, last2, first1, CaseCmp());
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());
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);
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) {
331 return std::equal(first2, last2, last1 - (last2 - first2));
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());
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);
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) {
349 return std::equal(first2, last2, last1 - (last2 - first2), CaseCmp());
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());
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);
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)) {
367 return std::equal(first1, last1, first2, CaseCmp());
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());
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);
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());
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)) {
389 return std::equal(first1, last1, first2);
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());
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);
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());
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()) !=
413 template <typename InputIt> void inp_strlower(InputIt first, InputIt last) {
414 std::transform(first, last, first, lowcase);
417 // Lowercase |s| in place.
418 inline void inp_strlower(std::string &s) {
419 inp_strlower(std::begin(s), std::end(s));
422 // Returns string representation of |n| with 2 fractional digits.
423 std::string dtos(double n);
425 template <typename T> std::string utos(T n) {
432 for (auto t = n; t; t /= 10, ++nlen)
436 res[--nlen] = (n % 10) + '0';
441 template <typename T, typename OutputIt> OutputIt utos(OutputIt dst, T n) {
447 for (auto t = n; t; t /= 10, ++nlen)
452 *--p = (n % 10) + '0';
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);
461 p = util::utos(p, n);
463 return StringRef{iov.base, p};
466 template <typename T> std::string utos_unit(T n) {
468 if (n >= (1 << 30)) {
471 } else if (n >= (1 << 20)) {
474 } else if (n >= (1 << 10)) {
484 // Like utos_unit(), but 2 digits fraction part is followed.
485 template <typename T> std::string utos_funit(T n) {
488 if (n >= (1 << 30)) {
491 } else if (n >= (1 << 20)) {
494 } else if (n >= (1 << 10)) {
501 return dtos(static_cast<double>(n) / (1 << b)) + u;
504 template <typename T> std::string utox(T n) {
512 for (; t; t /= 16, ++i)
516 for (; n; --i, n /= 16) {
517 res[i] = UPPER_XDIGITS[(n & 0x0f)];
522 void to_token68(std::string &base64str);
524 StringRef to_base64(BlockAllocator &balloc, const StringRef &token68str);
526 void show_candidates(const char *unkopt, const option *options);
528 bool has_uri_field(const http_parser_url &u, http_parser_url_fields field);
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);
533 bool fieldeq(const char *uri, const http_parser_url &u,
534 http_parser_url_fields field, const char *t);
536 bool fieldeq(const char *uri, const http_parser_url &u,
537 http_parser_url_fields field, const StringRef &t);
539 StringRef get_uri_field(const char *uri, const http_parser_url &u,
540 http_parser_url_fields field);
542 uint16_t get_default_port(const char *uri, const http_parser_url &u);
544 bool porteq(const char *uri1, const http_parser_url &u1, const char *uri2,
545 const http_parser_url &u2);
547 void write_uri_field(std::ostream &o, const char *uri, const http_parser_url &u,
548 http_parser_url_fields field);
550 bool numeric_host(const char *hostname);
552 bool numeric_host(const char *hostname, int family);
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);
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);
564 std::string to_numeric_addr(const struct sockaddr *sa, socklen_t salen);
566 // Sets |port| to |addr|.
567 void set_port(Address &addr, uint16_t port);
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);
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
579 char *get_exec_path(int argc, char **const argv, const char *cwd);
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);
587 // Returns the |tv| value as 64 bit integer using a microsecond as an
589 int64_t to_time64(const timeval &tv);
591 // Returns true if ALPN ID |proto| is supported HTTP/2 protocol
593 bool check_h2_is_selected(const StringRef &proto);
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
598 bool select_h2(const unsigned char **out, unsigned char *outlen,
599 const unsigned char *in, unsigned int inlen);
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
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);
608 // Returns default ALPN protocol list, which only contains supported
609 // HTTP/2 protocol identifier.
610 std::vector<unsigned char> get_default_alpn();
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,
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);
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);
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) {
636 std::chrono::duration_cast<std::chrono::seconds>(tp.time_since_epoch());
637 auto p = common_log_date(out, t.count());
639 return StringRef{out, p};
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());
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());
662 return StringRef{out, p};
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());
676 return StringRef{out, p};
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
685 template <typename T> StringRef format_http_date(char *out, const T &tp) {
687 std::chrono::duration_cast<std::chrono::seconds>(tp.time_since_epoch());
688 auto p = http_date(out, t.count());
690 return StringRef{out, p};
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);
698 return duration.count();
701 int make_socket_closeonexec(int fd);
702 int make_socket_nonblocking(int fd);
703 int make_socket_nodelay(int fd);
705 int create_nonblock_socket(int family);
706 int create_nonblock_udp_socket(int family);
708 int bind_any_addr_udp(int fd, int family);
710 bool check_socket_connected(int fd);
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);
717 // Returns true if |host| is IPv6 numeric address (e.g., ::1)
718 bool ipv6_numeric_addr(const char *host);
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
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);
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);
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);
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);
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);
762 // Just like above, but this takes |t| as seconds.
763 std::string format_duration(double t);
765 // The maximum buffer size including terminal NULL to store the result
767 constexpr size_t max_hostport = NI_MAXHOST + /* [] for IPv6 */ 2 + /* : */ 1 +
768 /* port */ 5 + /* terminal NULL */ 1;
770 // Just like make_http_hostport(), but doesn't treat 80 and 443
772 StringRef make_hostport(BlockAllocator &balloc, const StringRef &host,
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);
785 p = std::copy(std::begin(host), std::end(host), p);
793 p = std::copy(std::begin(serv), std::end(serv), p);
797 return StringRef{first, p};
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,
806 template <typename OutputIt>
807 StringRef make_http_hostport(OutputIt first, const StringRef &host,
809 if (port != 80 && port != 443) {
810 return make_hostport(first, host, port);
813 auto ipv6 = ipv6_numeric_addr(host.c_str());
820 p = std::copy(std::begin(host), std::end(host), p);
828 return StringRef{first, p};
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);
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);
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);
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);
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);
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);
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,
857 int read_mime_types(std::map<std::string, std::string> &res,
858 const char *filename);
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)];
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); });
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);
888 double int_pow(double x, size_t y);
890 uint32_t hash32(const StringRef &s);
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);
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);
900 // Returns host from |hostport|. If host cannot be found in
901 // |hostport|, returns empty string. The returned string might not be
903 StringRef extract_host(const StringRef &hostport);
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);
912 // Returns new std::mt19937 object.
913 std::mt19937 make_mt19937();
915 // daemonize calls daemon(3). If __APPLE__ is defined, it implements
916 // daemon() using fork().
917 int daemonize(int nochdir, int noclose);
920 int msghdr_get_local_addr(Address &dest, msghdr *msg, int family);
921 #endif // ENABLE_HTTP3
925 } // namespace nghttp2