diff --git a/.clang-tidy b/.clang-tidy index e8fad8a2..3216c702 100644 --- a/.clang-tidy +++ b/.clang-tidy @@ -1,38 +1,8 @@ --- -Checks: 'clang-*,misc-unused-*,llvm-header-guard,llvm-include-order,modernize-*' +Checks: '-*,clang-diagnostic-*,clang-analyzer-*,bugprone-*,concurrency-*,cppcoreguidelines-*,modernize-*,readability-*,-readability-redundant-access-specifiers,-readability-function-cognitive-complexity' WarningsAsErrors: '' HeaderFilterRegex: '' AnalyzeTemporaryDtors: false FormatStyle: none User: sgraves -CheckOptions: - - key: cert-dcl16-c.NewSuffixes - value: 'L;LL;LU;LLU' - - key: cert-oop54-cpp.WarnOnlyIfThisHasSuspiciousField - value: '0' - - key: cppcoreguidelines-explicit-virtual-functions.IgnoreDestructors - value: '1' - - key: cppcoreguidelines-non-private-member-variables-in-classes.IgnoreClassesWithAllMemberVariablesBeingPublic - value: '1' - - key: google-readability-braces-around-statements.ShortStatementLines - value: '1' - - key: google-readability-function-size.StatementThreshold - value: '800' - - key: google-readability-namespace-comments.ShortNamespaceLines - value: '10' - - key: google-readability-namespace-comments.SpacesBeforeComments - value: '2' - - key: modernize-loop-convert.MaxCopySize - value: '16' - - key: modernize-loop-convert.MinConfidence - value: reasonable - - key: modernize-loop-convert.NamingStyle - value: CamelCase - - key: modernize-pass-by-value.IncludeStyle - value: llvm - - key: modernize-replace-auto-ptr.IncludeStyle - value: llvm - - key: modernize-use-nullptr.NullMacros - value: 'NULL' ... - diff --git a/3rd_party/cpp-httplib/httplib.h b/3rd_party/cpp-httplib/httplib.h index 89449452..31dcbd65 100644 --- a/3rd_party/cpp-httplib/httplib.h +++ b/3rd_party/cpp-httplib/httplib.h @@ -338,7 +338,9 @@ struct scope_exit { } ~scope_exit() { - if (execute_on_destruction) { this->exit_function(); } + if (execute_on_destruction) { + this->exit_function(); + } } void release() { this->execute_on_destruction = false; } @@ -637,7 +639,9 @@ private: pool_.cond_.wait( lock, [&] { return !pool_.jobs_.empty() || pool_.shutdown_; }); - if (pool_.shutdown_ && pool_.jobs_.empty()) { break; } + if (pool_.shutdown_ && pool_.jobs_.empty()) { + break; + } fn = std::move(pool_.jobs_.front()); pool_.jobs_.pop_front(); @@ -972,7 +976,8 @@ public: Result() = default; Result(std::unique_ptr &&res, Error err, Headers &&request_headers = Headers{}) - : res_(std::move(res)), err_(err), + : res_(std::move(res)), + err_(err), request_headers_(std::move(request_headers)) {} // Response operator bool() const { return res_ != nullptr; } @@ -1754,7 +1759,9 @@ inline ssize_t Stream::write_format(const char *fmt, const Args &...args) { std::array buf{}; auto sn = snprintf(buf.data(), buf.size() - 1, fmt, args...); - if (sn <= 0) { return sn; } + if (sn <= 0) { + return sn; + } auto n = static_cast(sn); @@ -1792,71 +1799,134 @@ inline void default_socket_options(socket_t sock) { inline const char *status_message(int status) { switch (status) { - case 100: return "Continue"; - case 101: return "Switching Protocol"; - case 102: return "Processing"; - case 103: return "Early Hints"; - case 200: return "OK"; - case 201: return "Created"; - case 202: return "Accepted"; - case 203: return "Non-Authoritative Information"; - case 204: return "No Content"; - case 205: return "Reset Content"; - case 206: return "Partial Content"; - case 207: return "Multi-Status"; - case 208: return "Already Reported"; - case 226: return "IM Used"; - case 300: return "Multiple Choice"; - case 301: return "Moved Permanently"; - case 302: return "Found"; - case 303: return "See Other"; - case 304: return "Not Modified"; - case 305: return "Use Proxy"; - case 306: return "unused"; - case 307: return "Temporary Redirect"; - case 308: return "Permanent Redirect"; - case 400: return "Bad Request"; - case 401: return "Unauthorized"; - case 402: return "Payment Required"; - case 403: return "Forbidden"; - case 404: return "Not Found"; - case 405: return "Method Not Allowed"; - case 406: return "Not Acceptable"; - case 407: return "Proxy Authentication Required"; - case 408: return "Request Timeout"; - case 409: return "Conflict"; - case 410: return "Gone"; - case 411: return "Length Required"; - case 412: return "Precondition Failed"; - case 413: return "Payload Too Large"; - case 414: return "URI Too Long"; - case 415: return "Unsupported Media Type"; - case 416: return "Range Not Satisfiable"; - case 417: return "Expectation Failed"; - case 418: return "I'm a teapot"; - case 421: return "Misdirected Request"; - case 422: return "Unprocessable Entity"; - case 423: return "Locked"; - case 424: return "Failed Dependency"; - case 425: return "Too Early"; - case 426: return "Upgrade Required"; - case 428: return "Precondition Required"; - case 429: return "Too Many Requests"; - case 431: return "Request Header Fields Too Large"; - case 451: return "Unavailable For Legal Reasons"; - case 501: return "Not Implemented"; - case 502: return "Bad Gateway"; - case 503: return "Service Unavailable"; - case 504: return "Gateway Timeout"; - case 505: return "HTTP Version Not Supported"; - case 506: return "Variant Also Negotiates"; - case 507: return "Insufficient Storage"; - case 508: return "Loop Detected"; - case 510: return "Not Extended"; - case 511: return "Network Authentication Required"; + case 100: + return "Continue"; + case 101: + return "Switching Protocol"; + case 102: + return "Processing"; + case 103: + return "Early Hints"; + case 200: + return "OK"; + case 201: + return "Created"; + case 202: + return "Accepted"; + case 203: + return "Non-Authoritative Information"; + case 204: + return "No Content"; + case 205: + return "Reset Content"; + case 206: + return "Partial Content"; + case 207: + return "Multi-Status"; + case 208: + return "Already Reported"; + case 226: + return "IM Used"; + case 300: + return "Multiple Choice"; + case 301: + return "Moved Permanently"; + case 302: + return "Found"; + case 303: + return "See Other"; + case 304: + return "Not Modified"; + case 305: + return "Use Proxy"; + case 306: + return "unused"; + case 307: + return "Temporary Redirect"; + case 308: + return "Permanent Redirect"; + case 400: + return "Bad Request"; + case 401: + return "Unauthorized"; + case 402: + return "Payment Required"; + case 403: + return "Forbidden"; + case 404: + return "Not Found"; + case 405: + return "Method Not Allowed"; + case 406: + return "Not Acceptable"; + case 407: + return "Proxy Authentication Required"; + case 408: + return "Request Timeout"; + case 409: + return "Conflict"; + case 410: + return "Gone"; + case 411: + return "Length Required"; + case 412: + return "Precondition Failed"; + case 413: + return "Payload Too Large"; + case 414: + return "URI Too Long"; + case 415: + return "Unsupported Media Type"; + case 416: + return "Range Not Satisfiable"; + case 417: + return "Expectation Failed"; + case 418: + return "I'm a teapot"; + case 421: + return "Misdirected Request"; + case 422: + return "Unprocessable Entity"; + case 423: + return "Locked"; + case 424: + return "Failed Dependency"; + case 425: + return "Too Early"; + case 426: + return "Upgrade Required"; + case 428: + return "Precondition Required"; + case 429: + return "Too Many Requests"; + case 431: + return "Request Header Fields Too Large"; + case 451: + return "Unavailable For Legal Reasons"; + case 501: + return "Not Implemented"; + case 502: + return "Bad Gateway"; + case 503: + return "Service Unavailable"; + case 504: + return "Gateway Timeout"; + case 505: + return "HTTP Version Not Supported"; + case 506: + return "Variant Also Negotiates"; + case 507: + return "Insufficient Storage"; + case 508: + return "Loop Detected"; + case 510: + return "Not Extended"; + case 511: + return "Network Authentication Required"; default: - case 500: return "Internal Server Error"; + case 500: + return "Internal Server Error"; } } @@ -1886,23 +1956,38 @@ Server::set_idle_interval(const std::chrono::duration &duration) { inline std::string to_string(const Error error) { switch (error) { - case Error::Success: return "Success (no error)"; - case Error::Connection: return "Could not establish connection"; - case Error::BindIPAddress: return "Failed to bind IP address"; - case Error::Read: return "Failed to read connection"; - case Error::Write: return "Failed to write connection"; - case Error::ExceedRedirectCount: return "Maximum redirect count exceeded"; - case Error::Canceled: return "Connection handling canceled"; - case Error::SSLConnection: return "SSL connection failed"; - case Error::SSLLoadingCerts: return "SSL certificate loading failed"; - case Error::SSLServerVerification: return "SSL server verification failed"; + case Error::Success: + return "Success (no error)"; + case Error::Connection: + return "Could not establish connection"; + case Error::BindIPAddress: + return "Failed to bind IP address"; + case Error::Read: + return "Failed to read connection"; + case Error::Write: + return "Failed to write connection"; + case Error::ExceedRedirectCount: + return "Maximum redirect count exceeded"; + case Error::Canceled: + return "Connection handling canceled"; + case Error::SSLConnection: + return "SSL connection failed"; + case Error::SSLLoadingCerts: + return "SSL certificate loading failed"; + case Error::SSLServerVerification: + return "SSL server verification failed"; case Error::UnsupportedMultipartBoundaryChars: return "Unsupported HTTP multipart boundary characters"; - case Error::Compression: return "Compression failed"; - case Error::ConnectionTimeout: return "Connection timed out"; - case Error::ProxyConnection: return "Proxy connection failed"; - case Error::Unknown: return "Unknown"; - default: break; + case Error::Compression: + return "Compression failed"; + case Error::ConnectionTimeout: + return "Connection timed out"; + case Error::ProxyConnection: + return "Proxy connection failed"; + case Error::Unknown: + return "Unknown"; + default: + break; } return "Invalid"; @@ -2201,11 +2286,15 @@ inline bool is_hex(char c, int &v) { inline bool from_hex_to_i(const std::string &s, size_t i, size_t cnt, int &val) { - if (i >= s.size()) { return false; } + if (i >= s.size()) { + return false; + } val = 0; for (; cnt; i++, cnt--) { - if (!s[i]) { return false; } + if (!s[i]) { + return false; + } auto v = 0; if (is_hex(s[i], v)) { val = val * 16 + v; @@ -2279,7 +2368,9 @@ inline std::string base64_encode(const std::string &in) { } } - if (valb > -6) { out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); } + if (valb > -6) { + out.push_back(lookup[((val << 8) >> (valb + 8)) & 0x3F]); + } while (out.size() % 4) { out.push_back('='); @@ -2324,7 +2415,9 @@ inline bool is_valid_path(const std::string &path) { if (!path.compare(beg, len, ".")) { ; } else if (!path.compare(beg, len, "..")) { - if (level == 0) { return false; } + if (level == 0) { + return false; + } level--; } else { level++; @@ -2366,14 +2459,28 @@ inline std::string encode_url(const std::string &s) { for (size_t i = 0; s[i]; i++) { switch (s[i]) { - case ' ': result += "%20"; break; - case '+': result += "%2B"; break; - case '\r': result += "%0D"; break; - case '\n': result += "%0A"; break; - case '\'': result += "%27"; break; - case ',': result += "%2C"; break; + case ' ': + result += "%20"; + break; + case '+': + result += "%2B"; + break; + case '\r': + result += "%0D"; + break; + case '\n': + result += "%0A"; + break; + case '\'': + result += "%27"; + break; + case ',': + result += "%2C"; + break; // case ':': result += "%3A"; break; // ok? probably... - case ';': result += "%3B"; break; + case ';': + result += "%3B"; + break; default: auto c = static_cast(s[i]); if (c >= 0x80) { @@ -2404,7 +2511,9 @@ inline std::string decode_url(const std::string &s, // 4 digits Unicode codes char buff[4]; size_t len = to_utf8(val, buff); - if (len > 0) { result.append(buff, len); } + if (len > 0) { + result.append(buff, len); + } i += 5; // 'u0000' } else { result += s[i]; @@ -2441,7 +2550,9 @@ inline void read_file(const std::string &path, std::string &out) { inline std::string file_extension(const std::string &path) { std::smatch m; static auto re = std::regex("\\.([a-zA-Z0-9]+)$"); - if (std::regex_search(path, m, re)) { return m[1].str(); } + if (std::regex_search(path, m, re)) { + return m[1].str(); + } return std::string(); } @@ -2478,7 +2589,9 @@ inline void split(const char *b, const char *e, char d, while (e ? (b + i < e) : (b[i] != '\0')) { if (b[i] == d) { auto r = trim(b, e, beg, i); - if (r.first < r.second) { fn(&b[r.first], &b[r.second]); } + if (r.first < r.second) { + fn(&b[r.first], &b[r.second]); + } beg = i + 1; } i++; @@ -2486,13 +2599,16 @@ inline void split(const char *b, const char *e, char d, if (i) { auto r = trim(b, e, beg, i); - if (r.first < r.second) { fn(&b[r.first], &b[r.second]); } + if (r.first < r.second) { + fn(&b[r.first], &b[r.second]); + } } } inline stream_line_reader::stream_line_reader(Stream &strm, char *fixed_buffer, size_t fixed_buffer_size) - : strm_(strm), fixed_buffer_(fixed_buffer), + : strm_(strm), + fixed_buffer_(fixed_buffer), fixed_buffer_size_(fixed_buffer_size) {} inline const char *stream_line_reader::ptr() const { @@ -2536,7 +2652,9 @@ inline bool stream_line_reader::getline() { append(byte); - if (byte == '\n') { break; } + if (byte == '\n') { + break; + } } return true; @@ -2557,13 +2675,17 @@ inline void stream_line_reader::append(char c) { inline mmap::mmap(const char *path) #if defined(_WIN32) - : hFile_(NULL), hMapping_(NULL) + : hFile_(NULL), + hMapping_(NULL) #else : fd_(-1) #endif , - size_(0), addr_(nullptr) { - if (!open(path)) { std::runtime_error(""); } + size_(0), + addr_(nullptr) { + if (!open(path)) { + std::runtime_error(""); + } } inline mmap::~mmap() { close(); } @@ -2575,7 +2697,9 @@ inline bool mmap::open(const char *path) { hFile_ = ::CreateFileA(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); - if (hFile_ == INVALID_HANDLE_VALUE) { return false; } + if (hFile_ == INVALID_HANDLE_VALUE) { + return false; + } size_ = ::GetFileSize(hFile_, NULL); @@ -2589,7 +2713,9 @@ inline bool mmap::open(const char *path) { addr_ = ::MapViewOfFile(hMapping_, FILE_MAP_READ, 0, 0, 0); #else fd_ = ::open(path, O_RDONLY); - if (fd_ == -1) { return false; } + if (fd_ == -1) { + return false; + } struct stat sb; if (fstat(fd_, &sb) == -1) { @@ -2656,7 +2782,9 @@ template inline ssize_t handle_EINTR(T fn) { ssize_t res = 0; while (true) { res = fn(); - if (res < 0 && errno == EINTR) { continue; } + if (res < 0 && errno == EINTR) { + continue; + } break; } return res; @@ -2698,7 +2826,9 @@ inline ssize_t select_read(socket_t sock, time_t sec, time_t usec) { return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); }); #else #ifndef _WIN32 - if (sock >= FD_SETSIZE) { return 1; } + if (sock >= FD_SETSIZE) { + return 1; + } #endif fd_set fds; @@ -2726,7 +2856,9 @@ inline ssize_t select_write(socket_t sock, time_t sec, time_t usec) { return handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); }); #else #ifndef _WIN32 - if (sock >= FD_SETSIZE) { return 1; } + if (sock >= FD_SETSIZE) { + return 1; + } #endif fd_set fds; @@ -2754,7 +2886,9 @@ inline Error wait_until_socket_is_ready(socket_t sock, time_t sec, auto poll_res = handle_EINTR([&]() { return poll(&pfd_read, 1, timeout); }); - if (poll_res == 0) { return Error::ConnectionTimeout; } + if (poll_res == 0) { + return Error::ConnectionTimeout; + } if (poll_res > 0 && pfd_read.revents & (POLLIN | POLLOUT)) { auto error = 0; @@ -2768,7 +2902,9 @@ inline Error wait_until_socket_is_ready(socket_t sock, time_t sec, return Error::Connection; #else #ifndef _WIN32 - if (sock >= FD_SETSIZE) { return Error::Connection; } + if (sock >= FD_SETSIZE) { + return Error::Connection; + } #endif fd_set fdsr; @@ -2786,7 +2922,9 @@ inline Error wait_until_socket_is_ready(socket_t sock, time_t sec, return select(static_cast(sock + 1), &fdsr, &fdsw, &fdse, &tv); }); - if (ret == 0) { return Error::ConnectionTimeout; } + if (ret == 0) { + return Error::ConnectionTimeout; + } if (ret > 0 && (FD_ISSET(sock, &fdsr) || FD_ISSET(sock, &fdsw))) { auto error = 0; @@ -2876,7 +3014,9 @@ inline bool keep_alive(socket_t sock, time_t keep_alive_timeout_sec) { auto current = steady_clock::now(); auto duration = duration_cast(current - start); auto timeout = keep_alive_timeout_sec * 1000; - if (duration.count() > timeout) { return false; } + if (duration.count() > timeout) { + return false; + } std::this_thread::sleep_for(std::chrono::milliseconds(1)); } else { return true; @@ -2897,7 +3037,9 @@ process_server_socket_core(const std::atomic &svr_sock, socket_t sock, auto close_connection = count == 1; auto connection_closed = false; ret = callback(close_connection, connection_closed); - if (!ret || connection_closed) { break; } + if (!ret || connection_closed) { + break; + } count--; } return ret; @@ -2957,7 +3099,9 @@ socket_t create_socket(const std::string &host, const std::string &ip, int port, hints.ai_family = AF_UNSPEC; hints.ai_flags = AI_NUMERICHOST; } else { - if (!host.empty()) { node = host.c_str(); } + if (!host.empty()) { + node = host.c_str(); + } hints.ai_family = address_family; hints.ai_flags = socket_flags; } @@ -2965,7 +3109,8 @@ socket_t create_socket(const std::string &host, const std::string &ip, int port, #ifndef _WIN32 if (hints.ai_family == AF_UNIX) { const auto addrlen = host.length(); - if (addrlen > sizeof(sockaddr_un::sun_path)) return INVALID_SOCKET; + if (addrlen > sizeof(sockaddr_un::sun_path)) + return INVALID_SOCKET; auto sock = socket(hints.ai_family, hints.ai_socktype, hints.ai_protocol); if (sock != INVALID_SOCKET) { @@ -2978,7 +3123,9 @@ socket_t create_socket(const std::string &host, const std::string &ip, int port, sizeof(addr) - sizeof(addr.sun_path) + addrlen); fcntl(sock, F_SETFD, FD_CLOEXEC); - if (socket_options) { socket_options(sock); } + if (socket_options) { + socket_options(sock); + } if (!bind_or_connect(sock, hints)) { close_socket(sock); @@ -3024,7 +3171,9 @@ socket_t create_socket(const std::string &host, const std::string &ip, int port, #else auto sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); #endif - if (sock == INVALID_SOCKET) { continue; } + if (sock == INVALID_SOCKET) { + continue; + } #ifndef _WIN32 if (fcntl(sock, F_SETFD, FD_CLOEXEC) == -1) { @@ -3044,7 +3193,9 @@ socket_t create_socket(const std::string &host, const std::string &ip, int port, #endif } - if (socket_options) { socket_options(sock); } + if (socket_options) { + socket_options(sock); + } if (rp->ai_family == AF_INET6) { auto no = 0; @@ -3098,7 +3249,9 @@ inline bool bind_ip_address(socket_t sock, const std::string &host) { hints.ai_socktype = SOCK_STREAM; hints.ai_protocol = 0; - if (getaddrinfo(host.c_str(), "0", &hints, &result)) { return false; } + if (getaddrinfo(host.c_str(), "0", &hints, &result)) { + return false; + } auto ret = false; for (auto rp = result; rp; rp = rp->ai_next) { @@ -3168,7 +3321,9 @@ inline socket_t create_client_socket( if (!intf.empty()) { #ifdef USE_IF2IP auto ip_from_if = if2ip(address_family, intf); - if (ip_from_if.empty()) { ip_from_if = intf; } + if (ip_from_if.empty()) { + ip_from_if = intf; + } if (!bind_ip_address(sock2, ip_from_if.c_str())) { error = Error::BindIPAddress; return false; @@ -3188,7 +3343,9 @@ inline socket_t create_client_socket( } error = wait_until_socket_is_ready(sock2, connection_timeout_sec, connection_timeout_usec); - if (error != Error::Success) { return false; } + if (error != Error::Success) { + return false; + } } set_nonblocking(sock2, false); @@ -3230,7 +3387,9 @@ inline socket_t create_client_socket( if (sock != INVALID_SOCKET) { error = Error::Success; } else { - if (error == Error::Success) { error = Error::Connection; } + if (error == Error::Success) { + error = Error::Connection; + } } return sock; @@ -3326,62 +3485,105 @@ find_content_type(const std::string &path, auto ext = file_extension(path); auto it = user_data.find(ext); - if (it != user_data.end()) { return it->second.c_str(); } + if (it != user_data.end()) { + return it->second.c_str(); + } using udl::operator""_t; switch (str2tag(ext)) { - default: return default_content_type; + default: + return default_content_type; - case "css"_t: return "text/css"; - case "csv"_t: return "text/csv"; + case "css"_t: + return "text/css"; + case "csv"_t: + return "text/csv"; case "htm"_t: - case "html"_t: return "text/html"; + case "html"_t: + return "text/html"; case "js"_t: - case "mjs"_t: return "text/javascript"; - case "txt"_t: return "text/plain"; - case "vtt"_t: return "text/vtt"; + case "mjs"_t: + return "text/javascript"; + case "txt"_t: + return "text/plain"; + case "vtt"_t: + return "text/vtt"; - case "apng"_t: return "image/apng"; - case "avif"_t: return "image/avif"; - case "bmp"_t: return "image/bmp"; - case "gif"_t: return "image/gif"; - case "png"_t: return "image/png"; - case "svg"_t: return "image/svg+xml"; - case "webp"_t: return "image/webp"; - case "ico"_t: return "image/x-icon"; - case "tif"_t: return "image/tiff"; - case "tiff"_t: return "image/tiff"; + case "apng"_t: + return "image/apng"; + case "avif"_t: + return "image/avif"; + case "bmp"_t: + return "image/bmp"; + case "gif"_t: + return "image/gif"; + case "png"_t: + return "image/png"; + case "svg"_t: + return "image/svg+xml"; + case "webp"_t: + return "image/webp"; + case "ico"_t: + return "image/x-icon"; + case "tif"_t: + return "image/tiff"; + case "tiff"_t: + return "image/tiff"; case "jpg"_t: - case "jpeg"_t: return "image/jpeg"; + case "jpeg"_t: + return "image/jpeg"; - case "mp4"_t: return "video/mp4"; - case "mpeg"_t: return "video/mpeg"; - case "webm"_t: return "video/webm"; + case "mp4"_t: + return "video/mp4"; + case "mpeg"_t: + return "video/mpeg"; + case "webm"_t: + return "video/webm"; - case "mp3"_t: return "audio/mp3"; - case "mpga"_t: return "audio/mpeg"; - case "weba"_t: return "audio/webm"; - case "wav"_t: return "audio/wave"; + case "mp3"_t: + return "audio/mp3"; + case "mpga"_t: + return "audio/mpeg"; + case "weba"_t: + return "audio/webm"; + case "wav"_t: + return "audio/wave"; - case "otf"_t: return "font/otf"; - case "ttf"_t: return "font/ttf"; - case "woff"_t: return "font/woff"; - case "woff2"_t: return "font/woff2"; + case "otf"_t: + return "font/otf"; + case "ttf"_t: + return "font/ttf"; + case "woff"_t: + return "font/woff"; + case "woff2"_t: + return "font/woff2"; - case "7z"_t: return "application/x-7z-compressed"; - case "atom"_t: return "application/atom+xml"; - case "pdf"_t: return "application/pdf"; - case "json"_t: return "application/json"; - case "rss"_t: return "application/rss+xml"; - case "tar"_t: return "application/x-tar"; + case "7z"_t: + return "application/x-7z-compressed"; + case "atom"_t: + return "application/atom+xml"; + case "pdf"_t: + return "application/pdf"; + case "json"_t: + return "application/json"; + case "rss"_t: + return "application/rss+xml"; + case "tar"_t: + return "application/x-tar"; case "xht"_t: - case "xhtml"_t: return "application/xhtml+xml"; - case "xslt"_t: return "application/xslt+xml"; - case "xml"_t: return "application/xml"; - case "gz"_t: return "application/gzip"; - case "zip"_t: return "application/zip"; - case "wasm"_t: return "application/wasm"; + case "xhtml"_t: + return "application/xhtml+xml"; + case "xslt"_t: + return "application/xslt+xml"; + case "xml"_t: + return "application/xml"; + case "gz"_t: + return "application/gzip"; + case "zip"_t: + return "application/zip"; + case "wasm"_t: + return "application/wasm"; } } @@ -3396,7 +3598,8 @@ inline bool can_compress_content_type(const std::string &content_type) { case "application/json"_t: case "application/xml"_t: case "application/protobuf"_t: - case "application/xhtml+xml"_t: return true; + case "application/xhtml+xml"_t: + return true; default: return !content_type.rfind("text/", 0) && tag != "text/event-stream"_t; @@ -3406,7 +3609,9 @@ inline bool can_compress_content_type(const std::string &content_type) { inline EncodingType encoding_type(const Request &req, const Response &res) { auto ret = detail::can_compress_content_type(res.get_header_value("Content-Type")); - if (!ret) { return EncodingType::None; } + if (!ret) { + return EncodingType::None; + } const auto &s = req.get_header_value("Accept-Encoding"); (void)(s); @@ -3414,13 +3619,17 @@ inline EncodingType encoding_type(const Request &req, const Response &res) { #ifdef CPPHTTPLIB_BROTLI_SUPPORT // TODO: 'Accept-Encoding' has br, not br;q=0 ret = s.find("br") != std::string::npos; - if (ret) { return EncodingType::Brotli; } + if (ret) { + return EncodingType::Brotli; + } #endif #ifdef CPPHTTPLIB_ZLIB_SUPPORT // TODO: 'Accept-Encoding' has gzip, not gzip;q=0 ret = s.find("gzip") != std::string::npos; - if (ret) { return EncodingType::Gzip; } + if (ret) { + return EncodingType::Gzip; + } #endif return EncodingType::None; @@ -3428,7 +3637,9 @@ inline EncodingType encoding_type(const Request &req, const Response &res) { inline bool nocompressor::compress(const char *data, size_t data_length, bool /*last*/, Callback callback) { - if (!data_length) { return true; } + if (!data_length) { + return true; + } return callback(data, data_length); } @@ -3469,7 +3680,9 @@ inline bool gzip_compressor::compress(const char *data, size_t data_length, strm_.next_out = reinterpret_cast(buff.data()); ret = deflate(&strm_, flush); - if (ret == Z_STREAM_ERROR) { return false; } + if (ret == Z_STREAM_ERROR) { + return false; + } if (!callback(buff.data(), buff.size() - strm_.avail_out)) { return false; @@ -3529,7 +3742,9 @@ inline bool gzip_decompressor::decompress(const char *data, size_t data_length, switch (ret) { case Z_NEED_DICT: case Z_DATA_ERROR: - case Z_MEM_ERROR: inflateEnd(&strm_); return false; + case Z_MEM_ERROR: + inflateEnd(&strm_); + return false; } if (!callback(buff.data(), buff.size() - strm_.avail_out)) { @@ -3537,7 +3752,8 @@ inline bool gzip_decompressor::decompress(const char *data, size_t data_length, } } - if (ret != Z_OK && ret != Z_STREAM_END) return false; + if (ret != Z_OK && ret != Z_STREAM_END) + return false; } while (data_length > 0); @@ -3564,9 +3780,13 @@ inline bool brotli_compressor::compress(const char *data, size_t data_length, for (;;) { if (last) { - if (BrotliEncoderIsFinished(state_)) { break; } + if (BrotliEncoderIsFinished(state_)) { + break; + } } else { - if (!available_in) { break; } + if (!available_in) { + break; + } } auto available_out = buff.size(); @@ -3593,7 +3813,9 @@ inline brotli_decompressor::brotli_decompressor() { } inline brotli_decompressor::~brotli_decompressor() { - if (decoder_s) { BrotliDecoderDestroyInstance(decoder_s); } + if (decoder_s) { + BrotliDecoderDestroyInstance(decoder_s); + } } inline bool brotli_decompressor::is_valid() const { return decoder_s; } @@ -3621,9 +3843,13 @@ inline bool brotli_decompressor::decompress(const char *data, decoder_s, &avail_in, &next_in, &avail_out, reinterpret_cast(&next_out), &total_out); - if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { return false; } + if (decoder_r == BROTLI_DECODER_RESULT_ERROR) { + return false; + } - if (!callback(buff.data(), buff.size() - avail_out)) { return false; } + if (!callback(buff.data(), buff.size() - avail_out)) { + return false; + } } return decoder_r == BROTLI_DECODER_RESULT_SUCCESS || @@ -3641,14 +3867,20 @@ inline const char *get_header_value(const Headers &headers, auto rng = headers.equal_range(key); auto it = rng.first; std::advance(it, static_cast(id)); - if (it != rng.second) { return it->second.c_str(); } + if (it != rng.second) { + return it->second.c_str(); + } return def; } inline bool compare_case_ignore(const std::string &a, const std::string &b) { - if (a.size() != b.size()) { return false; } + if (a.size() != b.size()) { + return false; + } for (size_t i = 0; i < b.size(); i++) { - if (::tolower(a[i]) != ::tolower(b[i])) { return false; } + if (::tolower(a[i]) != ::tolower(b[i])) { + return false; + } } return true; } @@ -3665,11 +3897,15 @@ inline bool parse_header(const char *beg, const char *end, T fn) { p++; } - if (p == end) { return false; } + if (p == end) { + return false; + } auto key_end = p; - if (*p++ != ':') { return false; } + if (*p++ != ':') { + return false; + } while (p < end && is_space_or_tab(*p)) { p++; @@ -3693,17 +3929,23 @@ inline bool read_headers(Stream &strm, Headers &headers) { stream_line_reader line_reader(strm, buf, bufsiz); for (;;) { - if (!line_reader.getline()) { return false; } + if (!line_reader.getline()) { + return false; + } // Check if the line ends with CRLF. auto line_terminator_len = 2; if (line_reader.end_with_crlf()) { // Blank line indicates end of headers. - if (line_reader.size() == 2) { break; } + if (line_reader.size() == 2) { + break; + } #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR } else { // Blank line indicates end of headers. - if (line_reader.size() == 1) { break; } + if (line_reader.size() == 1) { + break; + } line_terminator_len = 1; } #else @@ -3712,7 +3954,9 @@ inline bool read_headers(Stream &strm, Headers &headers) { } #endif - if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; } + if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { + return false; + } // Exclude line terminator auto end = line_reader.ptr() + line_reader.size() - line_terminator_len; @@ -3735,13 +3979,19 @@ inline bool read_content_with_length(Stream &strm, uint64_t len, while (r < len) { auto read_len = static_cast(len - r); auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ)); - if (n <= 0) { return false; } + if (n <= 0) { + return false; + } - if (!out(buf, static_cast(n), r, len)) { return false; } + if (!out(buf, static_cast(n), r, len)) { + return false; + } r += static_cast(n); if (progress) { - if (!progress(r, len)) { return false; } + if (!progress(r, len)) { + return false; + } } } @@ -3754,7 +4004,9 @@ inline void skip_content_with_length(Stream &strm, uint64_t len) { while (r < len) { auto read_len = static_cast(len - r); auto n = strm.read(buf, (std::min)(read_len, CPPHTTPLIB_RECV_BUFSIZ)); - if (n <= 0) { return; } + if (n <= 0) { + return; + } r += static_cast(n); } } @@ -3771,7 +4023,9 @@ inline bool read_content_without_length(Stream &strm, return true; } - if (!out(buf, static_cast(n), r, 0)) { return false; } + if (!out(buf, static_cast(n), r, 0)) { + return false; + } r += static_cast(n); } @@ -3786,7 +4040,9 @@ inline bool read_content_chunked(Stream &strm, T &x, stream_line_reader line_reader(strm, buf, bufsiz); - if (!line_reader.getline()) { return false; } + if (!line_reader.getline()) { + return false; + } unsigned long chunk_len; while (true) { @@ -3794,29 +4050,45 @@ inline bool read_content_chunked(Stream &strm, T &x, chunk_len = std::strtoul(line_reader.ptr(), &end_ptr, 16); - if (end_ptr == line_reader.ptr()) { return false; } - if (chunk_len == ULONG_MAX) { return false; } + if (end_ptr == line_reader.ptr()) { + return false; + } + if (chunk_len == ULONG_MAX) { + return false; + } - if (chunk_len == 0) { break; } + if (chunk_len == 0) { + break; + } if (!read_content_with_length(strm, chunk_len, nullptr, out)) { return false; } - if (!line_reader.getline()) { return false; } + if (!line_reader.getline()) { + return false; + } - if (strcmp(line_reader.ptr(), "\r\n")) { return false; } + if (strcmp(line_reader.ptr(), "\r\n")) { + return false; + } - if (!line_reader.getline()) { return false; } + if (!line_reader.getline()) { + return false; + } } assert(chunk_len == 0); // Trailer - if (!line_reader.getline()) { return false; } + if (!line_reader.getline()) { + return false; + } while (strcmp(line_reader.ptr(), "\r\n")) { - if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; } + if (line_reader.size() > CPPHTTPLIB_HEADER_MAX_LENGTH) { + return false; + } // Exclude line terminator constexpr auto line_terminator_len = 2; @@ -3827,7 +4099,9 @@ inline bool read_content_chunked(Stream &strm, T &x, x.headers.emplace(std::move(key), std::move(val)); }); - if (!line_reader.getline()) { return false; } + if (!line_reader.getline()) { + return false; + } } return true; @@ -3911,7 +4185,9 @@ bool read_content(Stream &strm, T &x, size_t payload_max_length, int &status, } } - if (!ret) { status = exceed_payload_max_length ? 413 : 400; } + if (!ret) { + status = exceed_payload_max_length ? 413 : 400; + } return ret; }); } // namespace detail @@ -3921,11 +4197,15 @@ inline ssize_t write_headers(Stream &strm, const Headers &headers) { for (const auto &x : headers) { auto len = strm.write_format("%s: %s\r\n", x.first.c_str(), x.second.c_str()); - if (len < 0) { return len; } + if (len < 0) { + return len; + } write_len += len; } auto len = strm.write("\r\n"); - if (len < 0) { return len; } + if (len < 0) { + return len; + } write_len += len; return write_len; } @@ -3934,7 +4214,9 @@ inline bool write_data(Stream &strm, const char *d, size_t l) { size_t offset = 0; while (offset < l) { auto length = strm.write(d + offset, l - offset); - if (length < 0) { return false; } + if (length < 0) { + return false; + } offset += static_cast(length); } return true; @@ -3998,7 +4280,9 @@ write_content_without_length(Stream &strm, data_sink.write = [&](const char *d, size_t l) -> bool { if (ok) { offset += l; - if (!strm.is_writable() || !write_data(strm, d, l)) { ok = false; } + if (!strm.is_writable() || !write_data(strm, d, l)) { + ok = false; + } } return ok; }; @@ -4054,7 +4338,9 @@ write_content_chunked(Stream &strm, const ContentProvider &content_provider, }; auto done_with_trailer = [&](const Headers *trailer) { - if (!ok) { return; } + if (!ok) { + return; + } data_available = false; @@ -4094,7 +4380,9 @@ write_content_chunked(Stream &strm, const ContentProvider &content_provider, } static const std::string crlf("\r\n"); - if (!write_data(strm, crlf.data(), crlf.size())) { ok = false; } + if (!write_data(strm, crlf.data(), crlf.size())) { + ok = false; + } }; data_sink.done = [&](void) { done_with_trailer(nullptr); }; @@ -4150,7 +4438,8 @@ inline bool redirect(T &cli, Request &req, Response &res, req = new_req; res = new_res; - if (res.location.empty()) res.location = location; + if (res.location.empty()) + res.location = location; } return ret; } @@ -4159,7 +4448,9 @@ inline std::string params_to_query_str(const Params ¶ms) { std::string query; for (auto it = params.begin(); it != params.end(); ++it) { - if (it != params.begin()) { query += "&"; } + if (it != params.begin()) { + query += "&"; + } query += it->first; query += "="; query += encode_query_param(it->second); @@ -4171,7 +4462,9 @@ inline void parse_query_text(const std::string &s, Params ¶ms) { std::set cache; split(s.data(), s.data() + s.size(), '&', [&](const char *b, const char *e) { std::string kv(b, e); - if (cache.find(kv) != cache.end()) { return; } + if (cache.find(kv) != cache.end()) { + return; + } cache.insert(kv); std::string key; @@ -4194,7 +4487,9 @@ inline bool parse_multipart_boundary(const std::string &content_type, std::string &boundary) { auto boundary_keyword = "boundary="; auto pos = content_type.find(boundary_keyword); - if (pos == std::string::npos) { return false; } + if (pos == std::string::npos) { + return false; + } auto end = content_type.find(';', pos); auto beg = pos + strlen(boundary_keyword); boundary = trim_double_quotes_copy(content_type.substr(beg, end - beg)); @@ -4205,7 +4500,9 @@ inline void parse_disposition_params(const std::string &s, Params ¶ms) { std::set cache; split(s.data(), s.data() + s.size(), ';', [&](const char *b, const char *e) { std::string kv(b, e); - if (cache.find(kv) != cache.end()) { return; } + if (cache.find(kv) != cache.end()) { + return; + } cache.insert(kv); std::string key; @@ -4237,7 +4534,8 @@ inline bool parse_range_header(const std::string &s, Ranges &ranges) try { auto len = static_cast(m.length(1)); auto all_valid_ranges = true; split(&s[pos], &s[pos + len], ',', [&](const char *b, const char *e) { - if (!all_valid_ranges) return; + if (!all_valid_ranges) + return; static auto re_another_range = std::regex(R"(\s*(\d*)-(\d*))"); std::cmatch cm; if (std::regex_match(b, e, cm, re_another_range)) { @@ -4264,7 +4562,9 @@ inline bool parse_range_header(const std::string &s, Ranges &ranges) try { #ifdef CPPHTTPLIB_NO_EXCEPTIONS } #else -} catch (...) { return false; } +} catch (...) { + return false; +} #endif class MultipartFormDataParser { @@ -4288,8 +4588,12 @@ public: switch (state_) { case 0: { // Initial boundary buf_erase(buf_find(dash_boundary_crlf_)); - if (dash_boundary_crlf_.size() > buf_size()) { return true; } - if (!buf_start_with(dash_boundary_crlf_)) { return false; } + if (dash_boundary_crlf_.size() > buf_size()) { + return true; + } + if (!buf_start_with(dash_boundary_crlf_)) { + return false; + } buf_erase(dash_boundary_crlf_.size()); state_ = 1; break; @@ -4301,7 +4605,9 @@ public: } case 2: { // Headers auto pos = buf_find(crlf_); - if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { return false; } + if (pos > CPPHTTPLIB_HEADER_MAX_LENGTH) { + return false; + } while (pos < buf_size()) { // Empty line if (pos == 0) { @@ -4337,7 +4643,9 @@ public: } it = params.find("filename"); - if (it != params.end()) { file_.filename = it->second; } + if (it != params.end()) { + file_.filename = it->second; + } it = params.find("filename*"); if (it != params.end()) { @@ -4361,11 +4669,15 @@ public: buf_erase(pos + crlf_.size()); pos = buf_find(crlf_); } - if (state_ != 3) { return true; } + if (state_ != 3) { + return true; + } break; } case 3: { // Body - if (crlf_dash_boundary_.size() > buf_size()) { return true; } + if (crlf_dash_boundary_.size() > buf_size()) { + return true; + } auto pos = buf_find(crlf_dash_boundary_); if (pos < buf_size()) { if (!content_callback(buf_data(), pos)) { @@ -4388,12 +4700,16 @@ public: break; } case 4: { // Boundary - if (crlf_.size() > buf_size()) { return true; } + if (crlf_.size() > buf_size()) { + return true; + } if (buf_start_with(crlf_)) { buf_erase(crlf_.size()); state_ = 1; } else { - if (dash_.size() > buf_size()) { return true; } + if (dash_.size() > buf_size()) { + return true; + } if (buf_start_with(dash_)) { buf_erase(dash_.size()); is_valid_ = true; @@ -4419,9 +4735,13 @@ private: bool start_with_case_ignore(const std::string &a, const std::string &b) const { - if (a.size() < b.size()) { return false; } + if (a.size() < b.size()) { + return false; + } for (size_t i = 0; i < b.size(); i++) { - if (::tolower(a[i]) != ::tolower(b[i])) { return false; } + if (::tolower(a[i]) != ::tolower(b[i])) { + return false; + } } return true; } @@ -4439,9 +4759,13 @@ private: // Buffer bool start_with(const std::string &a, size_t spos, size_t epos, const std::string &b) const { - if (epos - spos < b.size()) { return false; } + if (epos - spos < b.size()) { + return false; + } for (size_t i = 0; i < b.size(); i++) { - if (a[i + spos] != b[i]) { return false; } + if (a[i + spos] != b[i]) { + return false; + } } return true; } @@ -4463,15 +4787,23 @@ private: while (off < buf_epos_) { auto pos = off; while (true) { - if (pos == buf_epos_) { return buf_size(); } - if (buf_[pos] == c) { break; } + if (pos == buf_epos_) { + return buf_size(); + } + if (buf_[pos] == c) { + break; + } pos++; } auto remaining_size = buf_epos_ - pos; - if (s.size() > remaining_size) { return buf_size(); } + if (s.size() > remaining_size) { + return buf_size(); + } - if (start_with(buf_, pos, buf_epos_, s)) { return pos - buf_spos_; } + if (start_with(buf_, pos, buf_epos_, s)) { + return pos - buf_spos_; + } off = pos + 1; } @@ -4489,7 +4821,9 @@ private: buf_spos_ = 0; buf_epos_ = remaining_size; - if (remaining_size + n > buf_.size()) { buf_.resize(remaining_size + n); } + if (remaining_size + n > buf_.size()) { + buf_.resize(remaining_size + n); + } for (size_t i = 0; i < n; i++) { buf_[buf_epos_ + i] = data[i]; @@ -4588,7 +4922,8 @@ serialize_multipart_formdata(const MultipartFormDataItems &items, body += item.content + serialize_multipart_formdata_item_end(); } - if (finish) body += serialize_multipart_formdata_finish(boundary); + if (finish) + body += serialize_multipart_formdata_finish(boundary); return body; } @@ -4609,7 +4944,9 @@ get_range_offset_and_length(const Request &req, size_t content_length, r.second = slen - 1; } - if (r.second == -1) { r.second = slen - 1; } + if (r.second == -1) { + r.second = slen - 1; + } return std::make_pair(r.first, static_cast(r.second - r.first) + 1); } @@ -4617,9 +4954,13 @@ inline std::string make_content_range_header_field(const std::pair &range, size_t content_length) { std::string field = "bytes "; - if (range.first != -1) { field += std::to_string(range.first); } + if (range.first != -1) { + field += std::to_string(range.first); + } field += "-"; - if (range.second != -1) { field += std::to_string(range.second); } + if (range.second != -1) { + field += std::to_string(range.second); + } field += "/"; field += std::to_string(content_length); return field; @@ -4650,7 +4991,9 @@ bool process_multipart_ranges_data(const Request &req, Response &res, auto offsets = get_range_offset_and_length(req, res.content_length_, i); auto offset = offsets.first; auto length = offsets.second; - if (!content(offset, length)) { return false; } + if (!content(offset, length)) { + return false; + } ctoken("\r\n"); } @@ -4736,7 +5079,9 @@ inline bool expect_content(const Request &req) { inline bool has_crlf(const std::string &s) { auto p = s.c_str(); while (*p) { - if (*p == '\r' || *p == '\n') { return true; } + if (*p == '\r' || *p == '\n') { + return true; + } p++; } return false; @@ -4782,7 +5127,9 @@ inline std::string SHA_512(const std::string &s) { // https://stackoverflow.com/questions/9507184/can-openssl-on-windows-use-the-system-certificate-store inline bool load_system_certs_on_windows(X509_STORE *store) { auto hStore = CertOpenSystemStoreW((HCRYPTPROV_LEGACY)NULL, L"ROOT"); - if (!hStore) { return false; } + if (!hStore) { + return false; + } auto result = false; PCCERT_CONTEXT pContext = NULL; @@ -4811,7 +5158,9 @@ using CFObjectPtr = std::unique_ptr::type, void (*)(CFTypeRef)>; inline void cf_object_ptr_deleter(CFTypeRef obj) { - if (obj) { CFRelease(obj); } + if (obj) { + CFRelease(obj); + } } inline bool retrieve_certs_from_keychain(CFObjectPtr &certs) { @@ -4826,7 +5175,9 @@ inline bool retrieve_certs_from_keychain(CFObjectPtr &certs) { &kCFTypeDictionaryValueCallBacks), cf_object_ptr_deleter); - if (!query) { return false; } + if (!query) { + return false; + } CFTypeRef security_items = nullptr; if (SecItemCopyMatching(query.get(), &security_items) != errSecSuccess || @@ -4854,7 +5205,9 @@ inline bool add_certs_to_x509_store(CFArrayRef certs, X509_STORE *store) { const auto cert = reinterpret_cast( CFArrayGetValueAtIndex(certs, i)); - if (SecCertificateGetTypeID() != CFGetTypeID(cert)) { continue; } + if (SecCertificateGetTypeID() != CFGetTypeID(cert)) { + continue; + } CFDataRef cert_data = nullptr; if (SecItemExport(cert, kSecFormatX509Cert, 0, nullptr, &cert_data) != @@ -4902,11 +5255,13 @@ class WSInit { public: WSInit() { WSADATA wsaData; - if (WSAStartup(0x0002, &wsaData) == 0) is_valid_ = true; + if (WSAStartup(0x0002, &wsaData) == 0) + is_valid_ = true; } ~WSInit() { - if (is_valid_) WSACleanup(); + if (is_valid_) + WSACleanup(); } bool is_valid_ = false; @@ -4940,7 +5295,9 @@ inline std::pair make_digest_authentication_header( } std::string algo = "MD5"; - if (auth.find("algorithm") != auth.end()) { algo = auth.at("algorithm"); } + if (auth.find("algorithm") != auth.end()) { + algo = auth.at("algorithm"); + } std::string response; { @@ -4951,7 +5308,9 @@ inline std::pair make_digest_authentication_header( auto A1 = username + ":" + auth.at("realm") + ":" + password; auto A2 = req.method + ":" + req.path; - if (qop == "auth-int") { A2 += ":" + H(req.body); } + if (qop == "auth-int") { + A2 += ":" + H(req.body); + } if (qop.empty()) { response = H(H(A1) + ":" + auth.at("nonce") + ":" + H(A2)); @@ -5017,7 +5376,7 @@ inline std::string random_string(size_t length) { "ABCDEFGHIJKLMNOPQRSTUVWXYZ" "abcdefghijklmnopqrstuvwxyz"; const size_t max_index = (sizeof(charset) - 1); - return charset[static_cast(std::rand()) % max_index]; + return charset[repertory_rand() % max_index]; }; std::string str(length, 0); std::generate_n(str.begin(), length, randchar); @@ -5043,7 +5402,9 @@ private: inline std::string hosted_at(const std::string &hostname) { std::vector addrs; hosted_at(hostname, addrs); - if (addrs.empty()) { return std::string(); } + if (addrs.empty()) { + return std::string(); + } return addrs[0]; } @@ -5092,10 +5453,16 @@ inline std::pair make_range_header(Ranges ranges) { std::string field = "bytes="; auto i = 0; for (auto r : ranges) { - if (i != 0) { field += ", "; } - if (r.first != -1) { field += std::to_string(r.first); } + if (i != 0) { + field += ", "; + } + if (r.first != -1) { + field += std::to_string(r.first); + } field += '-'; - if (r.second != -1) { field += std::to_string(r.second); } + if (r.second != -1) { + field += std::to_string(r.second); + } i++; } return std::make_pair("Range", std::move(field)); @@ -5148,7 +5515,9 @@ inline std::string Request::get_param_value(const std::string &key, auto rng = params.equal_range(key); auto it = rng.first; std::advance(it, static_cast(id)); - if (it != rng.second) { return it->second; } + if (it != rng.second) { + return it->second; + } return std::string(); } @@ -5168,7 +5537,9 @@ inline bool Request::has_file(const std::string &key) const { inline MultipartFormData Request::get_file_value(const std::string &key) const { auto it = files.find(key); - if (it != files.end()) { return it->second; } + if (it != files.end()) { + return it->second; + } return MultipartFormData(); } @@ -5234,7 +5605,9 @@ inline void Response::set_content_provider( ContentProviderResourceReleaser resource_releaser) { set_header("Content-Type", content_type); content_length_ = in_length; - if (in_length > 0) { content_provider_ = std::move(provider); } + if (in_length > 0) { + content_provider_ = std::move(provider); + } content_provider_resource_releaser_ = resource_releaser; is_chunked_content_provider_ = false; } @@ -5291,10 +5664,12 @@ inline SocketStream::SocketStream(socket_t sock, time_t read_timeout_sec, time_t read_timeout_usec, time_t write_timeout_sec, time_t write_timeout_usec) - : sock_(sock), read_timeout_sec_(read_timeout_sec), + : sock_(sock), + read_timeout_sec_(read_timeout_sec), read_timeout_usec_(read_timeout_usec), write_timeout_sec_(write_timeout_sec), - write_timeout_usec_(write_timeout_usec), read_buff_(read_buff_size_, 0) {} + write_timeout_usec_(write_timeout_usec), + read_buff_(read_buff_size_, 0) {} inline SocketStream::~SocketStream() {} @@ -5329,7 +5704,9 @@ inline ssize_t SocketStream::read(char *ptr, size_t size) { } } - if (!is_readable()) { return -1; } + if (!is_readable()) { + return -1; + } read_buff_off_ = 0; read_buff_content_size_ = 0; @@ -5354,7 +5731,9 @@ inline ssize_t SocketStream::read(char *ptr, size_t size) { } inline ssize_t SocketStream::write(const char *ptr, size_t size) { - if (!is_writable()) { return -1; } + if (!is_writable()) { + return -1; + } #if defined(_WIN32) && !defined(_WIN64) size = @@ -5420,7 +5799,9 @@ inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern) { while (true) { const auto marker_pos = pattern.find(marker, last_param_end); - if (marker_pos == std::string::npos) { break; } + if (marker_pos == std::string::npos) { + break; + } static_fragments_.push_back( pattern.substr(last_param_end, marker_pos - last_param_end)); @@ -5428,7 +5809,9 @@ inline PathParamsMatcher::PathParamsMatcher(const std::string &pattern) { const auto param_name_start = marker_pos + 1; auto sep_pos = pattern.find(separator, param_name_start); - if (sep_pos == std::string::npos) { sep_pos = pattern.length(); } + if (sep_pos == std::string::npos) { + sep_pos = pattern.length(); + } auto param_name = pattern.substr(param_name_start, sep_pos - param_name_start); @@ -5477,10 +5860,14 @@ inline bool PathParamsMatcher::match(Request &request) const { // Should only happen when we have a static fragment after a param // Example: '/users/:id/subscriptions' // The 'subscriptions' fragment here does not have a corresponding param - if (i >= param_names_.size()) { continue; } + if (i >= param_names_.size()) { + continue; + } auto sep_pos = request.path.find(separator, starting_pos); - if (sep_pos == std::string::npos) { sep_pos = request.path.length(); } + if (sep_pos == std::string::npos) { + sep_pos = request.path.length(); + } const auto ¶m_name = param_names_[i]; @@ -5729,7 +6116,8 @@ inline Server &Server::set_payload_max_length(size_t length) { inline bool Server::bind_to_port(const std::string &host, int port, int socket_flags) { - if (bind_internal(host, port, socket_flags) < 0) return false; + if (bind_internal(host, port, socket_flags) < 0) + return false; return true; } inline int Server::bind_to_any_port(const std::string &host, int socket_flags) { @@ -5766,7 +6154,9 @@ inline void Server::stop() { inline bool Server::parse_request_line(const char *s, Request &req) { auto len = strlen(s); - if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { return false; } + if (len < 2 || s[len - 2] != '\r' || s[len - 1] != '\n') { + return false; + } len -= 2; { @@ -5774,24 +6164,37 @@ inline bool Server::parse_request_line(const char *s, Request &req) { detail::split(s, s + len, ' ', [&](const char *b, const char *e) { switch (count) { - case 0: req.method = std::string(b, e); break; - case 1: req.target = std::string(b, e); break; - case 2: req.version = std::string(b, e); break; - default: break; + case 0: + req.method = std::string(b, e); + break; + case 1: + req.target = std::string(b, e); + break; + case 2: + req.version = std::string(b, e); + break; + default: + break; } count++; }); - if (count != 3) { return false; } + if (count != 3) { + return false; + } } static const std::set methods{ "GET", "HEAD", "POST", "PUT", "DELETE", "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"}; - if (methods.find(req.method) == methods.end()) { return false; } + if (methods.find(req.method) == methods.end()) { + return false; + } - if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") { return false; } + if (req.version != "HTTP/1.1" && req.version != "HTTP/1.0") { + return false; + } { // Skip URL fragment @@ -5816,12 +6219,15 @@ inline bool Server::parse_request_line(const char *s, Request &req) { } break; } - default: break; + default: + break; } count++; }); - if (count > 2) { return false; } + if (count > 2) { + return false; + } } return true; @@ -5851,7 +6257,9 @@ inline bool Server::write_response_core(Stream &strm, bool close_connection, std::string content_type; std::string boundary; - if (need_apply_ranges) { apply_ranges(req, res, content_type, boundary); } + if (need_apply_ranges) { + apply_ranges(req, res, content_type, boundary); + } // Prepare additional headers if (close_connection || req.get_header_value("Connection") == "close") { @@ -5877,7 +6285,9 @@ inline bool Server::write_response_core(Stream &strm, bool close_connection, res.set_header("Accept-Ranges", "bytes"); } - if (post_routing_handler_) { post_routing_handler_(req, res); } + if (post_routing_handler_) { + post_routing_handler_(req, res); + } // Response line and headers { @@ -5888,7 +6298,9 @@ inline bool Server::write_response_core(Stream &strm, bool close_connection, return false; } - if (!header_writer_(bstrm, res.headers)) { return false; } + if (!header_writer_(bstrm, res.headers)) { + return false; + } // Flush buffer auto &data = bstrm.get_buffer(); @@ -5913,7 +6325,9 @@ inline bool Server::write_response_core(Stream &strm, bool close_connection, } // Log - if (logger_) { logger_(req, res); } + if (logger_) { + logger_(req, res); + } return ret; } @@ -5975,7 +6389,9 @@ inline bool Server::read_content(Stream &strm, Request &req, Response &res) { strm, req, res, // Regular [&](const char *buf, size_t n) { - if (req.body.size() + n > req.body.max_size()) { return false; } + if (req.body.size() + n > req.body.max_size()) { + return false; + } req.body.append(buf, n); return true; }, @@ -5989,7 +6405,9 @@ inline bool Server::read_content(Stream &strm, Request &req, Response &res) { }, [&](const char *buf, size_t n) { auto &content = cur->second.content; - if (content.size() + n > content.max_size()) { return false; } + if (content.size() + n > content.max_size()) { + return false; + } content.append(buf, n); return true; })) { @@ -6078,7 +6496,9 @@ inline bool Server::handle_file_request(const Request &req, Response &res, std::string sub_path = "/" + req.path.substr(entry.mount_point.size()); if (detail::is_valid_path(sub_path)) { auto path = entry.base_dir + sub_path; - if (path.back() == '/') { path += "index.html"; } + if (path.back() == '/') { + path += "index.html"; + } if (detail::is_file(path)) { for (const auto &kv : entry.headers) { @@ -6086,7 +6506,9 @@ inline bool Server::handle_file_request(const Request &req, Response &res, } auto mm = std::make_shared(path.c_str()); - if (!mm->is_open()) { return false; } + if (!mm->is_open()) { + return false; + } res.set_content_provider( mm->size(), @@ -6120,17 +6542,23 @@ Server::create_server_socket(const std::string &host, int port, if (::bind(sock, ai.ai_addr, static_cast(ai.ai_addrlen))) { return false; } - if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) { return false; } + if (::listen(sock, CPPHTTPLIB_LISTEN_BACKLOG)) { + return false; + } return true; }); } inline int Server::bind_internal(const std::string &host, int port, int socket_flags) { - if (!is_valid()) { return -1; } + if (!is_valid()) { + return -1; + } svr_sock_ = create_server_socket(host, port, socket_flags, socket_options_); - if (svr_sock_ == INVALID_SOCKET) { return -1; } + if (svr_sock_ == INVALID_SOCKET) { + return -1; + } if (port == 0) { struct sockaddr_storage addr; @@ -6286,7 +6714,9 @@ inline bool Server::routing(Request &req, Response &res, Stream &strm) { } // Read content into `req.body` - if (!read_content(strm, req, res)) { return false; } + if (!read_content(strm, req, res)) { + return false; + } } // Regular handler @@ -6458,7 +6888,9 @@ Server::process_request(Stream &strm, bool close_connection, detail::stream_line_reader line_reader(strm, buf.data(), buf.size()); // Connection has been closed on client - if (!line_reader.getline()) { return false; } + if (!line_reader.getline()) { + return false; + } Request req; @@ -6520,7 +6952,9 @@ Server::process_request(Stream &strm, bool close_connection, } } - if (setup_request) { setup_request(req); } + if (setup_request) { + setup_request(req); + } if (req.get_header_value("Expect") == "100-continue") { auto status = 100; @@ -6533,7 +6967,8 @@ Server::process_request(Stream &strm, bool close_connection, strm.write_format("HTTP/1.1 %d %s\r\n\r\n", status, status_message(status)); break; - default: return write_response(strm, close_connection, req, res); + default: + return write_response(strm, close_connection, req, res); } } @@ -6555,9 +6990,15 @@ Server::process_request(Stream &strm, bool close_connection, auto s = e.what(); for (size_t i = 0; s[i]; i++) { switch (s[i]) { - case '\r': val += "\\r"; break; - case '\n': val += "\\n"; break; - default: val += s[i]; break; + case '\r': + val += "\\r"; + break; + case '\n': + val += "\\n"; + break; + default: + val += s[i]; + break; } } res.set_header("EXCEPTION_WHAT", val); @@ -6575,10 +7016,14 @@ Server::process_request(Stream &strm, bool close_connection, #endif if (routed) { - if (res.status == -1) { res.status = req.ranges.empty() ? 200 : 206; } + if (res.status == -1) { + res.status = req.ranges.empty() ? 200 : 206; + } return write_response_with_content(strm, close_connection, req, res); } else { - if (res.status == -1) { res.status = 404; } + if (res.status == -1) { + res.status = 404; + } return write_response(strm, close_connection, req, res); } } @@ -6610,9 +7055,11 @@ inline ClientImpl::ClientImpl(const std::string &host, int port) inline ClientImpl::ClientImpl(const std::string &host, int port, const std::string &client_cert_path, const std::string &client_key_path) - : host_(host), port_(port), + : host_(host), + port_(port), host_and_port_(adjust_host_string(host) + ":" + std::to_string(port)), - client_cert_path_(client_cert_path), client_key_path_(client_key_path) {} + client_cert_path_(client_cert_path), + client_key_path_(client_key_path) {} inline ClientImpl::~ClientImpl() { std::lock_guard guard(socket_mutex_); @@ -6678,7 +7125,8 @@ inline socket_t ClientImpl::create_client_socket(Error &error) const { // Check is custom IP specified for host_ std::string ip; auto it = addr_map_.find(host_); - if (it != addr_map_.end()) ip = it->second; + if (it != addr_map_.end()) + ip = it->second; return detail::create_client_socket( host_, ip, port_, address_family_, tcp_nodelay_, socket_options_, @@ -6690,7 +7138,9 @@ inline socket_t ClientImpl::create_client_socket(Error &error) const { inline bool ClientImpl::create_and_connect_socket(Socket &socket, Error &error) { auto sock = create_client_socket(error); - if (sock == INVALID_SOCKET) { return false; } + if (sock == INVALID_SOCKET) { + return false; + } socket.sock = sock; return true; } @@ -6704,7 +7154,9 @@ inline void ClientImpl::shutdown_ssl(Socket & /*socket*/, } inline void ClientImpl::shutdown_socket(Socket &socket) { - if (socket.sock == INVALID_SOCKET) { return; } + if (socket.sock == INVALID_SOCKET) { + return; + } detail::shutdown_socket(socket.sock); } @@ -6722,7 +7174,9 @@ inline void ClientImpl::close_socket(Socket &socket) { #ifdef CPPHTTPLIB_OPENSSL_SUPPORT assert(socket.ssl == nullptr); #endif - if (socket.sock == INVALID_SOCKET) { return; } + if (socket.sock == INVALID_SOCKET) { + return; + } detail::close_socket(socket.sock); socket.sock = INVALID_SOCKET; } @@ -6733,7 +7187,9 @@ inline bool ClientImpl::read_response_line(Stream &strm, const Request &req, detail::stream_line_reader line_reader(strm, buf.data(), buf.size()); - if (!line_reader.getline()) { return false; } + if (!line_reader.getline()) { + return false; + } #ifdef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR const static std::regex re("(HTTP/1\\.[01]) (\\d{3})(?: (.*?))?\r?\n"); @@ -6751,10 +7207,16 @@ inline bool ClientImpl::read_response_line(Stream &strm, const Request &req, // Ignore '100 Continue' while (res.status == 100) { - if (!line_reader.getline()) { return false; } // CRLF - if (!line_reader.getline()) { return false; } // next response line + if (!line_reader.getline()) { + return false; + } // CRLF + if (!line_reader.getline()) { + return false; + } // next response line - if (!std::regex_match(line_reader.ptr(), m, re)) { return false; } + if (!std::regex_match(line_reader.ptr(), m, re)) { + return false; + } res.version = std::string(m[1]); res.status = std::stoi(std::string(m[2])); res.reason = std::string(m[3]); @@ -6797,7 +7259,9 @@ inline bool ClientImpl::send_(Request &req, Response &res, Error &error) { } if (!is_alive) { - if (!create_and_connect_socket(socket_, error)) { return false; } + if (!create_and_connect_socket(socket_, error)) { + return false; + } #ifdef CPPHTTPLIB_OPENSSL_SUPPORT // TODO: refactoring @@ -6810,7 +7274,9 @@ inline bool ClientImpl::send_(Request &req, Response &res, Error &error) { } } - if (!scli.initialize_ssl(socket_, error)) { return false; } + if (!scli.initialize_ssl(socket_, error)) { + return false; + } } #endif } @@ -6856,7 +7322,9 @@ inline bool ClientImpl::send_(Request &req, Response &res, Error &error) { }); if (!ret) { - if (error == Error::Success) { error = Error::Unknown; } + if (error == Error::Success) { + error = Error::Unknown; + } } return ret; @@ -6896,7 +7364,9 @@ inline bool ClientImpl::handle_request(Stream &strm, Request &req, ret = process_request(strm, req, res, close_connection, error); } - if (!ret) { return false; } + if (!ret) { + return false; + } if (res.get_header_value("Connection") == "close" || (res.version == "HTTP/1.0" && res.reason != "Connection established")) { @@ -6941,7 +7411,9 @@ inline bool ClientImpl::handle_request(Stream &strm, Request &req, Response new_res; ret = send(new_req, new_res, error); - if (ret) { res = new_res; } + if (ret) { + res = new_res; + } } } } @@ -6957,19 +7429,25 @@ inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) { } auto location = res.get_header_value("location"); - if (location.empty()) { return false; } + if (location.empty()) { + return false; + } const static std::regex re( R"((?:(https?):)?(?://(?:\[([\d:]+)\]|([^:/?#]+))(?::(\d+))?)?([^?#]*)(\?[^#]*)?(?:#.*)?)"); std::smatch m; - if (!std::regex_match(location, m, re)) { return false; } + if (!std::regex_match(location, m, re)) { + return false; + } auto scheme = is_ssl() ? "https" : "http"; auto next_scheme = m[1].str(); auto next_host = m[2].str(); - if (next_host.empty()) { next_host = m[3].str(); } + if (next_host.empty()) { + next_host = m[3].str(); + } auto port_str = m[4].str(); auto next_path = m[5].str(); auto next_query = m[6].str(); @@ -6981,9 +7459,15 @@ inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) { next_port = next_scheme == "https" ? 443 : 80; } - if (next_scheme.empty()) { next_scheme = scheme; } - if (next_host.empty()) { next_host = host_; } - if (next_path.empty()) { next_path = "/"; } + if (next_scheme.empty()) { + next_scheme = scheme; + } + if (next_host.empty()) { + next_host = host_; + } + if (next_path.empty()) { + next_path = "/"; + } auto path = detail::decode_url(next_path, true) + next_query; @@ -6994,7 +7478,9 @@ inline bool ClientImpl::redirect(Request &req, Response &res, Error &error) { #ifdef CPPHTTPLIB_OPENSSL_SUPPORT SSLClient cli(next_host.c_str(), next_port); cli.copy_settings(*this); - if (ca_cert_store_) { cli.set_ca_cert_store(ca_cert_store_); } + if (ca_cert_store_) { + cli.set_ca_cert_store(ca_cert_store_); + } return detail::redirect(cli, req, res, path, location, error); #else return false; @@ -7057,7 +7543,9 @@ inline bool ClientImpl::write_request(Stream &strm, Request &req, } } - if (!req.has_header("Accept")) { req.set_header("Accept", "*/*"); } + if (!req.has_header("Accept")) { + req.set_header("Accept", "*/*"); + } #ifndef CPPHTTPLIB_NO_DEFAULT_USER_AGENT if (!req.has_header("User-Agent")) { @@ -7155,10 +7643,14 @@ inline std::unique_ptr ClientImpl::send_with_content_provider( ContentProvider content_provider, ContentProviderWithoutLength content_provider_without_length, const std::string &content_type, Error &error) { - if (!content_type.empty()) { req.set_header("Content-Type", content_type); } + if (!content_type.empty()) { + req.set_header("Content-Type", content_type); + } #ifdef CPPHTTPLIB_ZLIB_SUPPORT - if (compress_) { req.set_header("Content-Encoding", "gzip"); } + if (compress_) { + req.set_header("Content-Encoding", "gzip"); + } #endif #ifdef CPPHTTPLIB_ZLIB_SUPPORT @@ -7250,7 +7742,9 @@ inline Result ClientImpl::send_with_content_provider( inline std::string ClientImpl::adjust_host_string(const std::string &host) const { - if (host.find(':') != std::string::npos) { return "[" + host + "]"; } + if (host.find(':') != std::string::npos) { + return "[" + host + "]"; + } return host; } @@ -7258,7 +7752,9 @@ inline bool ClientImpl::process_request(Stream &strm, Request &req, Response &res, bool close_connection, Error &error) { // Send request - if (!write_request(strm, req, close_connection, error)) { return false; } + if (!write_request(strm, req, close_connection, error)) { + return false; + } #ifdef CPPHTTPLIB_OPENSSL_SUPPORT if (is_ssl()) { @@ -7296,9 +7792,13 @@ inline bool ClientImpl::process_request(Stream &strm, Request &req, req.content_receiver ? static_cast( [&](const char *buf, size_t n, uint64_t off, uint64_t len) { - if (redirect) { return true; } + if (redirect) { + return true; + } auto ret = req.content_receiver(buf, n, off, len); - if (!ret) { error = Error::Canceled; } + if (!ret) { + error = Error::Canceled; + } return ret; }) : static_cast( @@ -7312,9 +7812,13 @@ inline bool ClientImpl::process_request(Stream &strm, Request &req, }); auto progress = [&](uint64_t current, uint64_t total) { - if (!req.progress || redirect) { return true; } + if (!req.progress || redirect) { + return true; + } auto ret = req.progress(current, total); - if (!ret) { error = Error::Canceled; } + if (!ret) { + error = Error::Canceled; + } return ret; }; @@ -7322,13 +7826,17 @@ inline bool ClientImpl::process_request(Stream &strm, Request &req, if (!detail::read_content(strm, res, (std::numeric_limits::max)(), dummy_status, std::move(progress), std::move(out), decompress_)) { - if (error != Error::Canceled) { error = Error::Read; } + if (error != Error::Canceled) { + error = Error::Read; + } return false; } } // Log - if (logger_) { logger_(req, res); } + if (logger_) { + logger_(req, res); + } return true; } @@ -7475,7 +7983,9 @@ inline Result ClientImpl::Get(const std::string &path, const Headers &headers, inline Result ClientImpl::Get(const std::string &path, const Params ¶ms, const Headers &headers, Progress progress) { - if (params.empty()) { return Get(path, headers); } + if (params.empty()) { + return Get(path, headers); + } std::string path_with_query = append_query_params(path, params); return Get(path_with_query.c_str(), headers, progress); @@ -7823,7 +8333,9 @@ inline Result ClientImpl::Delete(const std::string &path, req.headers = headers; req.path = path; - if (!content_type.empty()) { req.set_header("Content-Type", content_type); } + if (!content_type.empty()) { + req.set_header("Content-Type", content_type); + } req.body.assign(body, content_length); return send_(std::move(req)); @@ -7998,7 +8510,8 @@ inline void ClientImpl::set_ca_cert_store(X509_STORE *ca_cert_store) { inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert, std::size_t size) { auto mem = BIO_new_mem_buf(ca_cert, static_cast(size)); - if (!mem) return nullptr; + if (!mem) + return nullptr; auto inf = PEM_X509_INFO_read_bio(mem, nullptr, nullptr, nullptr); if (!inf) { @@ -8010,10 +8523,16 @@ inline X509_STORE *ClientImpl::create_ca_cert_store(const char *ca_cert, if (cts) { for (auto i = 0; i < static_cast(sk_X509_INFO_num(inf)); i++) { auto itmp = sk_X509_INFO_value(inf, i); - if (!itmp) { continue; } + if (!itmp) { + continue; + } - if (itmp->x509) { X509_STORE_add_cert(cts, itmp->x509); } - if (itmp->crl) { X509_STORE_add_crl(cts, itmp->crl); } + if (itmp->x509) { + X509_STORE_add_cert(cts, itmp->x509); + } + if (itmp->crl) { + X509_STORE_add_crl(cts, itmp->crl); + } } } @@ -8074,7 +8593,9 @@ inline void ssl_delete(std::mutex &ctx_mutex, SSL *ssl, // the remote has closed the network connection // Note that it is not always possible to avoid SIGPIPE, this is merely a // best-efforts. - if (shutdown_gracefully) { SSL_shutdown(ssl); } + if (shutdown_gracefully) { + SSL_shutdown(ssl); + } std::lock_guard guard(ctx_mutex); SSL_free(ssl); @@ -8090,12 +8611,17 @@ bool ssl_connect_or_accept_nonblocking(socket_t sock, SSL *ssl, auto err = SSL_get_error(ssl, res); switch (err) { case SSL_ERROR_WANT_READ: - if (select_read(sock, timeout_sec, timeout_usec) > 0) { continue; } + if (select_read(sock, timeout_sec, timeout_usec) > 0) { + continue; + } break; case SSL_ERROR_WANT_WRITE: - if (select_write(sock, timeout_sec, timeout_usec) > 0) { continue; } + if (select_write(sock, timeout_sec, timeout_usec) > 0) { + continue; + } + break; + default: break; - default: break; } return false; } @@ -8141,7 +8667,9 @@ inline SSLSocketStream::SSLSocketStream(socket_t sock, SSL *ssl, time_t read_timeout_usec, time_t write_timeout_sec, time_t write_timeout_usec) - : sock_(sock), ssl_(ssl), read_timeout_sec_(read_timeout_sec), + : sock_(sock), + ssl_(ssl), + read_timeout_sec_(read_timeout_sec), read_timeout_usec_(read_timeout_usec), write_timeout_sec_(write_timeout_sec), write_timeout_usec_(write_timeout_usec) { @@ -8179,7 +8707,9 @@ inline ssize_t SSLSocketStream::read(char *ptr, size_t size) { } else if (is_readable()) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); ret = SSL_read(ssl_, ptr, static_cast(size)); - if (ret >= 0) { return ret; } + if (ret >= 0) { + return ret; + } err = SSL_get_error(ssl_, ret); } else { return -1; @@ -8210,7 +8740,9 @@ inline ssize_t SSLSocketStream::write(const char *ptr, size_t size) { if (is_writable()) { std::this_thread::sleep_for(std::chrono::milliseconds(1)); ret = SSL_write(ssl_, ptr, static_cast(handle_size)); - if (ret >= 0) { return ret; } + if (ret >= 0) { + return ret; + } err = SSL_get_error(ssl_, ret); } else { return -1; @@ -8310,7 +8842,9 @@ inline SSLServer::SSLServer( } inline SSLServer::~SSLServer() { - if (ctx_) { SSL_CTX_free(ctx_); } + if (ctx_) { + SSL_CTX_free(ctx_); + } } inline bool SSLServer::is_valid() const { return ctx_; } @@ -8398,7 +8932,9 @@ inline SSLClient::SSLClient(const std::string &host, int port, } inline SSLClient::~SSLClient() { - if (ctx_) { SSL_CTX_free(ctx_); } + if (ctx_) { + SSL_CTX_free(ctx_); + } // Make sure to shut down SSL since shutdown_ssl will resolve to the // base function rather than the derived function once we get to the // base class destructor, and won't free the SSL (causing a leak). @@ -8529,7 +9065,9 @@ inline bool SSLClient::load_certs() { loaded = detail::load_system_certs_on_macos(SSL_CTX_get_cert_store(ctx_)); #endif // TARGET_OS_OSX #endif // _WIN32 - if (!loaded) { SSL_CTX_set_default_verify_paths(ctx_); } + if (!loaded) { + SSL_CTX_set_default_verify_paths(ctx_); + } } }); @@ -8690,7 +9228,9 @@ SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const { auto name_len = static_cast(ASN1_STRING_length(val->d.ia5)); switch (type) { - case GEN_DNS: dsn_matched = check_host_name(name, name_len); break; + case GEN_DNS: + dsn_matched = check_host_name(name, name_len); + break; case GEN_IPADD: if (!memcmp(&addr6, name, addr_len) || @@ -8702,7 +9242,9 @@ SSLClient::verify_host_with_subject_alt_name(X509 *server_cert) const { } } - if (dsn_matched || ip_matched) { ret = true; } + if (dsn_matched || ip_matched) { + ret = true; + } } GENERAL_NAMES_free(const_cast( @@ -8728,7 +9270,9 @@ inline bool SSLClient::verify_host_with_common_name(X509 *server_cert) const { inline bool SSLClient::check_host_name(const char *pattern, size_t pattern_len) const { - if (host_.size() == pattern_len && host_ == pattern) { return true; } + if (host_.size() == pattern_len && host_ == pattern) { + return true; + } // Wildcard match // https://bugs.launchpad.net/ubuntu/+source/firefox-3.0/+bug/376484 @@ -8738,7 +9282,9 @@ inline bool SSLClient::check_host_name(const char *pattern, pattern_components.emplace_back(std::string(b, e)); }); - if (host_components_.size() != pattern_components.size()) { return false; } + if (host_components_.size() != pattern_components.size()) { + return false; + } auto itr = pattern_components.begin(); for (const auto &h : host_components_) { @@ -8746,7 +9292,9 @@ inline bool SSLClient::check_host_name(const char *pattern, if (p != h && p != "*") { auto partial_match = (p.size() > 0 && p[p.size() - 1] == '*' && !p.compare(0, p.size() - 1, h)); - if (!partial_match) { return false; } + if (!partial_match) { + return false; + } } ++itr; } @@ -8784,7 +9332,9 @@ inline Client::Client(const std::string &scheme_host_port, auto is_ssl = scheme == "https"; auto host = m[2].str(); - if (host.empty()) { host = m[3].str(); } + if (host.empty()) { + host = m[3].str(); + } auto port_str = m[4].str(); auto port = !port_str.empty() ? std::stoi(port_str) : (is_ssl ? 443 : 80); @@ -9246,7 +9796,9 @@ inline long Client::get_openssl_verify_result() const { } inline SSL_CTX *Client::ssl_context() const { - if (is_ssl_) { return static_cast(*cli_).ssl_context(); } + if (is_ssl_) { + return static_cast(*cli_).ssl_context(); + } return nullptr; } #endif diff --git a/include/common.hpp b/include/common.hpp index 4731e1e8..24556966 100644 --- a/include/common.hpp +++ b/include/common.hpp @@ -82,7 +82,6 @@ #include #include #include -#include #include #include #include @@ -90,6 +89,14 @@ #include #include +#include +template +[[nodiscard]] constexpr auto repertory_rand() -> data_type { + data_type ret{}; + randombytes_buf(&ret, sizeof(ret)); + return ret; +} + #include #include #include @@ -116,7 +123,6 @@ #endif #include -#include #define CPPHTTPLIB_TCP_NODELAY true #define CPPHTTPLIB_OPENSSL_SUPPORT @@ -136,12 +142,12 @@ using json = nlohmann::json; #define REPERTORY_API_INVALID_HANDLE static_cast(-1) using native_handle = HANDLE; #else -#define REPERTORY_INVALID_HANDLE -1 +#define REPERTORY_INVALID_HANDLE (-1) #define REPERTORY_API_INVALID_HANDLE REPERTORY_INVALID_HANDLE using native_handle = int; #endif -#define NANOS_PER_SECOND 1000000000L +constexpr const auto NANOS_PER_SECOND = 1000000000L; #ifdef _WIN32 #ifdef CreateDirectory @@ -339,6 +345,7 @@ using WCHAR = wchar_t; #define STATUS_OBJECT_NAME_NOT_FOUND std::int32_t(0xC0000034L) #define STATUS_OBJECT_PATH_INVALID std::int32_t(0xC0000039L) #define STATUS_UNEXPECTED_IO_ERROR std::int32_t(0xC00000E9L) + #define CONVERT_STATUS_NOT_IMPLEMENTED(e) \ ((std::int32_t(e) == STATUS_NOT_IMPLEMENTED) ? -ENOTSUP : e) diff --git a/include/events/event.hpp b/include/events/event.hpp index 9e8ff9c5..ceac3978 100644 --- a/include/events/event.hpp +++ b/include/events/event.hpp @@ -23,7 +23,13 @@ #define INCLUDE_EVENTS_EVENT_HPP_ namespace repertory { -enum class event_level { error, warn, normal, debug, verbose }; +enum class event_level { + error, + warn, + normal, + debug, + verbose, +}; auto event_level_from_string(std::string level) -> event_level; @@ -37,10 +43,14 @@ protected: : allow_async_(allow_async), ss_(ss.str()), j_(std::move(j)) {} public: + event(const event &) = delete; + event(event &&) = delete; + auto operator=(const event &) -> event & = delete; + auto operator=(event &&) -> event & = delete; virtual ~event() = default; private: - const bool allow_async_; + bool allow_async_; protected: std::stringstream ss_; diff --git a/include/types/remote.hpp b/include/types/remote.hpp index 4e8e7228..24f583ad 100644 --- a/include/types/remote.hpp +++ b/include/types/remote.hpp @@ -22,8 +22,8 @@ #ifndef INCLUDE_TYPES_REMOTE_HPP_ #define INCLUDE_TYPES_REMOTE_HPP_ -#define PACKET_SERVICE_FUSE std::uint32_t(1) -#define PACKET_SERVICE_WINFSP std::uint32_t(2) +#define PACKET_SERVICE_FUSE 1U +#define PACKET_SERVICE_WINFSP 2U #ifdef _WIN32 #define PACKET_SERVICE_FLAGS PACKET_SERVICE_WINFSP @@ -44,48 +44,51 @@ using group_id = std::uint32_t; using user_id = std::uint32_t; enum class open_flags : std::uint32_t { - read_only = 0u, - write_only = 1u, - read_write = 2u, - create = 4u, - excl = 8u, - no_ctty = 16u, - truncate = 32u, - append = 64u, - non_blocking = 128u, - sync = 256u, - async = 512u, - directory = 1024u, - no_follow = 2048u, - clo_exec = 4096u, - direct = 8192u, - no_atime = 16384u, - path = 32768u, - temp_file = 65536u, - dsync = 131072u, + read_only = 0U, + write_only = 1U, + read_write = 2U, + create = 4U, + excl = 8U, + no_ctty = 16U, + truncate = 32U, + append = 64U, + non_blocking = 128U, + sync = 256U, + async = 512U, + directory = 1024U, + no_follow = 2048U, + clo_exec = 4096U, + direct = 8192U, + no_atime = 16384U, + path = 32768U, + temp_file = 65536U, + dsync = 131072U, }; -inline auto operator|(const open_flags &a, const open_flags &b) -> open_flags { +inline auto operator|(const open_flags &flag_1, const open_flags &flag_2) + -> open_flags { using t = std::underlying_type_t; - return static_cast(static_cast(a) | static_cast(b)); + return static_cast(static_cast(flag_1) | + static_cast(flag_2)); } #ifdef __GNUG__ __attribute__((unused)) #endif inline auto -operator|=(open_flags &a, const open_flags &b) -> open_flags & { - a = a | b; - return a; +operator|=(open_flags &flag_1, const open_flags &flag_2) -> open_flags & { + flag_1 = flag_1 | flag_2; + return flag_1; } #ifdef __GNUG__ __attribute__((unused)) #endif inline auto -operator&(const open_flags &a, const open_flags &b) -> open_flags { +operator&(const open_flags &flag_1, const open_flags &flag_2) -> open_flags { using t = std::underlying_type_t; - return static_cast(static_cast(a) & static_cast(b)); + return static_cast(static_cast(flag_1) & + static_cast(flag_2)); } #pragma pack(1) diff --git a/include/utils/utils.hpp b/include/utils/utils.hpp index 016cf20a..d3106552 100644 --- a/include/utils/utils.hpp +++ b/include/utils/utils.hpp @@ -38,11 +38,13 @@ void calculate_allocation_size(bool directory, std::uint64_t file_size, template [[nodiscard]] auto collection_excludes(t collection, - const typename t::value_type &v) -> bool; + const typename t::value_type &val) + -> bool; template [[nodiscard]] auto collection_includes(t collection, - const typename t::value_type &v) -> bool; + const typename t::value_type &val) + -> bool; [[nodiscard]] auto compare_version_strings(std::string version1, std::string version2) -> int; @@ -53,7 +55,8 @@ template [[nodiscard]] auto create_uuid_string() -> std::string; -[[nodiscard]] auto create_volume_label(const provider_type &pt) -> std::string; +[[nodiscard]] auto create_volume_label(const provider_type &prov) + -> std::string; template [[nodiscard]] auto divide_with_ceiling(const t &n, const t &d) -> t; @@ -66,7 +69,7 @@ template -> std::string; template -[[nodiscard]] auto from_hex_string(const std::string &str, t &v) -> bool; +[[nodiscard]] auto from_hex_string(const std::string &str, t &val) -> bool; [[nodiscard]] auto generate_random_string(std::uint16_t length) -> std::string; @@ -77,7 +80,7 @@ template [[nodiscard]] auto get_file_time_now() -> std::uint64_t; -void get_local_time_now(struct tm &localTime); +void get_local_time_now(struct tm &local_time); [[nodiscard]] auto get_next_available_port(std::uint16_t first_port, std::uint16_t &available_port) @@ -85,11 +88,12 @@ void get_local_time_now(struct tm &localTime); [[nodiscard]] auto get_time_now() -> std::uint64_t; -template -[[nodiscard]] auto random_between(const t &begin, const t &end) -> t; +template +[[nodiscard]] auto random_between(const data_type &begin, const data_type &end) + -> data_type; template -void remove_element_from(t &v, const typename t::value_type &value); +void remove_element_from(t &collection, const typename t::value_type &val); [[nodiscard]] auto reset_curl(CURL *curl_handle) -> CURL *; @@ -97,28 +101,30 @@ void remove_element_from(t &v, const typename t::value_type &value); -> bool; void spin_wait_for_mutex(std::function complete, - std::condition_variable &cv, std::mutex &mtx, - const std::string &txt = ""); + std::condition_variable &cond, std::mutex &mtx, + const std::string &text = ""); -void spin_wait_for_mutex(bool &complete, std::condition_variable &cv, - std::mutex &mtx, const std::string &txt = ""); +void spin_wait_for_mutex(bool &complete, std::condition_variable &cond, + std::mutex &mtx, const std::string &text = ""); template -[[nodiscard]] auto to_hex_string(const t &v) -> std::string; +[[nodiscard]] auto to_hex_string(const t &val) -> std::string; // template implementations template [[nodiscard]] auto collection_excludes(t collection, - const typename t::value_type &v) + const typename t::value_type &val) -> bool { - return std::find(collection.begin(), collection.end(), v) == collection.end(); + return std::find(collection.begin(), collection.end(), val) == + collection.end(); } template [[nodiscard]] auto collection_includes(t collection, - const typename t::value_type &v) + const typename t::value_type &val) -> bool { - return std::find(collection.begin(), collection.end(), v) != collection.end(); + return std::find(collection.begin(), collection.end(), val) != + collection.end(); } template @@ -127,12 +133,14 @@ template } template -[[nodiscard]] auto from_hex_string(const std::string &str, t &v) -> bool { - v.clear(); - if (not(str.length() % 2u)) { - for (std::size_t i = 0u; i < str.length(); i += 2u) { - v.emplace_back(static_cast( - strtol(str.substr(i, 2u).c_str(), nullptr, 16))); +[[nodiscard]] auto from_hex_string(const std::string &str, t &val) -> bool { + static constexpr const auto base16 = 16; + + val.clear(); + if (not(str.length() % 2U)) { + for (std::size_t i = 0U; i < str.length(); i += 2U) { + val.emplace_back(static_cast( + strtol(str.substr(i, 2U).c_str(), nullptr, base16))); } return true; } @@ -140,30 +148,32 @@ template return false; } -template -[[nodiscard]] auto random_between(const t &begin, const t &end) -> t { - srand(static_cast(get_time_now())); - return begin + static_cast(rand()) % ((end + 1) - begin); +template +[[nodiscard]] auto random_between(const data_type &begin, const data_type &end) + -> data_type { + return begin + repertory_rand() % ((end + 1) - begin); } template -void remove_element_from(t &v, const typename t::value_type &value) { - v.erase(std::remove(v.begin(), v.end(), value), v.end()); +void remove_element_from(t &collection, const typename t::value_type &value) { + collection.erase(std::remove(collection.begin(), collection.end(), value), + collection.end()); } template [[nodiscard]] auto to_hex_string(const t &value) -> std::string { std::string ret{}; - std::array h{}; + std::array tmp{}; for (const auto &num : value) { #ifdef _WIN32 sprintf_s(h.data(), h.size() - 1U, "%x", static_cast(num)); #else - sprintf(h.data(), "%x", static_cast(num)); + sprintf(tmp.data(), "%x", static_cast(num)); #endif - ret += (strlen(h.data()) == 1) ? std::string("0") + h.data() : h.data(); + ret += + (strlen(tmp.data()) == 1) ? std::string("0") + tmp.data() : tmp.data(); } return ret; diff --git a/src/common.cpp.in b/src/common.cpp.in index 68f886e5..cdd71f92 100644 --- a/src/common.cpp.in +++ b/src/common.cpp.in @@ -20,6 +20,7 @@ SOFTWARE. */ #include "types/repertory.hpp" +#include "utils/utils.hpp" namespace repertory { auto get_repertory_git_revision() -> const std::string & { diff --git a/src/drives/fuse/remotefuse/remote_server.cpp b/src/drives/fuse/remotefuse/remote_server.cpp index 0a70bc14..5a26b0ea 100644 --- a/src/drives/fuse/remotefuse/remote_server.cpp +++ b/src/drives/fuse/remotefuse/remote_server.cpp @@ -601,11 +601,11 @@ auto remote_server::fuse_read(const char *path, char *buffer, const remote::file_handle &handle) -> packet::error_type { const auto file_path = construct_path(path); - auto &b = *reinterpret_cast(buffer); + auto &data = *reinterpret_cast(buffer); auto res = has_open_info(static_cast(handle), EBADF); if (res == 0) { - b.resize(read_size); - res = pread64(static_cast(handle), &b[0], read_size, + data.resize(read_size); + res = pread64(static_cast(handle), data.data(), read_size, static_cast(read_offset)); } @@ -630,7 +630,7 @@ auto remote_server::fuse_rename(const char *from, const char *to) auto remote_server::fuse_readdir(const char *path, const remote::file_offset &offset, const remote::file_handle &handle, - std::string &itemPath) -> packet::error_type { + std::string &item_path) -> packet::error_type { const auto file_path = construct_path(path); auto res = 0; if (offset > std::numeric_limits::max()) { @@ -639,7 +639,7 @@ auto remote_server::fuse_readdir(const char *path, } else { auto *iterator = reinterpret_cast(handle); if (iterator) { - res = iterator->get(static_cast(offset), itemPath); + res = iterator->get(static_cast(offset), item_path); } else { res = -1; errno = EFAULT; diff --git a/src/types/remote.cpp b/src/types/remote.cpp index d043b457..7014f355 100644 --- a/src/types/remote.cpp +++ b/src/types/remote.cpp @@ -26,160 +26,92 @@ namespace repertory::remote { auto create_open_flags(std::uint32_t flags) -> open_flags { open_flags ret{}; { - const auto f = (flags & 3u); - ret |= (f == 1u) ? open_flags::write_only - : (f == 2u) ? open_flags::read_write - : open_flags::read_only; - } - if (flags & static_cast(O_CREAT)) { - ret |= open_flags::create; + const auto val = (flags & 3U); + ret |= (val == 1U) ? open_flags::write_only + : (val == 2U) ? open_flags::read_write + : open_flags::read_only; } - if (flags & static_cast(O_EXCL)) { - ret |= open_flags::excl; - } + const auto set_if_has_flag = [&flags, &ret](auto flag, open_flags o_flag) { + if ((flags & static_cast(flag)) != 0U) { + ret |= o_flag; + } + }; - if (flags & static_cast(O_NOCTTY)) { - ret |= open_flags::no_ctty; - } - - if (flags & static_cast(O_TRUNC)) { - ret |= open_flags::truncate; - } - - if (flags & static_cast(O_APPEND)) { - ret |= open_flags::append; - } - - if (flags & static_cast(O_NONBLOCK)) { - ret |= open_flags::non_blocking; - } - - if (flags & static_cast(O_SYNC)) { - ret |= open_flags::sync; - } - - if (flags & static_cast(O_ASYNC)) { - ret |= open_flags::async; - } - - if (flags & static_cast(O_DIRECTORY)) { - ret |= open_flags::directory; - } - - if (flags & static_cast(O_NOFOLLOW)) { - ret |= open_flags::no_follow; - } - - if (flags & static_cast(O_CLOEXEC)) { - ret |= open_flags::clo_exec; - } + set_if_has_flag(O_APPEND, open_flags::append); + set_if_has_flag(O_ASYNC, open_flags::async); + set_if_has_flag(O_CLOEXEC, open_flags::clo_exec); + set_if_has_flag(O_CREAT, open_flags::create); #ifdef O_DIRECT - if (flags & static_cast(O_DIRECT)) { - ret |= open_flags::direct; - } -#endif -#ifdef O_NOATIME - if (flags & static_cast(O_NOATIME)) { - ret |= open_flags::no_atime; - } -#endif -#ifdef O_PATH - if (flags & static_cast(O_PATH)) { - ret |= open_flags::path; - } -#endif -#ifdef O_TMPFILE - if (flags & static_cast(O_TMPFILE)) { - ret |= open_flags::temp_file; - } + set_if_has_flag(O_DIRECT, open_flags::direct); #endif + set_if_has_flag(O_DIRECTORY, open_flags::directory); #ifdef O_DSYNC - if (flags & static_cast(O_DSYNC)) { - ret |= open_flags::dsync; - } + set_if_has_flag(O_DSYNC, open_flags::dsync); #endif + set_if_has_flag(O_EXCL, open_flags::excl); +#ifdef O_NOATIME + set_if_has_flag(O_NOATIME, open_flags::no_atime); +#endif + set_if_has_flag(O_NOCTTY, open_flags::no_ctty); + set_if_has_flag(O_NOFOLLOW, open_flags::no_follow); + set_if_has_flag(O_NONBLOCK, open_flags::non_blocking); +#ifdef O_PATH + set_if_has_flag(O_PATH, open_flags::path); +#endif + set_if_has_flag(O_SYNC, open_flags::sync); +#ifdef O_TMPFILE + set_if_has_flag(O_TMPFILE, open_flags::temp_file); +#endif + set_if_has_flag(O_TRUNC, open_flags::truncate); + return ret; } auto create_os_open_flags(const open_flags &flags) -> std::uint32_t { - std::uint32_t ret = 0u; - if ((flags & open_flags::read_write) == open_flags::read_write) { - ret |= static_cast(O_RDWR); - } else if ((flags & open_flags::write_only) == open_flags::write_only) { - ret |= static_cast(O_WRONLY); - } else { - ret |= static_cast(O_RDONLY); + std::uint32_t ret{}; + const auto set_if_has_flag = [&flags, &ret](auto o_flag, auto flag) -> bool { + if ((flags & o_flag) == o_flag) { + ret |= static_cast(flag); + return true; + } + + return false; + }; + + if (not set_if_has_flag(open_flags::read_write, O_RDWR)) { + if (not set_if_has_flag(open_flags::write_only, O_WRONLY)) { + ret |= static_cast(O_RDONLY); + } } - if ((flags & open_flags::create) == open_flags::create) { - ret |= static_cast(O_CREAT); - } - - if ((flags & open_flags::excl) == open_flags::excl) { - ret |= static_cast(O_EXCL); - } - - if ((flags & open_flags::no_ctty) == open_flags::no_ctty) { - ret |= static_cast(O_NOCTTY); - } - - if ((flags & open_flags::truncate) == open_flags::truncate) { - ret |= static_cast(O_TRUNC); - } - - if ((flags & open_flags::append) == open_flags::append) { - ret |= static_cast(O_APPEND); - } - - if ((flags & open_flags::non_blocking) == open_flags::non_blocking) { - ret |= static_cast(O_NONBLOCK); - } - - if ((flags & open_flags::sync) == open_flags::sync) { - ret |= static_cast(O_SYNC); - } - - if ((flags & open_flags::async) == open_flags::async) { - ret |= static_cast(O_ASYNC); - } - - if ((flags & open_flags::directory) == open_flags::directory) { - ret |= static_cast(O_DIRECTORY); - } - - if ((flags & open_flags::no_follow) == open_flags::no_follow) { - ret |= static_cast(O_NOFOLLOW); - } - - if ((flags & open_flags::clo_exec) == open_flags::clo_exec) { - ret |= static_cast(O_CLOEXEC); - } + set_if_has_flag(open_flags::append, O_APPEND); + set_if_has_flag(open_flags::async, O_ASYNC); + set_if_has_flag(open_flags::clo_exec, O_CLOEXEC); + set_if_has_flag(open_flags::create, O_CREAT); #ifdef O_DIRECT - if ((flags & open_flags::direct) == open_flags::direct) { - ret |= static_cast(O_DIRECT); - } -#endif -#ifdef O_NOATIME - if ((flags & open_flags::no_atime) == open_flags::no_atime) { - ret |= static_cast(O_NOATIME); - } -#endif -#ifdef O_PATH - if ((flags & open_flags::path) == open_flags::path) { - ret |= static_cast(O_PATH); - } -#endif -#ifdef O_TMPFILE - if ((flags & open_flags::temp_file) == open_flags::temp_file) { - ret |= static_cast(O_TMPFILE); - } + set_if_has_flag(open_flags::direct, O_DIRECT); #endif + set_if_has_flag(open_flags::directory, O_DIRECTORY); #ifdef O_DSYNC - if ((flags & open_flags::dsync) == open_flags::dsync) { - ret |= static_cast(O_DSYNC); - } + set_if_has_flag(open_flags::dsync, O_DSYNC); #endif + set_if_has_flag(open_flags::excl, O_EXCL); +#ifdef O_NOATIME + set_if_has_flag(open_flags::no_atime, O_NOATIME); +#endif + set_if_has_flag(open_flags::no_ctty, O_NOCTTY); + set_if_has_flag(open_flags::no_follow, O_NOFOLLOW); + set_if_has_flag(open_flags::non_blocking, O_NONBLOCK); +#ifdef O_PATH + set_if_has_flag(open_flags::path, O_PATH); +#endif + set_if_has_flag(open_flags::sync, O_SYNC); +#ifdef O_TMPFILE + set_if_has_flag(open_flags::temp_file, O_TMPFILE); +#endif + set_if_has_flag(open_flags::truncate, O_TRUNC); + return ret; } #endif diff --git a/src/utils/utils.cpp b/src/utils/utils.cpp index 750a2a3d..d684dc87 100644 --- a/src/utils/utils.cpp +++ b/src/utils/utils.cpp @@ -44,7 +44,7 @@ void calculate_allocation_size(bool directory, std::uint64_t file_size, allocation_size = file_size; } allocation_size = - ((allocation_size == 0u) ? WINFSP_ALLOCATION_UNIT : allocation_size); + ((allocation_size == 0U) ? WINFSP_ALLOCATION_UNIT : allocation_size); allocation_size = utils::divide_with_ceiling(allocation_size, WINFSP_ALLOCATION_UNIT) * WINFSP_ALLOCATION_UNIT; @@ -55,18 +55,18 @@ auto calculate_read_size(const uint64_t &total_size, std::size_t read_size, const uint64_t &offset) -> std::size_t { return static_cast( ((offset + read_size) > total_size) - ? ((offset < total_size) ? total_size - offset : 0u) + ? ((offset < total_size) ? total_size - offset : 0U) : read_size); } auto compare_version_strings(std::string version1, std::string version2) -> int { if (utils::string::contains(version1, "-")) { - version1 = utils::string::split(version1, '-')[0u]; + version1 = utils::string::split(version1, '-')[0U]; } if (utils::string::contains(version2, "-")) { - version2 = utils::string::split(version2, '-')[0u]; + version2 = utils::string::split(version2, '-')[0U]; } auto nums1 = utils::string::split(version1, '.'); @@ -80,11 +80,11 @@ auto compare_version_strings(std::string version1, std::string version2) nums1.emplace_back("0"); } - for (std::size_t i = 0u; i < nums1.size(); i++) { + for (std::size_t i = 0U; i < nums1.size(); i++) { const auto int1 = utils::string::to_uint32(nums1[i]); const auto int2 = utils::string::to_uint32(nums2[i]); const auto res = std::memcmp(&int1, &int2, sizeof(int1)); - if (res) { + if (res != 0) { return res; } } @@ -105,15 +105,15 @@ auto convert_api_date(const std::string &date) -> std::uint64_t { #else strptime(date_time.c_str(), "%Y-%m-%dT%T", &tm1); #endif - return nanos + (mktime(&tm1) * NANOS_PER_SECOND); + return nanos + (static_cast(mktime(&tm1)) * NANOS_PER_SECOND); } auto create_curl() -> CURL * { static std::recursive_mutex mtx; - unique_recur_mutex_lock l(mtx); + unique_recur_mutex_lock lock(mtx); curl_global_init(CURL_GLOBAL_DEFAULT); - l.unlock(); + lock.unlock(); return reset_curl(curl_easy_init()); } @@ -132,9 +132,9 @@ auto create_uuid_string() -> std::string { return ret; #else #if __linux__ - uuid id; - id.make(UUID_MAKE_V4); - return id.string(); + uuid guid; + guid.make(UUID_MAKE_V4); + return guid.string(); #else uuid_t guid; uuid_generate_random(guid); @@ -148,8 +148,8 @@ auto create_uuid_string() -> std::string { #endif } -auto create_volume_label(const provider_type &pt) -> std::string { - return "repertory_" + app_config::get_provider_name(pt); +auto create_volume_label(const provider_type &prov) -> std::string { + return "repertory_" + app_config::get_provider_name(prov); } auto download_type_from_string(std::string type, @@ -158,9 +158,13 @@ auto download_type_from_string(std::string type, type = utils::string::to_lower(utils::string::trim(type)); if (type == "direct") { return download_type::direct; - } else if (type == "fallback") { + } + + if (type == "fallback") { return download_type::fallback; - } else if (type == "ring_buffer") { + } + + if (type == "ring_buffer") { return download_type::ring_buffer; } @@ -192,20 +196,18 @@ auto filetime_to_unix_time(const FILETIME &ft) -> remote::file_time { } void unix_time_to_filetime(const remote::file_time &ts, FILETIME &ft) { - const auto winTime = (ts / 100ull) + 116444736000000000ull; - ft.dwHighDateTime = winTime >> 32u; - ft.dwLowDateTime = winTime & 0xFFFFFFFF; + const auto win_time = (ts / 100ULl) + 116444736000000000ull; + ft.dwHighDateTime = win_time >> 32u; + ft.dwLowDateTime = win_time & 0xFFFFFFFF; } #endif auto generate_random_string(std::uint16_t length) -> std::string { - srand(static_cast(get_time_now())); - std::string ret; ret.resize(length); - for (std::uint16_t i = 0u; i < length; i++) { + for (std::uint16_t i = 0U; i < length; i++) { do { - ret[i] = static_cast(rand() % 74 + 48); + ret[i] = static_cast(repertory_rand() % 74 + 48); } while (((ret[i] >= 91) && (ret[i] <= 96)) || ((ret[i] >= 58) && (ret[i] <= 64))); } @@ -219,17 +221,21 @@ auto get_attributes_from_meta(const api_meta_map &meta) -> DWORD { auto get_environment_variable(const std::string &variable) -> std::string { #ifdef _WIN32 - std::string value; + std::string val; auto sz = ::GetEnvironmentVariable(&variable[0], nullptr, 0); if (sz > 0) { - value.resize(sz); - ::GetEnvironmentVariable(&variable[0], &value[0], sz); + val.resize(sz); + ::GetEnvironmentVariable(&variable[0], &val[0], sz); } return value.c_str(); #else - const auto *v = getenv(variable.c_str()); - return std::string(v ? v : ""); + static std::mutex mtx{}; + mutex_lock lock{mtx}; + + const auto *val = std::getenv(variable.c_str()); + auto ret = std::string(val == nullptr ? "" : val); + return ret; #endif } @@ -253,8 +259,11 @@ void get_local_time_now(struct tm &local_time) { #ifdef _WIN32 localtime_s(&local_time, &now); #else + static std::mutex mtx{}; + mutex_lock lock{mtx}; + const auto *tmp = std::localtime(&now); - if (tmp) { + if (tmp != nullptr) { memcpy(&local_time, tmp, sizeof(local_time)); } #endif @@ -264,18 +273,19 @@ auto get_next_available_port(std::uint16_t first_port, std::uint16_t &available_port) -> bool { using namespace boost::asio; using ip::tcp; - boost::system::error_code ec; + boost::system::error_code error_code; do { io_service svc; - tcp::acceptor a(svc); - a.open(tcp::v4(), ec) || a.bind({tcp::v4(), first_port}, ec); - } while (ec && (first_port++ < 65535u)); + tcp::acceptor acceptor(svc); + acceptor.open(tcp::v4(), error_code) || + acceptor.bind({tcp::v4(), first_port}, error_code); + } while (error_code && (first_port++ < 65535U)); - if (not ec) { + if (not error_code) { available_port = first_port; } - return not ec; + return not error_code; } auto get_time_now() -> std::uint64_t { @@ -305,41 +315,44 @@ auto reset_curl(CURL *curl_handle) -> CURL * { } auto retryable_action(const std::function &action) -> bool { + static constexpr const auto retry_count = 20U; + auto succeeded = false; - for (std::uint8_t i = 0u; not(succeeded = action()) && (i < 20u); i++) { + for (std::uint8_t i = 0U; not(succeeded = action()) && (i < retry_count); + i++) { std::this_thread::sleep_for(100ms); } return succeeded; } void spin_wait_for_mutex(std::function complete, - std::condition_variable &cv, std::mutex &mtx, + std::condition_variable &cond, std::mutex &mtx, const std::string &text) { while (not complete()) { - unique_mutex_lock l(mtx); + unique_mutex_lock lock(mtx); if (not complete()) { if (not text.empty()) { /* event_system::instance().raise(__FUNCTION__, * "spin_wait_for_mutex", text); */ } - cv.wait_for(l, 1s); + cond.wait_for(lock, 1s); } - l.unlock(); + lock.unlock(); } } -void spin_wait_for_mutex(bool &complete, std::condition_variable &cv, +void spin_wait_for_mutex(bool &complete, std::condition_variable &cond, std::mutex &mtx, const std::string &text) { while (not complete) { - unique_mutex_lock l(mtx); + unique_mutex_lock lock(mtx); if (not complete) { if (not text.empty()) { /* event_system::instance().raise(__FUNCTION__, * "spin_wait_for_mutex", text); */ } - cv.wait_for(l, 1s); + cond.wait_for(lock, 1s); } - l.unlock(); + lock.unlock(); } } } // namespace repertory::utils